diff --git a/apps/website/content/docs/react/ag-ui/guides/client-tools.mdx b/apps/website/content/docs/react/ag-ui/guides/client-tools.mdx index c21aaed2f..b9f2e4dce 100644 --- a/apps/website/content/docs/react/ag-ui/guides/client-tools.mdx +++ b/apps/website/content/docs/react/ag-ui/guides/client-tools.mdx @@ -19,7 +19,7 @@ The [React conversation walkthrough](/docs/react/langgraph/concepts/conversation ## Execute a typed browser catalog -Choose **Run**. Each of the six example prompts sends its question, or type your own and choose **Send**. **get_weather** returns a fixed simulated reading. **slow_status_check** waits three seconds and supports **Stop**. **weather_card** renders a local reading and follows up. **weather_snapshot** renders the same reading without an automatic follow-up. **confirm_booking** waits in an approval card for **Confirm booking** or a cancel action. **Plan a trip** checks the weather and asks for the booking in one turn. No tool fetches real weather or makes a real reservation. +Choose **Run**. Each of the six example prompts sends its question, or type your own and choose **Send**. **get_weather** returns a fixed simulated reading. **slow_status_check** waits three seconds and supports **Stop**. **weather_card** renders a local reading and follows up. **weather_snapshot** renders the same reading without an automatic follow-up. **confirm_booking** waits in a card below its call for **Confirm booking** or a cancel action. **Plan a trip** checks the weather and asks for the booking in one turn. No tool fetches real weather or makes a real reservation. @@ -39,7 +39,9 @@ The native session owns the catalog and physical continuations. The app owns a l -A fictional booking resolves a browser promise through your explicit decision. This is separate from a native agent pause/resume. The booking waits in the `` approval slot as an **ApprovalCard** at the end of the transcript, and the composer asks you to answer it first. An answer the application admits stays in the transcript as a one-line record. Once resolved, stopped, replaced, or unmounted, the card cannot make another decision. +A fictional booking resolves a browser promise through your explicit decision. This is separate from a native agent pause/resume. The booking is an **ask** tool from `@threadplane/react/chat`: `createClientTools` turns it into a function tool whose handler waits for the answer, and `` draws its **ApprovalCard** below the message's tool calls while the call keeps its running row. The application checks the arguments and the native call before the question is asked. The composer asks you to answer the booking first, and an answer the booking admits stays in the transcript as a one-line record. Once resolved, stopped, replaced, or unmounted, the card cannot make another decision. + + When a turn requests more than one call, the graph writes a **todos** list to its state, and the session publishes it as the plan. While the trip waits for the booking, the running tool group lists the plan's pending steps, such as **Summarize the results**. diff --git a/apps/website/content/docs/react/chat/guides/client-tools.mdx b/apps/website/content/docs/react/chat/guides/client-tools.mdx index 417138ea0..9e52ce8e4 100644 --- a/apps/website/content/docs/react/chat/guides/client-tools.mdx +++ b/apps/website/content/docs/react/chat/guides/client-tools.mdx @@ -51,9 +51,11 @@ Ask for **Trip** in the local preview. The model calls `get_weather` and `confir ## Booking decisions and ownership -A fictional booking is an approval, so it follows the same pattern as the other examples: its `ApprovalCard` waits at the end of the transcript (through the `approval` slot of `Chat`) with named actions, `Confirm booking` and `Don't book`, and the composer reads "Answer the approval to continue". These actions stay available while chat is busy. Parallel cards resolve independently, including identical summaries, and only the first takes focus. An answered booking leaves a one-line record in the transcript, **Approved: Booking** or **Declined: Booking**, through `approvalRecords`. `Chat` returns focus to the composer once no booking waits and the composer is enabled again. A booking that **Stop** revokes was never answered, so it leaves no record. Completed weather panels and booking records remain visible until **New conversation**. +A fictional booking is an ask tool: `confirm_booking` is declared with `ask`, and `Chat` draws its `ApprovalCard` through `clientTools`. The card waits below the message's tool calls with named actions, `Confirm booking` and `Don't book`, and the composer reads "Answer the booking to continue". The call keeps its row in the tool group, so the group's progress, **Stop** and plan stay visible while the booking waits. These actions stay available while chat is busy. Parallel cards resolve independently, including identical summaries, and only the oldest takes focus. An answered booking leaves a one-line record in the transcript, **Approved: Booking** or **Declined: Booking**, through `approvalRecords`. `Chat` returns focus to the composer once no booking waits and the composer is enabled again. A booking that **Stop** revokes was never answered, so it leaves no record. Completed weather panels and booking records remain visible until **New conversation**. -React borrows snapshots through useAgent and renders `Chat` and `ApprovalCard`. The application exposes itself to `Chat` as a core session through `application.agent`: its run status, the thread's messages and tool calls, and the declared plan. Admission stays with the application, which sets `disabled` on `Chat` while it cannot accept a message. Weather details and booking summaries render as literal text. This preview uses authored functions and example-owned presentation; it does not implement a general view-tool or ask-tool registry or infer schemas from TypeScript. + + +React borrows snapshots through useAgent and renders `Chat`. The application exposes itself to `Chat` as a core session through `application.agent`: its run status, the thread's messages and tool calls, and the declared plan. It passes the booking ask tool as `application.clientTools`. Admission stays with the application, which sets `disabled` on `Chat` while it cannot accept a message. Weather details and booking summaries render as literal text, and the booking handler checks its arguments before the card is shown. The other tools are authored functions with example-owned presentation; this preview does not implement render-only view tools or infer schemas from TypeScript. @@ -65,6 +67,47 @@ The existing shared backend is used by default. A developer LangGraph target can +## Ask the person in the transcript + +An ask tool is a function tool that the person answers. Declare it with `ask`, collect the declarations with `createClientTools`, pass `clientTools.tools` to the session, and pass the whole object to `Chat` as `clientTools`. While a call waits, your view is drawn below the message's tool calls, and the call keeps its row and its place in the tool group. The value you pass to `answer` becomes the tool result, the view goes, and focus returns to the composer. + +~~~tsx +import type { AgentSession } from '@threadplane/core'; +import { Chat, ask, createClientTools } from '@threadplane/react/chat'; + +const clientTools = createClientTools({ + pick_day: ask<{ days: string[] }, { day: string }>({ + description: 'Ask which itinerary day to plan.', + parameters: { + type: 'object', + properties: { days: { type: 'array', items: { type: 'string' } } }, + required: ['days'], + }, + render: ({ args, answer }) => ( +
+ Which day? + {args.days.map((day) => ( + + ))} +
+ ), + }), +}); + +// Create the session once, with these tools beside any other function tools: +// createSession({ ...options, tools: { ...clientTools.tools, ...otherTools } }) + +export function Planner({ session }: { session: AgentSession }) { + return ; +} +~~~ + +Create `clientTools` once, outside the component, like the session. Only the first answer counts, and **Stop** cancels a waiting call. `Chat` shows these views only when `clientTools` is set, and `renderToolCall` still decides how the call itself is drawn. Arguments are not validated before `render` runs, so check them in your view. A call observed from saved history has no handler waiting and keeps its built-in row. With `MessageList`, pass `useClientToolCalls(clientTools)` as `renderToolCallPrompt`. + +The session does not tell a handler its call ID. A waiting call is paired with the transcript call of the same name and equal arguments, and a view always answers the arguments it was drawn with. Render-only view tools, schema-derived argument types, and a continuation limit are not part of this API. + ## Build from source ~~~sh diff --git a/apps/website/src/lib/docs-example-code.spec.ts b/apps/website/src/lib/docs-example-code.spec.ts index 3d0dcaa97..dcb0216ff 100644 --- a/apps/website/src/lib/docs-example-code.spec.ts +++ b/apps/website/src/lib/docs-example-code.spec.ts @@ -282,7 +282,7 @@ it('renders every native AG-UI Client Tools include from exact registered source if (!context) throw new Error('Missing native AG-UI Client Tools source context'); const article = readFileSync(join(WORKSPACE_ROOT, 'apps/website/content/docs/react/ag-ui/guides/client-tools.mdx'), 'utf8'); const includes = includesIn(article); - expect(includes).toHaveLength(10); + expect(includes).toHaveLength(11); for (const include of includes) { const asset = resolveExampleFile(include.file, context); expect(context.sources[asset]).toBe(readFileSync(join(WORKSPACE_ROOT, asset), 'utf8')); diff --git a/cockpit/ag-ui/client-tools/react/README.md b/cockpit/ag-ui/client-tools/react/README.md index 8232324cc..bef352eea 100644 --- a/cockpit/ag-ui/client-tools/react/README.md +++ b/cockpit/ag-ui/client-tools/react/README.md @@ -4,7 +4,7 @@ Five browser tools demonstrate simulated weather, a cancellable status check, an ## Execute a typed browser catalog -Choose **Run**. Each of the six example prompts sends its question, or type your own and choose **Send**. **get_weather** returns a fixed simulated reading. **slow_status_check** waits three seconds and supports **Stop**. **weather_card** renders a local reading and follows up. **weather_snapshot** renders the same reading without an automatic follow-up. **confirm_booking** waits in an approval card for **Confirm booking** or a cancel action. **Plan a trip** checks the weather and asks for the booking in one turn. No tool fetches real weather or makes a real reservation. +Choose **Run**. Each of the six example prompts sends its question, or type your own and choose **Send**. **get_weather** returns a fixed simulated reading. **slow_status_check** waits three seconds and supports **Stop**. **weather_card** renders a local reading and follows up. **weather_snapshot** renders the same reading without an automatic follow-up. **confirm_booking** waits in a card below its call for **Confirm booking** or a cancel action. **Plan a trip** checks the weather and asks for the booking in one turn. No tool fetches real weather or makes a real reservation. Source: `cockpit/ag-ui/client-tools/react/src/tools.ts` @@ -24,7 +24,9 @@ Source: `cockpit/ag-ui/client-tools/react/src/projection.ts` Source: `cockpit/ag-ui/client-tools/react/src/weather-card.tsx` -A fictional booking resolves a browser promise through your explicit decision. This is separate from a native agent pause/resume. The booking waits in the `` approval slot as an **ApprovalCard** at the end of the transcript, and the composer asks you to answer it first. An answer the application admits stays in the transcript as a one-line record. Once resolved, stopped, replaced, or unmounted, the card cannot make another decision. +A fictional booking resolves a browser promise through your explicit decision. This is separate from a native agent pause/resume. The booking is an **ask** tool from `@threadplane/react/chat`: `createClientTools` turns it into a function tool whose handler waits for the answer, and `` draws its **ApprovalCard** below the message's tool calls while the call keeps its running row. The application checks the arguments and the native call before the question is asked. The composer asks you to answer the booking first, and an answer the booking admits stays in the transcript as a one-line record. Once resolved, stopped, replaced, or unmounted, the card cannot make another decision. + +Source: `cockpit/ag-ui/client-tools/react/src/booking.tsx` When a turn requests more than one call, the graph writes a **todos** list to its state, and the session publishes it as the plan. While the trip waits for the booking, the running tool group lists the plan's pending steps, such as **Summarize the results**. diff --git a/cockpit/ag-ui/client-tools/react/e2e/client-tools.spec.ts b/cockpit/ag-ui/client-tools/react/e2e/client-tools.spec.ts index 7eec4690b..062188e8b 100644 --- a/cockpit/ag-ui/client-tools/react/e2e/client-tools.spec.ts +++ b/cockpit/ag-ui/client-tools/react/e2e/client-tools.spec.ts @@ -66,12 +66,11 @@ test('a planned trip shows Chat progress with plan steps, waits for the booking, const group = conversation.locator('.tp-tool-activity-group[data-active="true"]'); await expect(group).toBeVisible(); await expect(group.getByRole('button', {name:'Stop', exact:true})).toBeVisible(); - // The booking waits in Chat's approval slot at the end of the transcript. - const card = conversation.locator('.tp-approval-card'); - await expect(card).toContainText('Waiting for your approval.'); + // The booking is an ask tool: its card sits below the tool calls, and the call keeps its running group. + const card = conversation.locator('[data-tool-prompt] .tp-approval-card'); await expect(card).toContainText('Fictional trip to Portland'); await expect(page.getByRole('button', {name:'Confirm booking'})).toBeFocused(); - await expect(page.getByLabel('Message', {exact:true})).toHaveAttribute('placeholder', 'Answer the approval to continue'); + await expect(page.getByLabel('Message', {exact:true})).toHaveAttribute('placeholder', 'Answer the booking to continue'); causal(await records(request), 1); // Opened while running: a static count, then the plan's pending steps after the calls. await group.locator('.tp-tool-activity-group__details > summary').click(); diff --git a/cockpit/ag-ui/client-tools/react/src/app.spec.tsx b/cockpit/ag-ui/client-tools/react/src/app.spec.tsx index b9fdfd658..e21c6fd3e 100644 --- a/cockpit/ag-ui/client-tools/react/src/app.spec.tsx +++ b/cockpit/ag-ui/client-tools/react/src/app.spec.tsx @@ -1,3 +1,4 @@ +import type { ReactElement } from 'react'; import { createSession } from '@threadplane/ag-ui'; import type { RunAgentInput } from '@ag-ui/client'; import type { AgentSnapshot } from '@threadplane/core'; @@ -12,6 +13,7 @@ import { } from '@testing-library/react'; import { afterEach, expect, it, vi } from 'vitest'; import { ClientToolsDemo } from './app'; +import { createBookingTools, type BookingTools } from './booking'; import type { ClientToolsApplicationSnapshot } from './application'; const mocks = vi.hoisted(() => ({ create: vi.fn() })); vi.mock('./connection', () => ({ createConnectedApplication: mocks.create })); @@ -38,7 +40,6 @@ function fixture( threadId: null, native: undefined, views: [], - bookings: [], busy: false, canSubmit: true, activity: 'idle', @@ -54,6 +55,7 @@ function fixture( toolCalls: [], ...view, } as AgentSnapshot; + const tools = createBookingTools(); const listeners = new Set<() => void>(); const subscribe = (notify: () => void) => { listeners.add(notify); @@ -67,7 +69,7 @@ function fixture( submit: vi.fn(), stop: vi.fn(), newConversation: vi.fn(), - respond: vi.fn(() => true), + clientTools: tools, dispose: vi.fn(), agent: { getSnapshot: () => agentSnapshot, @@ -180,54 +182,51 @@ it('renders native text literally and local evidence under its call', () => { expect(screen.getByText('Delivery: unsent')).toBeTruthy(); expect(screen.getByText('Simulated weather')).toBeTruthy(); }); -it('a pending booking waits in the approval card, dispatches its exact token and records the answer', () => { - const booking = { - ownerGeneration: 1, - callId: 'c', - assistantMessageId: 'a', - sourceRunId: 'r', - summary: 'Fictional table', - token: 'owned', - status: 'pending' as const, - }; - const f = fixture( - { busy: true, canSubmit: false, bookings: [booking] }, - transcript({ - id: 'c', - name: 'confirm_booking', - args: { summary: 'Fictional table' }, - status: 'running', - }) - ); +/** Starts the booking question the way a session calls its tool. */ +const ask = (tools: BookingTools, context: { signal: AbortSignal }) => + Promise.resolve(tools.tools.confirm_booking.handler({ summary: 'Fictional table' }, context)); +const running = transcript({ + id: 'c', + name: 'confirm_booking', + args: { summary: 'Fictional table' }, + status: 'running', +}); +it('a waiting booking shows its card below the call, answers the tool and records the answer', async () => { + const f = fixture({ busy: true, canSubmit: false }, running); + expect(screen.queryByRole('button', { name: 'Confirm booking' })).toBeNull(); + let result!: Promise<{ confirmed: boolean }>; + act(() => { + result = ask(f.app.clientTools, + { signal: new AbortController().signal } + ); + }); expect(screen.getByText('Fictional table')).toBeTruthy(); + expect(screen.getByText('Waiting for your fictional booking decision…')).toBeTruthy(); expect( screen .getByRole('textbox', { name: 'Message' }) .getAttribute('placeholder') - ).toBe('Answer the approval to continue'); + ).toBe('Answer the booking to continue'); fireEvent.click(screen.getByRole('button', { name: "Don't book" })); - expect(f.app.respond).toHaveBeenCalledWith('owned', false); + expect(await result).toEqual({ confirmed: false }); expect(screen.getByText('Declined: Booking')).toBeTruthy(); - f.update({ bookings: [{ ...booking, status: 'resolved', confirmed: false }] }); expect(screen.queryByRole('button', { name: 'Confirm booking' })).toBeNull(); }); -it('a decision the application refuses leaves no record, and an aborted booking clears the card', () => { - const booking = { - ownerGeneration: 1, - callId: 'c', - assistantMessageId: 'a', - sourceRunId: 'r', - summary: 'Fictional table', - token: 'owned', - status: 'pending' as const, - }; - const f = fixture({ busy: true, canSubmit: false, bookings: [booking] }); - f.app.respond.mockReturnValueOnce(false); - fireEvent.click(screen.getByRole('button', { name: 'Confirm booking' })); - expect(f.app.respond).toHaveBeenCalledWith('owned', true); - expect(screen.queryByText('Approved: Booking')).toBeNull(); - f.update({ bookings: [{ ...booking, status: 'aborted' }] }); +it('a stopped booking clears the card and leaves no record', async () => { + const f = fixture({ busy: true, canSubmit: false }, running); + const abort = new AbortController(); + let result!: Promise<{ confirmed: boolean }>; + act(() => { + result = ask(f.app.clientTools, + abort + ); + }); + const rejected = expect(result).rejects.toMatchObject({ name: 'AbortError' }); + expect(screen.getByRole('button', { name: 'Confirm booking' })).toBeTruthy(); + act(() => abort.abort()); + await rejected; expect(screen.queryByRole('button', { name: 'Confirm booking' })).toBeNull(); + expect(screen.queryByText(/^(Approved|Declined): Booking$/)).toBeNull(); }); it('busy input exposes Stop and prevents New, while blocked idle asks for explicit New', () => { const f = fixture({ busy: true, canSubmit: false }); @@ -318,9 +317,15 @@ it('actual owned pending booking loses all authority on React unmount without na await waitFor(() => expect(screen.getByRole('button', { name: 'Confirm booking' })).toBeTruthy() ); - const token = app.getSnapshot().bookings[0].token; + const card = app.clientTools.render({ + id: 'unmount-call', + name: 'confirm_booking', + args: { summary: 'Fictional only' }, + status: 'running', + }) as ReactElement<{ answer(result: { confirmed: boolean }): boolean }>; rendered.unmount(); await done; - expect(app.respond(token, true)).toBe(false); + expect(card.props.answer({ confirmed: true })).toBe(false); + expect(app.clientTools.getSnapshot()).toEqual([]); expect(fetch).toHaveBeenCalledOnce(); }); diff --git a/cockpit/ag-ui/client-tools/react/src/app.tsx b/cockpit/ag-ui/client-tools/react/src/app.tsx index faa1ebadf..c936d5d7e 100644 --- a/cockpit/ag-ui/client-tools/react/src/app.tsx +++ b/cockpit/ag-ui/client-tools/react/src/app.tsx @@ -3,17 +3,17 @@ import { ExampleLayout } from '../../../../shared/react-example'; import { useCallback, useEffect, useState } from 'react'; import { useAgent } from '@threadplane/react'; import { - ApprovalCard, Chat, + usePendingClientToolCalls, type ApprovalRecordEntry, type ToolActivityInfo, } from '@threadplane/react/chat'; +import { BookingAnswered } from './booking'; import { createConnectedApplication, type ClientToolsConnection, } from './connection'; import { WeatherCard } from './weather-card'; -import type { BookingPanel } from './tools'; const prompts = Object.freeze([ { label: 'Weather result', @@ -63,15 +63,17 @@ export function ClientToolsDemo({ useEffect(() => { setRecords([]); }, [snapshot.viewGeneration]); - function decide(row: BookingPanel, confirmed: boolean) { - const afterId = application.agent.getSnapshot().messages.at(-1)?.id; - // Record only a decision the application admitted. - if (!application.respond(row.token, confirmed)) return; - setRecords((previous) => [ - ...previous, - { afterId, verdict: confirmed ? 'approved' : 'declined', label: 'Booking' }, - ]); - } + // The card reports an answer the booking admitted. + const answered = useCallback( + (confirmed: boolean) => { + const afterId = application.agent.getSnapshot().messages.at(-1)?.id; + setRecords((previous) => [ + ...previous, + { afterId, verdict: confirmed ? 'approved' : 'declined', label: 'Booking' }, + ]); + }, + [application] + ); // Local execution evidence and a validated weather reading under each call. const { views } = snapshot; const renderToolResult = useCallback( @@ -94,11 +96,11 @@ export function ClientToolsDemo({ }, [views] ); - const pending = snapshot.bookings.filter((row) => row.status === 'pending'); + const asked = usePendingClientToolCalls(application.clientTools).length > 0; const status = snapshot.busy ? snapshot.activity === 'replacing' ? 'Starting a new conversation…' - : pending.length + : asked ? 'Waiting for your fictional booking decision…' : 'Running client tools…' : !snapshot.canSubmit @@ -142,37 +144,20 @@ export function ClientToolsDemo({ {/* Chat owns the transcript, the progress view and the composer. The - application is its session; a booking waits at the end of the - transcript through the approval slot, which also hints the composer - and returns focus to it once the composer is enabled again. + application is its session; `clientTools` draws a waiting booking + below its call, which keeps its row and progress, and returns focus + to the composer once the booking is answered and it is enabled again. */} + ( - decide(row, true) }, - { id: 'cancel', label: "Don't book", onSelect: () => decide(row, false) }, - ]} - > -

{row.summary}

-

No real reservation is made.

-
- )) - : undefined - } inputFooter={ <> {snapshot.error &&

{snapshot.error}

} @@ -180,6 +165,7 @@ export function ClientToolsDemo({ } /> +
); } diff --git a/cockpit/ag-ui/client-tools/react/src/application.spec.ts b/cockpit/ag-ui/client-tools/react/src/application.spec.ts index 0b2967177..00eb48db4 100644 --- a/cockpit/ag-ui/client-tools/react/src/application.spec.ts +++ b/cockpit/ag-ui/client-tools/react/src/application.spec.ts @@ -1,3 +1,4 @@ +import type { ReactElement } from 'react'; import { createServer, type ServerResponse } from 'node:http'; import { once } from 'node:events'; import type { AddressInfo } from 'node:net'; @@ -17,6 +18,17 @@ afterEach(() => { for (const dispose of disposals.splice(0)) dispose(); vi.restoreAllMocks(); }); +type App = ReturnType; +/** The booking card `Chat` would draw for the running call, if a booking waits for it. */ +function bookingCard(app: App, id: string, summary: string) { + return app.clientTools.render({ + id, name: 'confirm_booking', args: { summary }, status: 'running', + }) as ReactElement<{ answer(result: { confirmed: boolean }): boolean }> | undefined; +} +/** Answers that card; false when no booking waits or it was already answered or revoked. */ +function answerBooking(app: App, id: string, summary: string, confirmed: boolean) { + return bookingCard(app, id, summary)?.props.answer({ confirmed }) ?? false; +} async function until(check: () => boolean) { for (let i = 0; i < 200; i++) { if (check()) return; @@ -168,19 +180,16 @@ describe('application with actual native owner and synthetic SDK SSE', () => { const done = f.app.submit('Booking'); await f.next(); f.finish(0, 'confirm_booking', { summary: 'Fictional table' }); - await until(() => f.app.getSnapshot().bookings.length === 1); - const panel = f.app.getSnapshot().bookings[0]; - expect(panel).toMatchObject({ - callId: 'call-0', - assistantMessageId: 'assistant-0', - sourceRunId: f.requests[0].body.runId, - summary: 'Fictional table', - status: 'pending', - }); - expect(f.app.respond('wrong', confirmed)).toBe(false); + await until(() => f.app.clientTools.getSnapshot().length === 1); + expect(f.app.clientTools.getSnapshot()).toEqual([ + { name: 'confirm_booking', args: { summary: 'Fictional table' } }, + ]); + expect( + f.app.agent.getSnapshot().toolCalls.find((call) => call.id === 'call-0') + ).toMatchObject({ name: 'confirm_booking', status: 'running' }); expect(f.requests).toHaveLength(1); - expect(f.app.respond(panel.token, confirmed)).toBe(true); - expect(f.app.respond(panel.token, !confirmed)).toBe(false); + expect(answerBooking(f.app, 'call-0', 'Fictional table', confirmed)).toBe(true); + expect(answerBooking(f.app, 'call-0', 'Fictional table', !confirmed)).toBe(false); await f.next(1); expect(f.requests[1].body.threadId).toBe(f.requests[0].body.threadId); expect(f.requests[1].body.runId).not.toBe(f.requests[0].body.runId); @@ -264,7 +273,7 @@ describe('application with actual native owner and synthetic SDK SSE', () => { await f.next(); f.finish(0, 'confirm_booking', { summary: 'Fictional' }); await done; - expect(f.app.getSnapshot().bookings).toHaveLength(0); + expect(f.app.clientTools.getSnapshot()).toHaveLength(0); expect(invoked).not.toHaveBeenCalled(); expect(f.app.getSnapshot().canSubmit).toBe(false); expect(f.requests).toHaveLength(1); @@ -274,20 +283,18 @@ describe('application with actual native owner and synthetic SDK SSE', () => { const done = f.app.submit('Booking'); await f.next(); f.finish(0, 'confirm_booking', { summary: 'Fictional' }); - await until(() => f.app.getSnapshot().bookings.length > 0); - const old = f.app.getSnapshot().bookings[0]; + await until(() => f.app.clientTools.getSnapshot().length > 0); + const old = bookingCard(f.app, 'call-0', 'Fictional'); + if (!old) throw new Error('Missing booking card'); const thread = f.app.getSnapshot().threadId; await f.app.stop(); await done; - expect(f.app.respond(old.token, false)).toBe(false); - expect(f.app.getSnapshot().bookings[0]).toMatchObject({ - status: 'aborted', - }); + expect(old.props.answer({ confirmed: false })).toBe(false); + expect(f.app.clientTools.getSnapshot()).toEqual([]); await f.app.newConversation(); expect(f.app.getSnapshot()).toMatchObject({ threadId: null, native: undefined, - bookings: [], views: [], error: null, canSubmit: true, @@ -296,7 +303,8 @@ describe('application with actual native owner and synthetic SDK SSE', () => { const next = f.app.submit('new'); await f.next(1); expect(f.app.getSnapshot().threadId).not.toBe(thread); - expect(f.app.respond(old.token, true)).toBe(false); + expect(old.props.answer({ confirmed: true })).toBe(false); + expect(f.app.clientTools.getSnapshot()).toEqual([]); f.finish(1); await next; }); @@ -488,7 +496,7 @@ it.each(['ambiguous', 'wrong-run', 'missing', 'invalid-args'] as const)( await f.next(1); f.finish(1); await done; - expect(f.app.getSnapshot().bookings).toHaveLength(0); + expect(f.app.clientTools.getSnapshot()).toHaveLength(0); expect(f.app.getSnapshot().canSubmit).toBe(false); } ); @@ -641,8 +649,8 @@ export function checkApplicationTypes( const state = app.getSnapshot(); // @ts-expect-error App snapshots are readonly. state.busy = false; - // @ts-expect-error Booking observations are readonly arrays. - state.bookings.push({}); + // @ts-expect-error Waiting bookings are a readonly array. + app.clientTools.getSnapshot().push({ name: 'confirm_booking', args: {} }); // @ts-expect-error Message projections are readonly arrays. state.views.push({}); for (const call of state.native?.clientTools.calls ?? []) { @@ -725,10 +733,8 @@ it('actual native SDK over loopback HTTP preserves terminal result and owns exac requests[1].body.messages.filter((message) => message.role === 'tool') ).toHaveLength(1); finish(1, 'confirm_booking', { summary: 'HTTP fictional table' }); - await until(() => app.getSnapshot().bookings.length === 1); - const panel = app.getSnapshot().bookings[0]; - expect(panel.callId).toBe('http-call-1'); - expect(app.respond(panel.token, true)).toBe(true); + await until(() => app.clientTools.getSnapshot().length === 1); + expect(answerBooking(app, 'http-call-1', 'HTTP fictional table', true)).toBe(true); await until(() => requests.length === 3); expect(requests[2].body.threadId).toBe(requests[1].body.threadId); expect(requests[2].body.runId).not.toBe(requests[1].body.runId); diff --git a/cockpit/ag-ui/client-tools/react/src/application.ts b/cockpit/ag-ui/client-tools/react/src/application.ts index 37ad5db00..5c4a06777 100644 --- a/cockpit/ag-ui/client-tools/react/src/application.ts +++ b/cockpit/ag-ui/client-tools/react/src/application.ts @@ -12,8 +12,8 @@ import { createClientToolsController, validateBookingArguments, type BookingInvocation, - type BookingPanel, } from './tools'; +import { createBookingTools } from './booking'; import { projectAgentSnapshot, projectClientToolViews, @@ -28,7 +28,6 @@ export interface ClientToolsApplicationSnapshot { readonly threadId: string | null; readonly native: NativeSnapshot | undefined; readonly views: readonly ClientToolMessageView[]; - readonly bookings: readonly BookingPanel[]; readonly busy: boolean; readonly canSubmit: boolean; readonly activity: 'idle' | 'running' | 'replacing'; @@ -48,10 +47,11 @@ export function createClientToolsApplication(options: { closed: boolean; unsafe: boolean; release?: () => void; - releaseTools?: () => void; }; type Operation = { readonly controller: AbortController; owner?: Primary }; const listeners = new Set<() => void>(); + // One booking ask for every conversation; each conversation's controller guards and revokes its own calls. + const bookings = createBookingTools(); let primary: Primary | undefined, operation: Operation | undefined; let generation = 0, disposed = false; @@ -59,7 +59,6 @@ export function createClientToolsApplication(options: { threadId: null, native: undefined, views: Object.freeze([]), - bookings: Object.freeze([]), busy: false, canSubmit: true, activity: 'idle', @@ -114,7 +113,6 @@ export function createClientToolsApplication(options: { if (owner.closed) return; owner.closed = true; cleanup(() => owner.release?.()); - cleanup(() => owner.releaseTools?.()); owner.tools.dispose(); const session = owner.session; if (session) { @@ -162,8 +160,7 @@ export function createClientToolsApplication(options: { if (!native || !valid()) return; const views = projectClientToolViews(native, valid); if (!valid()) return; - const bookings = owner.tools.getSnapshot().bookings; - return valid() ? { native, views, bookings } : undefined; + return valid() ? { native, views } : undefined; } function observe(owner: Primary) { const admitted = operation; @@ -191,7 +188,10 @@ export function createClientToolsApplication(options: { if (!valid()) return; const threadId = crypto.randomUUID(); if (!valid()) return; - const tools = createClientToolsController(() => booking(owner)); + const tools = createClientToolsController( + () => booking(owner), + bookings.tools.confirm_booking + ); const owner: Primary = { threadId, generation: ++generation, @@ -215,13 +215,6 @@ export function createClientToolsApplication(options: { cleanup(() => session.dispose()); return; } - const releaseTools = tools.subscribe(() => observe(owner)); - owner.releaseTools = releaseTools; - if (!current(owner, admitted)) { - cleanup(releaseTools); - close(owner); - return; - } const subscribe = session.subscribe; if (!current(owner, admitted)) return; const release = subscribe.call(session, () => observe(owner)); @@ -384,7 +377,6 @@ export function createClientToolsApplication(options: { canSubmit: false, activity: 'idle', outcome: 'aborted', - ...(owner ? { bookings: owner.tools.getSnapshot().bookings } : {}), error: 'The operation stopped. Start a new conversation.', }); } @@ -408,8 +400,7 @@ export function createClientToolsApplication(options: { threadId: null, native: undefined, views: Object.freeze([]), - bookings: Object.freeze([]), - busy: false, + busy: false, canSubmit: true, activity: 'idle', outcome: null, @@ -417,13 +408,6 @@ export function createClientToolsApplication(options: { viewGeneration: snapshot.viewGeneration + 1, }); } - function respond(token: string, decision: boolean) { - const owner = primary, - admitted = operation; - if (!owner || !admitted || !current(owner, admitted) || !snapshot.busy) - return false; - return owner.tools.respond(token, decision); - } function dispose(): Promise { if (disposed) return Promise.resolve(); disposed = true; @@ -461,8 +445,9 @@ export function createClientToolsApplication(options: { agent, submit, stop, + /** Pass to `Chat` as `clientTools`; a waiting booking is drawn from here. */ + clientTools: bookings, newConversation, - respond, dispose, }); } diff --git a/cockpit/ag-ui/client-tools/react/src/booking.tsx b/cockpit/ag-ui/client-tools/react/src/booking.tsx new file mode 100644 index 000000000..7cdf0e4ef --- /dev/null +++ b/cockpit/ag-ui/client-tools/react/src/booking.tsx @@ -0,0 +1,70 @@ +import { createContext, useContext } from 'react'; +import { + ApprovalCard, + ask, + createClientTools, + type AskTool, + type AskToolViewProps, + type ClientTools, +} from '@threadplane/react/chat'; +import type { BookingArguments, BookingDecision } from './tools'; + +export type BookingTools = ClientTools<{ + confirm_booking: AskTool; +}>; + +/** Tells the application about an answer the card admitted; the card works without it. */ +export const BookingAnswered = createContext<(confirmed: boolean) => void>( + () => undefined +); + +function BookingCard({ + args, + answer, + autoFocus, +}: AskToolViewProps & { + readonly autoFocus: boolean; +}) { + const answered = useContext(BookingAnswered); + // Only the first answer counts; a stopped booking admits none. + const decide = (confirmed: boolean) => { + if (answer({ confirmed })) answered(confirmed); + }; + return ( + decide(true) }, + { id: 'cancel', label: "Don't book", onSelect: () => decide(false) }, + ]} + > +

{args.summary}

+

No real reservation is made.

+
+ ); +} + +/** The booking question as an ask tool: the model calls it and the person answers in the transcript. */ +export function createBookingTools(): BookingTools { + const tools: BookingTools = createClientTools({ + confirm_booking: ask({ + // The controller in tools.ts sends its own description and schema; this one draws the card. + description: 'Ask the user to confirm a fictional booking. No real reservation is made.', + parameters: { + type: 'object', + properties: { summary: { type: 'string', minLength: 1 } }, + required: ['summary'], + additionalProperties: false, + }, + // Of parallel bookings only the oldest takes focus. + render: (props) => ( + + ), + }), + }); + return tools; +} diff --git a/cockpit/ag-ui/client-tools/react/src/tools.spec.ts b/cockpit/ag-ui/client-tools/react/src/tools.spec.ts index d93925d2a..e1b7e2841 100644 --- a/cockpit/ag-ui/client-tools/react/src/tools.spec.ts +++ b/cockpit/ag-ui/client-tools/react/src/tools.spec.ts @@ -1,25 +1,37 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; -import { createClientToolsController, type BookingInvocation } from './tools'; +import { createClientToolsController, type BookingArguments, type BookingAsk, type BookingDecision, type BookingInvocation } from './tools'; const weather = { location: 'Denver', temperatureF: 68, conditions: 'Sunny', humidity: 55, windMph: 8 }; const invocation: BookingInvocation = { ownerGeneration: 1, callId: 'call-real', assistantMessageId: 'assistant-real', sourceRunId: 'run-real', summary: 'Fictional Denver visit', }; +/** Stands in for the ask tool: records each question and waits like the real one. */ +function fakeAsk() { + const asks: { args: BookingArguments; signal: AbortSignal; resolve(decision: BookingDecision): void }[] = []; + const ask: BookingAsk = { + description: 'Ask', + handler: (args, { signal }) => new Promise((resolve, reject) => { + asks.push({ args, signal, resolve }); + signal.addEventListener('abort', () => reject(new DOMException('Client tool cancelled.', 'AbortError')), { once: true }); + }), + }; + return { ask, asks }; +} function setup() { let current: BookingInvocation | undefined = invocation; const read = vi.fn(() => current); - const controller = createClientToolsController(read); + const { ask, asks } = fakeAsk(); + const controller = createClientToolsController(read, ask); const abort = new AbortController(); - return { controller, abort, read, setCurrent(value: BookingInvocation | undefined) { current = value; } }; + return { controller, abort, read, asks, setCurrent(value: BookingInvocation | undefined) { current = value; } }; } afterEach(() => vi.useRealTimers()); describe('native five-tool business catalog', () => { - it('constructs and subscribes inertly and exposes exactly five authored schemas/policies', () => { - const { controller, read } = setup(); - const unsubscribe = controller.subscribe(() => undefined); - expect(read).not.toHaveBeenCalled(); + it('constructs inertly and exposes exactly five authored schemas/policies', () => { + const { controller, read, asks } = setup(); + expect(read).not.toHaveBeenCalled(); expect(asks).toHaveLength(0); expect(Object.keys(controller.tools)).toEqual(['get_weather', 'slow_status_check', 'weather_card', 'weather_snapshot', 'confirm_booking']); for (const tool of Object.values(controller.tools)) { expect(tool.parameters).toMatchObject({ type: 'object', additionalProperties: false }); @@ -30,7 +42,7 @@ describe('native five-tool business catalog', () => { expect(controller.tools.slow_status_check.parameters).toMatchObject({ required: [], properties: { label: { default: 'status check' } } }); expect(controller.tools.weather_card.parameters).toEqual(controller.tools.weather_snapshot.parameters); expect(controller.tools.weather_card.parameters).toMatchObject({ required: Object.keys(weather) }); - unsubscribe(); controller.dispose(); + controller.dispose(); }); it('returns asynchronous simulated data isolated across invocations and descriptors', async () => { const { controller, abort } = setup(); @@ -48,7 +60,6 @@ describe('native five-tool business catalog', () => { const { controller, abort } = setup(); expect(await controller.tools.weather_card.handler(weather, abort)).toEqual({ displayed: true }); expect(await controller.tools.weather_snapshot.handler(weather, abort)).toEqual({ displayed: true }); - expect(controller.getSnapshot()).toEqual({ bookings: [] }); }); it.each([null, [], Object.create({ location: 'Denver' }), { location: '' }, { location: ' ' }, { location: 7 }, { location: 'Denver', extra: true }, Object.defineProperty({}, 'location', { get() { throw new Error('getter ran'); }, enumerable: true })])('rejects malformed location arguments case %# without reading getters', async (input: unknown) => { const { controller, abort } = setup(); @@ -120,147 +131,83 @@ describe('owned slow delay', () => { }); }); -describe('identity-bound fictional booking decisions', () => { - it('does not reconstruct the same native booking identity after cancellation', async () => { - const { controller, abort } = setup(); - const result = controller.tools.confirm_booking.handler({ summary: invocation.summary }, abort); +describe('fictional booking guarded by its native call', () => { + const booking = { summary: invocation.summary }; + it('asks with the checked summary and returns each answer', async () => { + for (const confirmed of [true, false]) { + const { controller, abort, asks } = setup(); + const result = controller.tools.confirm_booking.handler(booking, abort); + await vi.waitFor(() => expect(asks).toHaveLength(1)); + expect(asks[0].args).toEqual(booking); + asks[0].resolve({ confirmed }); + expect(await result).toEqual({ confirmed }); + } + }); + it('does not ask the same native booking again after cancellation', async () => { + const { controller, abort, asks } = setup(); + const result = controller.tools.confirm_booking.handler(booking, abort); const cancelled = expect(result).rejects.toMatchObject({ name: 'AbortError' }); abort.abort(); await cancelled; - await expect(controller.tools.confirm_booking.handler({ summary: invocation.summary }, new AbortController())).rejects.toThrow('Booking invocation unavailable'); - expect(controller.getSnapshot().bookings).toHaveLength(1); + await expect(controller.tools.confirm_booking.handler(booking, new AbortController())).rejects.toThrow('Booking invocation unavailable'); + expect(asks).toHaveLength(1); }); - it('does not grant a fresh controller authority to an old controller token', async () => { - const old = setup(); const fresh = setup(); - const oldResult = old.controller.tools.confirm_booking.handler({ summary: invocation.summary }, old.abort); - const cancelled = expect(oldResult).rejects.toMatchObject({ name: 'AbortError' }); - const oldToken = old.controller.getSnapshot().bookings[0].token; - old.controller.dispose(); await cancelled; - const result = fresh.controller.tools.confirm_booking.handler({ summary: invocation.summary }, fresh.abort); - const newToken = fresh.controller.getSnapshot().bookings[0].token; - expect(fresh.controller.respond(oldToken, true)).toBe(false); - expect(fresh.controller.respond(newToken, false)).toBe(true); - expect(await result).toEqual({ confirmed: false }); - }); - it('revokes acquisition when pending notification changes the actual current call', async () => { - const { controller, abort, setCurrent } = setup(); - controller.subscribe(() => setCurrent(undefined)); - const result = controller.tools.confirm_booking.handler({ summary: invocation.summary }, abort); - await expect(result).rejects.toMatchObject({ name: 'AbortError' }); - expect(controller.getSnapshot().bookings[0].status).toBe('aborted'); + it('refuses a duplicate running booking and asks again for a new native call', async () => { + const { controller, abort, asks, setCurrent } = setup(); + const first = controller.tools.confirm_booking.handler(booking, abort); + const rejected = expect(first).rejects.toMatchObject({ name: 'AbortError' }); + await expect(controller.tools.confirm_booking.handler(booking, abort)).rejects.toThrow('Booking invocation unavailable'); + abort.abort(); await rejected; + setCurrent({ ...invocation, ownerGeneration: 2, callId: 'fresh-call' }); + const fresh = controller.tools.confirm_booking.handler(booking, new AbortController()); + await vi.waitFor(() => expect(asks).toHaveLength(2)); + asks[1].resolve({ confirmed: true }); + expect(await fresh).toEqual({ confirmed: true }); }); - it('does not expose authority from malformed identity accessors or argument getters', async () => { - const { controller, abort } = setup(); + it('does not ask for malformed arguments or a malformed native identity', async () => { + const { controller, abort, asks } = setup(); const malformed: unknown[] = [null, { summary: '' }, { summary: invocation.summary, extra: 1 }, Object.defineProperty({}, 'summary', { get() { throw new Error('getter ran'); } })]; for (const input of malformed) { // @ts-expect-error hostile runtime booking arguments await expect(controller.tools.confirm_booking.handler(input, abort)).rejects.toThrow('Invalid tool arguments'); } - const invalid = createClientToolsController(() => Object.defineProperty({ ...invocation }, 'callId', { get() { throw new Error('getter ran'); } })); - await expect(invalid.tools.confirm_booking.handler({ summary: invocation.summary }, abort)).rejects.toThrow('Booking invocation unavailable'); - expect(invalid.getSnapshot().bookings).toEqual([]); - }); - it('cannot acquire a duplicate running booking and cancelled controls stay distinct after a new generation', async () => { - const { controller, abort, setCurrent } = setup(); - const first = controller.tools.confirm_booking.handler({ summary: invocation.summary }, abort); - const rejected = expect(first).rejects.toMatchObject({ name: 'AbortError' }); - const old = controller.getSnapshot().bookings[0]; - await expect(controller.tools.confirm_booking.handler({ summary: invocation.summary }, abort)).rejects.toThrow('Booking invocation unavailable'); - abort.abort(); await rejected; - setCurrent({ ...invocation, ownerGeneration: 2, callId: 'fresh-call' }); - const fresh = controller.tools.confirm_booking.handler({ summary: invocation.summary }, new AbortController()); - const next = controller.getSnapshot().bookings[1]; - expect(next.token).not.toBe(old.token); expect(controller.respond(old.token, true)).toBe(false); - expect(controller.respond(next.token, true)).toBe(true); expect(await fresh).toEqual({ confirmed: true }); - }); - it.each([true, false])('settles only the first explicit boolean %s and retains frozen visible result', async (decision) => { - const { controller, abort } = setup(); - const result = controller.tools.confirm_booking.handler({ summary: invocation.summary }, abort); - const pending = controller.getSnapshot().bookings[0]; - expect(pending).toMatchObject({ ...invocation, status: 'pending' }); - expect(Object.isFrozen(pending)).toBe(true); - expect(Object.isFrozen(controller.getSnapshot().bookings)).toBe(true); - expect(Object.isFrozen(controller.getSnapshot())).toBe(true); - expect(controller.respond('wrong-token', decision)).toBe(false); - expect(controller.respond(pending.token, decision)).toBe(true); - expect(controller.respond(pending.token, !decision)).toBe(false); - expect(await result).toEqual({ confirmed: decision }); - expect(controller.getSnapshot().bookings[0]).toMatchObject({ status: 'resolved', confirmed: decision }); - expect(Object.isFrozen(controller.getSnapshot().bookings[0])).toBe(true); - }); - it.each([undefined, { ...invocation, summary: 'Different summary' }])('rejects unavailable or mismatched acquisition without publishing %j', async (current) => { - const { controller, abort, setCurrent } = setup(); setCurrent(current); - const notify = vi.fn(); controller.subscribe(notify); - await expect(controller.tools.confirm_booking.handler({ summary: invocation.summary }, abort)).rejects.toThrow('Booking invocation unavailable'); - expect(controller.getSnapshot().bookings).toEqual([]); expect(notify).not.toHaveBeenCalled(); - }); - it.each(['ownerGeneration', 'callId', 'assistantMessageId', 'sourceRunId', 'summary'] as const)('refuses stale %s identities', async (field) => { - const { controller, abort, setCurrent } = setup(); - const result = controller.tools.confirm_booking.handler({ summary: invocation.summary }, abort); - const rejected = expect(result).rejects.toMatchObject({ name: 'AbortError' }); - const pending = controller.getSnapshot().bookings[0]; - setCurrent(field === 'ownerGeneration' ? { ...invocation, ownerGeneration: 2 } : { ...invocation, [field]: 'other' }); - expect(controller.respond(pending.token, true)).toBe(false); - await rejected; - setCurrent(invocation); - expect(controller.respond(pending.token, true)).toBe(false); - expect(controller.getSnapshot().bookings[0]).toMatchObject({ status: 'aborted' }); - expect(controller.getSnapshot().bookings[0]).not.toHaveProperty('confirmed'); - }); - it.each(['missing', 'throwing'] as const)('irreversibly revokes an owned token when the accessor is %s', async (mode) => { - const { controller, abort, read, setCurrent } = setup(); - const remove = vi.spyOn(abort.signal, 'removeEventListener'); - const result = controller.tools.confirm_booking.handler({ summary: invocation.summary }, abort); - const rejected = expect(result).rejects.toMatchObject({ name: 'AbortError' }); - const token = controller.getSnapshot().bookings[0].token; - if (mode === 'missing') setCurrent(undefined); - else read.mockImplementationOnce(() => { throw new Error('native accessor failed'); }); - expect(controller.respond(token, true)).toBe(false); - await rejected; - setCurrent(invocation); - expect(controller.respond(token, false)).toBe(false); - expect(controller.getSnapshot().bookings[0]).toMatchObject({ status: 'aborted' }); - expect(controller.getSnapshot().bookings[0]).not.toHaveProperty('confirmed'); - expect(remove).toHaveBeenCalledWith('abort', expect.any(Function)); - }); - it('rejects ambiguous acquisition represented by the native accessor returning undefined', async () => { - const { controller, abort, setCurrent } = setup(); setCurrent(undefined); - await expect(controller.tools.confirm_booking.handler({ summary: invocation.summary }, abort)).rejects.toThrow('Booking invocation unavailable'); - expect(controller.getSnapshot().bookings).toEqual([]); - }); - it.each(['abort', 'dispose'] as const)('revokes before another listener can respond during pending publication: %s', async (action) => { - const { controller, abort } = setup(); - controller.subscribe(() => { if (action === 'abort') abort.abort(); else controller.dispose(); }); - const later = vi.fn(() => controller.respond(controller.getSnapshot().bookings[0].token, true)); - controller.subscribe(later); - await expect(controller.tools.confirm_booking.handler({ summary: invocation.summary }, abort)).rejects.toMatchObject({ name: 'AbortError' }); - const row = controller.getSnapshot().bookings[0]; - expect(row.status).toBe('aborted'); expect(row).not.toHaveProperty('confirmed'); - expect(controller.respond(row.token, false)).toBe(false); - expect(later.mock.results.every((entry) => entry.value !== true)).toBe(true); + expect(asks).toHaveLength(0); + const other = fakeAsk(); + const invalid = createClientToolsController(() => Object.defineProperty({ ...invocation }, 'callId', { get() { throw new Error('getter ran'); } }), other.ask); + await expect(invalid.tools.confirm_booking.handler(booking, abort)).rejects.toThrow('Booking invocation unavailable'); + expect(other.asks).toHaveLength(0); + }); + it.each([undefined, { ...invocation, summary: 'Different summary' }])('does not ask when the native call is unavailable or mismatched: %j', async (current) => { + const { controller, abort, asks, setCurrent } = setup(); setCurrent(current); + await expect(controller.tools.confirm_booking.handler(booking, abort)).rejects.toThrow('Booking invocation unavailable'); + expect(asks).toHaveLength(0); + }); + it.each(['ownerGeneration', 'sourceRunId'] as const)('does not ask for an unsafe %s identity', async (field) => { + const { controller, abort, asks, setCurrent } = setup(); + setCurrent({ ...invocation, [field]: field === 'ownerGeneration' ? -1 : ' ' }); + await expect(controller.tools.confirm_booking.handler(booking, abort)).rejects.toThrow('Booking invocation unavailable'); + expect(asks).toHaveLength(0); + }); + it('reports a throwing native accessor as unavailable, and its cancellation as cancelled', async () => { + const { controller, abort, asks, read } = setup(); + read.mockImplementationOnce(() => { throw new Error('native accessor failed'); }); + await expect(controller.tools.confirm_booking.handler(booking, abort)).rejects.toThrow('Booking invocation unavailable'); + read.mockImplementationOnce(() => { abort.abort(); return invocation; }); + await expect(controller.tools.confirm_booking.handler(booking, abort)).rejects.toMatchObject({ name: 'AbortError' }); + expect(asks).toHaveLength(0); + }); + it.each(['abort', 'dispose'] as const)('revokes a waiting booking on %s, and nothing is asked afterwards', async (action) => { + const { controller, abort, asks } = setup(); + const result = controller.tools.confirm_booking.handler(booking, abort); + const cancelled = expect(result).rejects.toMatchObject({ name: 'AbortError' }); + await vi.waitFor(() => expect(asks).toHaveLength(1)); + expect(asks[0].signal.aborted).toBe(false); + if (action === 'abort') abort.abort(); else controller.dispose(); + expect(asks[0].signal.aborted).toBe(true); + await cancelled; + asks[0].resolve({ confirmed: true }); + await expect(controller.tools.confirm_booking.handler(booking, abort)).rejects.toMatchObject({ name: 'AbortError' }); + expect(asks).toHaveLength(1); controller.dispose(); controller.dispose(); }); - it('rechecks cancellation caused by the accessor and by resolved publication', async () => { - const abort = new AbortController(); let cancelOnRead = false; - const controller = createClientToolsController(() => { if (cancelOnRead) abort.abort(); return invocation; }); - const result = controller.tools.confirm_booking.handler({ summary: invocation.summary }, abort); - const rejected = expect(result).rejects.toMatchObject({ name: 'AbortError' }); - const token = controller.getSnapshot().bookings[0].token; cancelOnRead = true; - expect(controller.respond(token, true)).toBe(false); await rejected; - const next = setup(); - next.controller.subscribe(() => { if (next.controller.getSnapshot().bookings[0]?.status === 'resolved') next.abort.abort(); }); - const pending = next.controller.tools.confirm_booking.handler({ summary: invocation.summary }, next.abort); - const cancelled = expect(pending).rejects.toMatchObject({ name: 'AbortError' }); - expect(next.controller.respond(next.controller.getSnapshot().bookings[0].token, true)).toBe(false); - await cancelled; expect(next.controller.getSnapshot().bookings[0].status).toBe('aborted'); - }); - it('refuses nonboolean decisions without settling and removes booking abort listener on explicit resolution', async () => { - const { controller, abort } = setup(); const remove = vi.spyOn(abort.signal, 'removeEventListener'); - const result = controller.tools.confirm_booking.handler({ summary: invocation.summary }, abort); - const token = controller.getSnapshot().bookings[0].token; - // @ts-expect-error runtime control input must be boolean - expect(controller.respond(token, 'yes')).toBe(false); - expect(controller.respond(token, false)).toBe(true); expect(await result).toEqual({ confirmed: false }); - expect(remove).toHaveBeenCalledWith('abort', expect.any(Function)); - }); }); diff --git a/cockpit/ag-ui/client-tools/react/src/tools.ts b/cockpit/ag-ui/client-tools/react/src/tools.ts index c5136ab01..af51a0fdf 100644 --- a/cockpit/ag-ui/client-tools/react/src/tools.ts +++ b/cockpit/ag-ui/client-tools/react/src/tools.ts @@ -16,12 +16,9 @@ export interface BookingInvocation { readonly sourceRunId: string; readonly summary: string; } -export type BookingPanel = BookingInvocation & { readonly token: string } & ( - | { readonly status: 'pending' } - | { readonly status: 'resolved'; readonly confirmed: boolean } - | { readonly status: 'aborted' } -); -export interface ClientToolsSnapshot { readonly bookings: readonly BookingPanel[] } +export interface BookingDecision { confirmed: boolean } +/** The booking question as a function tool whose handler waits for the person's answer. */ +export type BookingAsk = FunctionTool; function argumentsRecord(input: unknown, keys: readonly string[]): object { if (!input || typeof input !== 'object' || Array.isArray(input)) throw new Error('Invalid tool arguments'); @@ -76,33 +73,20 @@ function sameInvocation(left: BookingInvocation, right: BookingInvocation): bool return left.ownerGeneration === right.ownerGeneration && left.callId === right.callId && left.assistantMessageId === right.assistantMessageId && left.sourceRunId === right.sourceRunId && left.summary === right.summary; } -/** Owns business promises only. The native session supplies every protocol identity. */ -export function createClientToolsController(readCurrentBooking: () => BookingInvocation | undefined) { +/** + * Owns business promises only. The native session supplies every protocol identity, and `ask` + * (the booking declared in booking.tsx) waits for the person's answer. + */ +export function createClientToolsController(readCurrentBooking: () => BookingInvocation | undefined, ask: BookingAsk) { let disposed = false; - let snapshot: ClientToolsSnapshot = Object.freeze({ bookings: Object.freeze([]) }); - const listeners = new Set<() => void>(); const cancellations = new Set<() => void>(); - const pending = new Map void; - readonly finish: (decision: boolean) => boolean; - }>(); + // One native call is asked once, even after it was cancelled. + const asked: BookingInvocation[] = []; + // Disposal revokes a waiting booking, like Stop. + const disposal = new AbortController(); function active(signal: AbortSignal) { if (disposed || signal.aborted) throw aborted(); } - function publish(row: BookingPanel) { - const existing = snapshot.bookings.some((entry) => entry.token === row.token); - snapshot = Object.freeze({ bookings: Object.freeze(existing - ? snapshot.bookings.map((entry) => entry.token === row.token ? row : entry) - : [...snapshot.bookings, row]) }); - const publication = snapshot; - for (const notify of [...listeners]) { - if (disposed || snapshot !== publication) break; - // An observer cannot strand a tool promise or prevent other owned cleanup. - try { notify(); } catch { /* Consumers own their notification errors. */ } - } - } function current(signal: AbortSignal): BookingInvocation | undefined { active(signal); const value = readCurrentBooking(); @@ -172,74 +156,26 @@ export function createClientToolsController(readCurrentBooking: () => BookingInv description: 'Ask for an explicit fictional booking decision. No real reservation is made.', followUp: true, parameters: Object.freeze({ type: 'object', additionalProperties: false, required: Object.freeze(['summary']), properties: Object.freeze({ summary: Object.freeze({ type: 'string', minLength: 1 }) }) }), + // Check the arguments and the native call first, so the card only ever shows an admitted booking. async handler(input: BookingArguments, { signal }) { active(signal); const { summary } = validateBookingArguments(input); active(signal); let identity: BookingInvocation | undefined; try { identity = current(signal); } catch (error) { if (signal.aborted || disposed) throw aborted(); throw new Error('Booking invocation unavailable', { cause: error }); } - if (!identity || identity.summary !== summary || snapshot.bookings.some((entry) => sameInvocation(entry, identity))) { + if (!identity || identity.summary !== summary || asked.some((entry) => sameInvocation(entry, identity))) { throw new Error('Booking invocation unavailable'); } - const captured = identity; - // This UUID is app control authority, never a native call/message/run identity. - const token = crypto.randomUUID(); - const row: BookingPanel = Object.freeze({ ...captured, token, status: 'pending' }); - const result = new Promise<{ confirmed: boolean }>((resolve, reject) => { - let finished = false; - const cleanup = () => { pending.delete(token); cancellations.delete(cancel); signal.removeEventListener('abort', cancel); }; - const cancel = () => { - if (finished) return; - finished = true; cleanup(); - publish(Object.freeze({ ...captured, token, status: 'aborted' })); reject(aborted()); - }; - pending.set(token, { identity: captured, signal, cancel, finish(decision) { - if (finished || disposed || signal.aborted) return false; - // Consume authority before notification; reentrant controls cannot win twice. - pending.delete(token); - publish(Object.freeze({ ...captured, token, status: 'resolved', confirmed: decision })); - if (finished || disposed || signal.aborted) { cancel(); return false; } - // Notifications may revoke the native call without aborting its signal yet. - let latest: BookingInvocation | undefined; - try { latest = current(signal); } catch { cancel(); return false; } - if (!latest || !sameInvocation(captured, latest)) { cancel(); return false; } - finished = true; cleanup(); resolve({ confirmed: decision }); return true; - } }); - cancellations.add(cancel); signal.addEventListener('abort', cancel, { once: true }); - publish(row); - if (disposed || signal.aborted) cancel(); - if (!finished) { - let latest: BookingInvocation | undefined; - try { latest = current(signal); } catch { cancel(); } - if (!latest || !sameInvocation(captured, latest)) cancel(); - } - }); - // Observe rejection immediately even when native consumers attach after publication. - void result.catch(() => undefined); - return result; + asked.push(identity); + return ask.handler({ summary }, { signal: AbortSignal.any([signal, disposal.signal]) }); }, - } satisfies FunctionTool), + } satisfies BookingAsk), }); return Object.freeze({ tools, - getSnapshot: () => snapshot, - subscribe(notify: () => void) { - if (disposed) return () => undefined; - listeners.add(notify); return () => { listeners.delete(notify); }; - }, - respond(token: string, decision: boolean): boolean { - const request = pending.get(token); - if (!request || disposed || request.signal.aborted || typeof decision !== 'boolean') return false; - let latest: BookingInvocation | undefined; - try { latest = current(request.signal); } catch { request.cancel(); return false; } - if (!latest || !sameInvocation(request.identity, latest) || disposed || request.signal.aborted) { - request.cancel(); return false; - } - return request.finish(decision); - }, dispose() { if (disposed) return; - disposed = true; listeners.clear(); + disposed = true; for (const cancel of [...cancellations]) cancel(); - pending.clear(); + disposal.abort(); }, }); } diff --git a/cockpit/ag-ui/client-tools/react/src/tools.type-test.ts b/cockpit/ag-ui/client-tools/react/src/tools.type-test.ts index ecefde333..0712c1764 100644 --- a/cockpit/ag-ui/client-tools/react/src/tools.type-test.ts +++ b/cockpit/ag-ui/client-tools/react/src/tools.type-test.ts @@ -1,11 +1,13 @@ import { createSession } from '@threadplane/ag-ui'; import type { ClientToolCall } from '@threadplane/ag-ui'; import type { ToolContracts } from '@threadplane/core/tools'; -import { createClientToolsController } from './tools'; +import { createClientToolsController, type BookingAsk } from './tools'; + +declare const ask: BookingAsk; /** Compile-only checks against the actual native generic declaration boundary. */ export function checkToolDeclarations() { - const controller = createClientToolsController(() => undefined); + const controller = createClientToolsController(() => undefined, ask); const session = createSession({ threadId: 'compile-only', url: 'http://127.0.0.1:1', interruptMode: 'native' }, controller.tools); const calls = session.getSnapshot().clientTools.calls; const typed: readonly ClientToolCall>[] = calls; diff --git a/cockpit/langgraph/client-tools/react/README.md b/cockpit/langgraph/client-tools/react/README.md index cdba38a32..c49bf1b6e 100644 --- a/cockpit/langgraph/client-tools/react/README.md +++ b/cockpit/langgraph/client-tools/react/README.md @@ -2,9 +2,9 @@ This experimental frontend shares the existing Python `client-tools` assistant with Angular. Five explicitly authored browser tools provide simulated weather, a cancellable slow status check, finalized weather panels, a snapshot without model follow-up, and fictional booking confirmation. No real weather or booking service is contacted. -Native React `MessageList`, `ChatInput`, and `ApprovalCard` observe one confirmed application-owned session with `useAgent`. Literal weather panels and completed booking outcomes remain visible. Parallel booking requests have separate application-owned decision tokens; these are presentation identities, not runtime call IDs. Pending decisions remain available while the composer is busy. Stop and disposal immediately revoke their authority. +Native React `Chat` observes one confirmed application-owned session with `useAgent`. Literal weather panels and completed booking records remain visible. The booking is an ask tool (`ask` and `createClientTools` in `src/booking.tsx`): `Chat` draws its `ApprovalCard` below the message's tool calls through `clientTools`, and the answer becomes the tool result. Parallel booking requests are answered independently. Pending decisions remain available while the composer is busy. Stop and disposal immediately revoke them. -The neutral session executes the authored catalog. Normal tools produce same-thread model follow-up; a standalone `weather_snapshot` writes its acknowledgement into the same thread without another model run. Mixed batches follow the neutral runtime's batch policy. This preview does not implement a general view-tool or ask-tool registry. +The neutral session executes the authored catalog. Normal tools produce same-thread model follow-up; a standalone `weather_snapshot` writes its acknowledgement into the same thread without another model run. Mixed batches follow the neutral runtime's batch policy. This preview does not implement render-only view tools. Thread creation and execution use zero SDK retries. Stop, failures, uncertain creation, unexpected root pauses, unknown tools, and unresolved tool observations require New conversation. Page exit disposes the owner. A new conversation clears panels and transcript. diff --git a/cockpit/langgraph/client-tools/react/e2e/client-tools.spec.ts b/cockpit/langgraph/client-tools/react/e2e/client-tools.spec.ts index ce059b099..279ac36db 100644 --- a/cockpit/langgraph/client-tools/react/e2e/client-tools.spec.ts +++ b/cockpit/langgraph/client-tools/react/e2e/client-tools.spec.ts @@ -62,14 +62,14 @@ test('mixed snapshot and normal tools follow up as one batch with exact result i expect(entries.filter((entry) => entry.path.endsWith('/state'))).toHaveLength(0); expect(runs[1].body.input!.messages.map((message) => message.tool_call_id).sort()).toEqual(['snapshot-1', 'weather-1']); }); -test('identical parallel bookings wait in the transcript, confirm and decline independently, and leave records', async ({ page, request }) => { +test('identical parallel bookings wait below their calls, confirm and decline independently, and leave records', async ({ page, request }) => { await send(page, 'Bookings'); const conversation = page.getByRole('region', { name: 'Conversation' }); await expect(conversation.getByRole('button', { name: 'Confirm booking' })).toHaveCount(2); await expect(conversation.locator('.tp-approval-card').first()).toContainText('Waiting for your approval.'); // The first card takes focus; the second does not steal it. await expect(page.getByRole('button', { name: 'Confirm booking' }).nth(0)).toBeFocused(); - await expect(page.getByLabel('Message', { exact: true })).toHaveAttribute('placeholder', 'Answer the approval to continue'); + await expect(page.getByLabel('Message', { exact: true })).toHaveAttribute('placeholder', 'Answer the booking to continue'); await page.getByRole('button', { name: 'Confirm booking' }).nth(0).click(); await expect(conversation.getByText('Approved: Booking', { exact: true })).toBeVisible(); await expect(page.getByLabel('Message', { exact: true })).toBeDisabled(); @@ -217,12 +217,12 @@ test('a planned trip shows Chat progress with plan steps, waits for the booking, await expect(group).toBeVisible(); await expect(group.locator('.tp-tool-activity-group__elapsed')).toHaveText(/^\d+s$/); await expect(group.getByRole('button', { name: 'Stop', exact: true })).toBeVisible(); - // The booking waits in Chat's approval slot at the end of the transcript. - const card = conversation.locator('.tp-approval-card'); + // The booking waits below the group, which keeps its call, progress and Stop. + const card = conversation.locator('[data-tool-prompt] .tp-approval-card'); await expect(card).toContainText('Waiting for your approval.'); await expect(card).toContainText('Fictional trip to Portland'); await expect(page.getByRole('button', { name: 'Confirm booking' })).toBeFocused(); - await expect(page.getByLabel('Message', { exact: true })).toHaveAttribute('placeholder', 'Answer the approval to continue'); + await expect(page.getByLabel('Message', { exact: true })).toHaveAttribute('placeholder', 'Answer the booking to continue'); // Opened while running: a static count, then the plan's pending steps after the calls. await group.locator('.tp-tool-activity-group__details > summary').click(); await expect(group.locator('.tp-tool-activity-group__details > summary')).toContainText('Working · 1 of 2 done'); diff --git a/cockpit/langgraph/client-tools/react/src/app.spec.tsx b/cockpit/langgraph/client-tools/react/src/app.spec.tsx index bd0f91a65..6275ca13b 100644 --- a/cockpit/langgraph/client-tools/react/src/app.spec.tsx +++ b/cockpit/langgraph/client-tools/react/src/app.spec.tsx @@ -1,5 +1,6 @@ import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react'; import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import { completeDelivery } from '@threadplane/core'; import { createClientToolsApplication, type ClientToolsSession, type ClientToolCatalog } from './application'; import { ClientToolsDemo } from './app'; @@ -12,12 +13,22 @@ const statusOf = (view: ReturnType) => beforeEach(() => factory.mockReset()); function setup() { let tools!: ClientToolCatalog; + type State = ReturnType; + let state: State = { status: 'idle', messages: [], toolCalls: [], interrupts: [] }; const session: ClientToolsSession = { - getSnapshot: () => ({ status: 'idle', messages: [], toolCalls: [], interrupts: [] }), + getSnapshot: () => state, subscribe: () => () => undefined, submit: vi.fn(async (_text, options) => { await tools.weather_card.handler({ location: '', temperatureF: 68, conditions: 'Sunny', humidity: 55, windMph: 8 }, { signal: options!.signal! }); - await tools.confirm_booking.handler({ summary: ' Fictional booking' }, { signal: options!.signal! }); + // The session reports the call it is about to run, then runs its handler. + const call = { id: 'booking', name: 'confirm_booking', args: { summary: ' Fictional booking' } }; + state = { + ...state, + messages: [{ id: 'request', role: 'assistant', content: 'One booking to confirm.', delivery: completeDelivery('run', 'success'), toolCallIds: [call.id] }], + toolCalls: [{ ...call, status: 'running' }], + } as State; + const result = await tools.confirm_booking.handler(call.args, { signal: options!.signal! }); + state = { ...state, toolCalls: [{ ...call, status: 'complete', result }] } as State; return 'success'; }), stop: vi.fn(async () => undefined), dispose: vi.fn(async () => undefined), @@ -61,16 +72,20 @@ it('keeps browser decisions enabled while chat is busy and retains literal compl expect(h.view.getByText('No weather panels yet.')).toBeTruthy(); expect(h.view.queryByText('Approved: Booking')).toBeNull(); }); -it('waits for the booking at the end of the transcript, names both actions and hints the composer', async () => { +it('draws the waiting booking below its call, names both actions and hints the composer', async () => { const h = setup(); await h.send(); const conversation = h.view.getByRole('region', { name: 'Conversation' }); - const card = conversation.querySelector('.tp-approval-card') as HTMLElement; + const card = conversation.querySelector('[data-tool-prompt="booking"] .tp-approval-card') as HTMLElement; expect(card).toBeTruthy(); + // The call keeps its own row above the card. + const row = conversation.querySelector('.tp-tool-activity') as HTMLElement; + expect(row.textContent).toContain('confirm_booking'); + expect(row.compareDocumentPosition(card) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); expect(card.textContent).toContain('Waiting for your approval.'); expect(card.textContent).toContain(' Fictional booking'); expect([...card.querySelectorAll('button')].map((button) => button.textContent)).toEqual(['Confirm booking', "Don't book"]); expect(document.activeElement).toBe(h.view.getByRole('button', { name: 'Confirm booking' })); - expect(h.view.getByRole('textbox', { name: 'Message', exact: true }).getAttribute('placeholder')).toBe('Answer the approval to continue'); + expect(h.view.getByRole('textbox', { name: 'Message', exact: true }).getAttribute('placeholder')).toBe('Answer the booking to continue'); }); it('returns focus to the composer once the answered run completes', async () => { const h = setup(); await h.send(); diff --git a/cockpit/langgraph/client-tools/react/src/app.tsx b/cockpit/langgraph/client-tools/react/src/app.tsx index 3a4d262db..f3e772632 100644 --- a/cockpit/langgraph/client-tools/react/src/app.tsx +++ b/cockpit/langgraph/client-tools/react/src/app.tsx @@ -3,11 +3,11 @@ import { ExampleLayout } from '../../../../shared/react-example'; import { useEffect, useRef, useState } from 'react'; import { useAgent } from '@threadplane/react'; import { - ApprovalCard, Chat, + usePendingClientToolCalls, type ApprovalRecordEntry, } from '@threadplane/react/chat'; -import type { BookingPanel } from './tools'; +import { BookingAnswered } from './booking'; import { createConnectedApplication, type clientToolsConnection, @@ -28,11 +28,10 @@ export function ClientToolsDemo({ const snapshot = useAgent(application); // Answered bookings stay in the transcript as one-line records. const [records, setRecords] = useState([]); - const pending = snapshot.bookings.filter((row) => row.status === 'pending'); - function decide(row: BookingPanel, confirmed: boolean) { + const asked = usePendingClientToolCalls(application.clientTools).length > 0; + // The booking card reports only an answer it admitted. + function answered(confirmed: boolean) { const afterId = application.getSnapshot().rows.at(-1)?.id; - // Record only a decision the application admitted. - if (!application.decide(row, confirmed)) return; setRecords((previous) => [ ...previous, { afterId, verdict: confirmed ? 'approved' : 'declined', label: 'Booking' }, @@ -106,36 +105,19 @@ export function ClientToolsDemo({ {/* Chat owns the transcript, the progress view and the composer. The - application is its session; a booking waits at the end of the - transcript through the approval slot, which also hints the composer - and returns focus to it once the composer is enabled again. + application is its session; `clientTools` draws a waiting booking + below its call, which keeps its row and progress, and returns focus + to the composer once the booking is answered and it is enabled again. */} + ( - decide(row, true) }, - { id: 'cancel', label: "Don't book", onSelect: () => decide(row, false) }, - ]} - > -

{row.summary}

-

No real reservation is made.

-
- )) - : undefined - } inputFooter={ <> {snapshot.error &&

{snapshot.error}

} @@ -143,6 +125,7 @@ export function ClientToolsDemo({ } /> +
); } diff --git a/cockpit/langgraph/client-tools/react/src/application.spec.ts b/cockpit/langgraph/client-tools/react/src/application.spec.ts index 27daa11b0..f53e7fe19 100644 --- a/cockpit/langgraph/client-tools/react/src/application.spec.ts +++ b/cockpit/langgraph/client-tools/react/src/application.spec.ts @@ -1,7 +1,20 @@ -import { expect, it, vi } from 'vitest'; +import type { ReactElement } from 'react'; +import { cleanup, fireEvent, render } from '@testing-library/react'; +import { afterEach, expect, it, vi } from 'vitest'; import type { CompleteOutcome } from '@threadplane/core'; import { createClientToolsApplication, type ClientToolsSession, type ClientToolCatalog } from './application'; +afterEach(cleanup); +/** Answers the booking card `Chat` would draw; false when no booking waits. */ +function answerBooking(application: ReturnType, confirmed: boolean) { + const view = application.clientTools.render({ + id: 'booking', name: 'confirm_booking', args: { summary: 'Fictional booking' }, status: 'running', + }); + if (view === undefined) return false; + const card = render(view as ReactElement); + fireEvent.click(card.getByRole('button', { name: confirmed ? 'Confirm booking' : "Don't book" })); + return true; +} function deferred() { let resolve!: (value: T) => void; let reject!: (reason: unknown) => void; @@ -55,7 +68,7 @@ function setup() { it('starts empty and ignores blank text', async () => { const h = setup(); expect(h.application.getSnapshot()).toMatchObject({ - creation: 'idle', rows: [], weather: [], bookings: [], busy: false, + creation: 'idle', rows: [], weather: [], busy: false, canSubmit: true, outcome: null, error: null, }); await h.application.submit(' '); @@ -114,12 +127,12 @@ it('allows an owned booking decision while the command and composer remain busy' return 'success'; }); const { pending } = await h.start(); - const row = h.application.getSnapshot().bookings[0]; + expect(h.application.clientTools.getSnapshot()).toHaveLength(1); expect(h.application.getSnapshot()).toMatchObject({ busy: true, canSubmit: false }); - expect(h.application.decide(row, true)).toBe(true); - expect(h.application.decide(row, false)).toBe(false); + expect(answerBooking(h.application, true)).toBe(true); + expect(answerBooking(h.application, false)).toBe(false); await pending; - expect(h.application.getSnapshot().bookings[0].status).toBe('confirmed'); + expect(h.application.clientTools.getSnapshot()).toEqual([]); expect(h.application.getSnapshot().canSubmit).toBe(true); }); @@ -130,12 +143,12 @@ it('Stop aborts a pending browser decision and requires a new conversation', asy return 'success'; }); const { pending } = await h.start(); - const row = h.application.getSnapshot().bookings[0]; + expect(h.application.clientTools.getSnapshot()).toHaveLength(1); await h.application.stop(); await pending; - expect(h.application.decide(row, true)).toBe(false); + expect(answerBooking(h.application, true)).toBe(false); expect(h.application.getSnapshot()).toMatchObject({ busy: false, canSubmit: false, outcome: 'aborted' }); - expect(h.application.getSnapshot().bookings[0].status).toBe('aborted'); + expect(h.application.clientTools.getSnapshot()).toEqual([]); await h.application.submit('No replay'); expect(h.session.submit).toHaveBeenCalledTimes(1); }); @@ -283,10 +296,10 @@ it('disposal releases observation and fences both rows and decisions before asyn return 'success'; }); const { pending } = await h.start(); - const row = h.application.getSnapshot().bookings[0]; + expect(h.application.clientTools.getSnapshot()).toHaveLength(1); const disposal = h.application.dispose(); const snapshot = h.application.getSnapshot(); - expect(h.application.decide(row, true)).toBe(false); + expect(answerBooking(h.application, true)).toBe(false); h.replace({ messages: [{ id: 'late', role: 'assistant', content: 'Late', delivery: { generation: 'old', phase: 'complete' } }] }); expect(h.application.getSnapshot()).toBe(snapshot); expect(h.release).toHaveBeenCalledTimes(1); diff --git a/cockpit/langgraph/client-tools/react/src/application.ts b/cockpit/langgraph/client-tools/react/src/application.ts index e453bd376..fb56c7106 100644 --- a/cockpit/langgraph/client-tools/react/src/application.ts +++ b/cockpit/langgraph/client-tools/react/src/application.ts @@ -1,6 +1,6 @@ import type { AgentSession, AgentSnapshot, CompleteOutcome } from '@threadplane/core'; import { createMessageContent, type MessageRow } from '@threadplane/content/messages'; -import { createClientToolsController, type ClientToolsSnapshot, type BookingPanel } from './tools'; +import { createClientToolsController, type ClientToolsSnapshot } from './tools'; export interface ClientToolsSession extends Omit { getSnapshot(): AgentSnapshot & { @@ -17,7 +17,7 @@ export interface ClientToolsApplicationSnapshot extends ClientToolsSnapshot { readonly error: string | null; } -/** Owns one thread and the browser decisions admitted by its active command. */ +/** Owns one thread and the browser tools its active command runs. */ export function createClientToolsApplication(options: { readonly createThread: (signal: AbortSignal) => Promise; readonly sessionFactory: (threadId: string, tools: ClientToolCatalog) => ClientToolsSession; @@ -41,7 +41,7 @@ export function createClientToolsApplication(options: { // Typed sessions omit unknown tools, but retain their server call references. ) || !!state?.messages.some((message) => message.role === 'assistant' && message.toolCallIds?.some((id) => !state.toolCalls.some((call) => call.id === id)) - ) || controller.getSnapshot().bookings.some((row) => row.status === 'pending'); + ) || controller.clientTools.getSnapshot().length > 0; } /** The core session view `Chat` observes: run status from this owner, messages, calls and plan from the thread. */ const none = Object.freeze([]) as readonly never[]; @@ -72,6 +72,7 @@ export function createClientToolsApplication(options: { publish({ ...projection(), ...(blocked() ? { canSubmit: false } : {}) }); } const releaseTools = controller.subscribe(observe); + const releaseBookings = controller.clientTools.subscribe(observe); async function submit(text: string) { if (disposed || snapshot.busy || !snapshot.canSubmit || !text.trim()) return; if (blocked()) { observe(); return; } @@ -127,6 +128,7 @@ export function createClientToolsApplication(options: { operation = undefined; release?.(); releaseTools(); + releaseBookings(); controller.dispose(); content.dispose(); listeners.clear(); @@ -153,10 +155,8 @@ export function createClientToolsApplication(options: { getSnapshot: () => snapshot, subscribe, agent, + /** The booking ask tool for `Chat`; Stop and disposal revoke a waiting booking. */ + clientTools: controller.clientTools, submit, stop, dispose, - decide(row: BookingPanel, confirmed: boolean) { - if (disposed || !operation || operation.signal.aborted || !snapshot.busy) return false; - return controller.decide(row, confirmed); - }, }; } diff --git a/cockpit/langgraph/client-tools/react/src/booking.tsx b/cockpit/langgraph/client-tools/react/src/booking.tsx new file mode 100644 index 000000000..a71f84aed --- /dev/null +++ b/cockpit/langgraph/client-tools/react/src/booking.tsx @@ -0,0 +1,70 @@ +import { createContext, useContext } from 'react'; +import { + ApprovalCard, + ask, + createClientTools, + type AskTool, + type AskToolViewProps, + type ClientTools, +} from '@threadplane/react/chat'; + +export interface BookingArguments { summary: string } +export interface BookingDecision { confirmed: boolean } +export type BookingTools = ClientTools<{ + confirm_booking: AskTool; +}>; + +/** Tells the application about an answer the card admitted; the card works without it. */ +export const BookingAnswered = createContext<(confirmed: boolean) => void>( + () => undefined +); + +function BookingCard({ + args, + answer, + autoFocus, +}: AskToolViewProps & { + readonly autoFocus: boolean; +}) { + const answered = useContext(BookingAnswered); + // Only the first answer counts; a stopped booking admits none. + const decide = (confirmed: boolean) => { + if (answer({ confirmed })) answered(confirmed); + }; + return ( + decide(true) }, + { id: 'cancel', label: "Don't book", onSelect: () => decide(false) }, + ]} + > +

{args.summary}

+

No real reservation is made.

+
+ ); +} + +/** The booking question as an ask tool: the model calls it and the person answers in the transcript. */ +export function createBookingTools(): BookingTools { + const tools: BookingTools = createClientTools({ + confirm_booking: ask({ + description: 'Ask the user to confirm a fictional booking. No real reservation is made.', + parameters: { + type: 'object', + properties: { summary: { type: 'string', minLength: 1 } }, + required: ['summary'], + additionalProperties: false, + }, + // Of parallel bookings only the oldest takes focus. + render: (props) => ( + + ), + }), + }); + return tools; +} diff --git a/cockpit/langgraph/client-tools/react/src/tools.spec.ts b/cockpit/langgraph/client-tools/react/src/tools.spec.ts index f91e0270d..a1df5700d 100644 --- a/cockpit/langgraph/client-tools/react/src/tools.spec.ts +++ b/cockpit/langgraph/client-tools/react/src/tools.spec.ts @@ -1,3 +1,5 @@ +import type { ReactElement } from 'react'; +import { cleanup, fireEvent, render, within } from '@testing-library/react'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { createClientToolsController } from './tools'; @@ -6,7 +8,17 @@ const readings = { humidity: 55, windMph: 8, }; const context = () => ({ signal: new AbortController().signal }); -afterEach(() => vi.useRealTimers()); +afterEach(() => { vi.useRealTimers(); cleanup(); }); +type Controller = ReturnType; +/** The transcript call a session would report for a waiting booking. */ +const call = (id: string, summary: string) => + ({ id, name: 'confirm_booking', args: { summary }, status: 'running' }); +/** Draws the booking card `Chat` would show for that call. */ +function card(controller: Controller, id: string, summary: string) { + const view = controller.clientTools.render(call(id, summary)); + // Scoped to this card: several may be on the page. + return within(render(view as ReactElement).container); +} describe('authored client tools', () => { it('declares the complete five-tool catalog used by the shared graph', () => { @@ -73,7 +85,8 @@ describe('authored client tools', () => { const input = name === 'get_weather' ? { location: 'city' } : name === 'confirm_booking' ? { summary: 'booking' } : name === 'slow_status_check' ? {} : readings; const proxy = new Proxy(input, { getPrototypeOf(target) { abort.abort(); return Reflect.getPrototypeOf(target); } }); await expect(controller.tools[name].handler(proxy as never, { signal: abort.signal })).rejects.toMatchObject({ name: 'AbortError' }); - expect(controller.getSnapshot()).toMatchObject({ weather: [], bookings: [] }); + expect(controller.getSnapshot()).toMatchObject({ weather: [] }); + expect(controller.clientTools.getSnapshot()).toEqual([]); } ); @@ -89,98 +102,87 @@ describe('authored client tools', () => { expect(await controller.tools.weather_card.handler(Object.assign(Object.create(null), readings), context())).toEqual({ shown: true }); }); - it('keeps identical concurrent booking requests independent without runtime call IDs', async () => { + it('declares the booking as an ask tool whose card answers the call', async () => { + const controller = createClientToolsController(); + expect(controller.tools.confirm_booking).toMatchObject({ + description: expect.stringContaining('fictional booking'), + parameters: { type: 'object', required: ['summary'], additionalProperties: false }, + }); + const result = controller.tools.confirm_booking.handler({ summary: 'Fictional booking' }, context()); + expect(controller.clientTools.getSnapshot()).toEqual([ + { name: 'confirm_booking', args: { summary: 'Fictional booking' } }, + ]); + const view = card(controller, 'c1', 'Fictional booking'); + expect(view.getByText('Fictional booking')).toBeTruthy(); + expect(document.querySelector('b')).toBeNull(); + fireEvent.click(view.getByRole('button', { name: 'Confirm booking' })); + expect(await result).toEqual({ confirmed: true }); + expect(controller.clientTools.getSnapshot()).toEqual([]); + expect(controller.clientTools.render(call('c1', 'Fictional booking'))).toBeUndefined(); + }); + + it('keeps identical concurrent booking requests independent and focuses only the oldest', async () => { const controller = createClientToolsController(); const first = controller.tools.confirm_booking.handler({ summary: 'Same fictional booking' }, context()); const second = controller.tools.confirm_booking.handler({ summary: 'Same fictional booking' }, context()); - const [one, two] = controller.getSnapshot().bookings; - expect(one.id).not.toBe(two.id); - expect(one.summary).toBe(two.summary); - expect(controller.decide({ ...one }, true)).toBe(false); - expect(controller.decide(one, false)).toBe(true); - expect(controller.decide(one, true)).toBe(false); - expect(controller.decide(two, true)).toBe(true); + const one = card(controller, 'c1', 'Same fictional booking'); + const two = card(controller, 'c2', 'Same fictional booking'); + expect(document.activeElement).toBe(one.getByRole('button', { name: 'Confirm booking' })); + fireEvent.click(one.getByRole('button', { name: "Don't book" })); + fireEvent.click(one.getByRole('button', { name: 'Confirm booking' })); + fireEvent.click(two.getByRole('button', { name: 'Confirm booking' })); expect(await first).toEqual({ confirmed: false }); expect(await second).toEqual({ confirmed: true }); - expect(controller.getSnapshot().bookings.map((entry) => entry.status)).toEqual(['cancelled', 'confirmed']); + expect(controller.clientTools.getSnapshot()).toEqual([]); }); - it('consumes decision authority before reentrant publication', async () => { - const controller = createClientToolsController(); - const result = controller.tools.confirm_booking.handler({ summary: 'Fictional booking' }, context()); - const token = controller.getSnapshot().bookings[0]; - const duplicate = vi.fn(() => controller.decide(token, false)); - const release = controller.subscribe(duplicate); - expect(controller.decide(token, true)).toBe(true); - expect(duplicate).toHaveReturnedWith(false); - expect(await result).toEqual({ confirmed: true }); - release(); - expect(Object.isFrozen(controller.getSnapshot().bookings[0])).toBe(true); - }); - - it('abort revokes a pending decision and removes its listener', async () => { + it('abort revokes a waiting booking, and its card can no longer answer', async () => { const controller = createClientToolsController(); const abort = new AbortController(); - const remove = vi.spyOn(abort.signal, 'removeEventListener'); const result = controller.tools.confirm_booking.handler({ summary: 'Fictional booking' }, { signal: abort.signal }); const rejected = expect(result).rejects.toMatchObject({ name: 'AbortError' }); - const token = controller.getSnapshot().bookings[0]; + const view = card(controller, 'c1', 'Fictional booking'); abort.abort(); await rejected; - expect(controller.decide(token, true)).toBe(false); - expect(controller.getSnapshot().bookings[0].status).toBe('aborted'); - expect(remove).toHaveBeenCalledWith('abort', expect.any(Function)); + fireEvent.click(view.getByRole('button', { name: 'Confirm booking' })); + expect(controller.clientTools.getSnapshot()).toEqual([]); + expect(controller.clientTools.render(call('c1', 'Fictional booking'))).toBeUndefined(); }); - it('handles abort during pending request publication', async () => { + it('handles abort while the waiting booking is published', async () => { const controller = createClientToolsController(); const abort = new AbortController(); - controller.subscribe(() => abort.abort()); + controller.clientTools.subscribe(() => abort.abort()); await expect(controller.tools.confirm_booking.handler({ summary: 'Fictional booking' }, { signal: abort.signal })).rejects.toMatchObject({ name: 'AbortError' }); - const token = controller.getSnapshot().bookings[0]; - expect(token.status).toBe('aborted'); - expect(controller.decide(token, true)).toBe(false); - }); - - it('decision settlement cleans up handlers while retaining the completed panel', async () => { - const controller = createClientToolsController(); - const abort = new AbortController(); - const remove = vi.spyOn(abort.signal, 'removeEventListener'); - const result = controller.tools.confirm_booking.handler({ summary: 'Fictional booking' }, { signal: abort.signal }); - controller.decide(controller.getSnapshot().bookings[0], true); - await result; - const snapshot = controller.getSnapshot(); - abort.abort(); - expect(controller.getSnapshot()).toBe(snapshot); - expect(remove).toHaveBeenCalledWith('abort', expect.any(Function)); + expect(controller.clientTools.getSnapshot()).toEqual([]); }); - it('disposal immediately revokes pending handlers and cannot publish afterward', async () => { + it('disposal immediately revokes a waiting booking and cannot publish afterward', async () => { const controller = createClientToolsController(); const result = controller.tools.confirm_booking.handler({ summary: 'Fictional booking' }, context()); const rejected = expect(result).rejects.toMatchObject({ name: 'AbortError' }); - const token = controller.getSnapshot().bookings[0]; const notify = vi.fn(); controller.subscribe(notify); controller.dispose(); controller.dispose(); await rejected; - expect(controller.decide(token, true)).toBe(false); + expect(controller.clientTools.getSnapshot()).toEqual([]); + await expect(controller.tools.confirm_booking.handler({ summary: 'Fictional booking' }, context())).rejects.toMatchObject({ name: 'AbortError' }); await expect(controller.tools.get_weather.handler({ location: 'city' }, context())).rejects.toMatchObject({ name: 'AbortError' }); expect(notify).not.toHaveBeenCalled(); }); - it('rejects an already-aborted handler before admission or publication', async () => { + it('rejects an already-aborted handler before any booking waits', async () => { const controller = createClientToolsController(); const abort = new AbortController(); abort.abort(); await expect(controller.tools.confirm_booking.handler({ summary: 'Fictional booking' }, { signal: abort.signal })).rejects.toMatchObject({ name: 'AbortError' }); - expect(controller.getSnapshot().bookings).toEqual([]); + expect(controller.clientTools.getSnapshot()).toEqual([]); }); - it('cancels an admitted handler if publication disposes its controller', async () => { + it('cancels a waiting booking if its publication disposes the controller', async () => { const controller = createClientToolsController(); - controller.subscribe(() => controller.dispose()); + controller.clientTools.subscribe(() => controller.dispose()); await expect(controller.tools.confirm_booking.handler({ summary: 'Fictional booking' }, context())).rejects.toMatchObject({ name: 'AbortError' }); }); @@ -227,6 +229,6 @@ describe('authored client tools', () => { ] as const)('validates %s arguments before side effects', async (name, input) => { const controller = createClientToolsController(); await expect(controller.tools[name].handler(input as never, context())).rejects.toThrow(/Invalid/); - expect(controller.getSnapshot().bookings).toEqual([]); + expect(controller.clientTools.getSnapshot()).toEqual([]); }); }); diff --git a/cockpit/langgraph/client-tools/react/src/tools.ts b/cockpit/langgraph/client-tools/react/src/tools.ts index 097631740..7018b1f97 100644 --- a/cockpit/langgraph/client-tools/react/src/tools.ts +++ b/cockpit/langgraph/client-tools/react/src/tools.ts @@ -1,5 +1,6 @@ import type { PlainValue } from '@threadplane/core'; import type { FunctionTool } from '@threadplane/core/tools'; +import { createBookingTools, type BookingArguments, type BookingDecision } from './booking'; export interface LocationArguments { location: string } export interface WeatherArguments extends LocationArguments { @@ -8,19 +9,12 @@ export interface WeatherArguments extends LocationArguments { humidity: number; windMph: number; } -export interface BookingArguments { summary: string } export interface StatusArguments { label?: string } export interface WeatherPanel extends Readonly { readonly id: string; } -export interface BookingPanel { - readonly id: string; - readonly summary: string; - readonly status: 'pending' | 'confirmed' | 'cancelled' | 'aborted'; -} export interface ClientToolsSnapshot { readonly weather: readonly WeatherPanel[]; - readonly bookings: readonly BookingPanel[]; } function argumentsRecord(value: unknown, keys: readonly string[]) { @@ -75,18 +69,14 @@ const weatherParameters = parameters({ }, weatherKeys); const aborted = () => new DOMException('Client tool cancelled.', 'AbortError'); -/** App-owned presentation and decision authority; no runtime call IDs are inferred. */ +/** App-owned function tools and weather panels, plus the booking ask tool `Chat` draws. */ export function createClientToolsController() { - let snapshot: ClientToolsSnapshot = Object.freeze({ - weather: Object.freeze([]), bookings: Object.freeze([]), - }); + let snapshot: ClientToolsSnapshot = Object.freeze({ weather: Object.freeze([]) }); const listeners = new Set<() => void>(); const cancellations = new Set<() => void>(); - const pending = new Map void; - }>(); + const bookings = createBookingTools(); + // Disposal revokes a waiting booking, like Stop. + const disposal = new AbortController(); let sequence = 0; let disposed = false; function active(signal: AbortSignal) { @@ -97,11 +87,6 @@ export function createClientToolsController() { snapshot = Object.freeze({ ...snapshot, ...update }); for (const notify of listeners) notify(); } - function replaceBooking(row: BookingPanel, status: BookingPanel['status']) { - publish({ bookings: Object.freeze(snapshot.bookings.map((entry) => - entry === row ? Object.freeze({ ...row, status }) : entry - )) }); - } function delay(signal: AbortSignal): Promise { return new Promise((resolve, reject) => { active(signal); @@ -172,66 +157,33 @@ export function createClientToolsController() { handler: (input: WeatherArguments, { signal }) => showWeather(input, signal), } satisfies FunctionTool, confirm_booking: { - description: 'Ask the user to confirm a fictional booking. No real reservation is made.', - parameters: parameters({ summary: { type: 'string', minLength: 1 } }, ['summary']), + ...bookings.tools.confirm_booking, + // Check the arguments first, so the card only ever shows a valid summary. async handler(input: BookingArguments, { signal }) { active(signal); - const summary = text(argumentsRecord(input, ['summary']), 'summary'); - active(signal); - return new Promise<{ confirmed: boolean }>((resolve, reject) => { - const row: BookingPanel = Object.freeze({ id: `booking-${++sequence}`, summary, status: 'pending' }); - let finished = false; - const cleanup = () => { - pending.delete(row.id); - cancellations.delete(cancel); - signal.removeEventListener('abort', cancel); - }; - const cancel = () => { - if (finished) return; - finished = true; - cleanup(); - replaceBooking(row, 'aborted'); - reject(aborted()); - }; - pending.set(row.id, { - row, signal, - finish(confirmed) { - if (finished) return; - finished = true; - cleanup(); - replaceBooking(row, confirmed ? 'confirmed' : 'cancelled'); - resolve({ confirmed }); - }, - }); - cancellations.add(cancel); - signal.addEventListener('abort', cancel, { once: true }); - publish({ bookings: Object.freeze([...snapshot.bookings, row]) }); - if (signal.aborted || disposed) cancel(); + text(argumentsRecord(input, ['summary']), 'summary'); + return bookings.tools.confirm_booking.handler(input, { + signal: AbortSignal.any([signal, disposal.signal]), }); }, - } satisfies FunctionTool, + } satisfies FunctionTool, }); return Object.freeze({ tools, + /** Pass to `Chat` as `clientTools`; a waiting booking is drawn from here. */ + clientTools: bookings, getSnapshot: () => snapshot, subscribe(notify: () => void) { if (disposed) return () => undefined; listeners.add(notify); return () => { listeners.delete(notify); }; }, - decide(row: BookingPanel, confirmed: boolean): boolean { - const request = pending.get(row.id); - if (disposed || typeof confirmed !== 'boolean' || !request || - request.row !== row || request.signal.aborted) return false; - request.finish(confirmed); - return true; - }, dispose() { if (disposed) return; disposed = true; listeners.clear(); for (const cancel of [...cancellations]) cancel(); - pending.clear(); + disposal.abort(); }, }); } diff --git a/libs/cockpit-registry/src/lib/content-descriptors.ts b/libs/cockpit-registry/src/lib/content-descriptors.ts index 4927428ef..0cec9546b 100644 --- a/libs/cockpit-registry/src/lib/content-descriptors.ts +++ b/libs/cockpit-registry/src/lib/content-descriptors.ts @@ -1209,7 +1209,7 @@ const agUiClientToolsReact = (() => { ...canonical, id: 'ag-ui-client-tools-python-react', frontend: 'react', title: 'AG-UI Client Tools (React preview)', codeAssetPaths: [ - ...['app.tsx', 'tools.ts', 'application.ts', 'projection.ts', 'weather-card.tsx', 'connection.ts', 'main.tsx', 'styles.css'].map(file => `cockpit/ag-ui/client-tools/react/src/${file}`), + ...['app.tsx', 'tools.ts', 'booking.tsx', 'application.ts', 'projection.ts', 'weather-card.tsx', 'connection.ts', 'main.tsx', 'styles.css'].map(file => `cockpit/ag-ui/client-tools/react/src/${file}`), 'cockpit/ag-ui/client-tools/react/project.json', ...canonical.promptAssetPaths, ], @@ -1504,7 +1504,7 @@ export const frontendCapabilityModules: readonly RegisteredCapabilityModule[] = if (!canonical || !frontend) throw new Error(`${topic} frontend registration is missing`); return freezeCapabilityDescriptor({ ...canonical, id: `langgraph-${topic}-python-react`, frontend: 'react', title, - codeAssetPaths: ['app.tsx', 'application.ts', ...(topic === 'client-tools' ? ['tools.ts'] : []), ...(topic === 'time-travel' ? ['checkpoint-history.ts'] : []), ...(['time-travel', 'deployment-runtime'].includes(topic) ? ['canonical-history.ts'] : []), 'connection.ts', 'main.tsx'].map((file) => `cockpit/langgraph/${topic}/react/src/${file}`), + codeAssetPaths: ['app.tsx', 'application.ts', ...(topic === 'client-tools' ? ['tools.ts', 'booking.tsx'] : []), ...(topic === 'time-travel' ? ['checkpoint-history.ts'] : []), ...(['time-travel', 'deployment-runtime'].includes(topic) ? ['canonical-history.ts'] : []), 'connection.ts', 'main.tsx'].map((file) => `cockpit/langgraph/${topic}/react/src/${file}`), runtimeUrl: frontend.runtimePath, devPort: frontend.port, }); }), diff --git a/libs/cockpit-registry/src/lib/frontend-pilot.spec.ts b/libs/cockpit-registry/src/lib/frontend-pilot.spec.ts index 69f65b0d0..88e3491ca 100644 --- a/libs/cockpit-registry/src/lib/frontend-pilot.spec.ts +++ b/libs/cockpit-registry/src/lib/frontend-pilot.spec.ts @@ -531,6 +531,7 @@ describe('registered React public previews', () => { 'app.tsx', 'application.ts', 'tools.ts', + 'booking.tsx', 'connection.ts', 'main.tsx', ].map((file) => `cockpit/langgraph/client-tools/react/src/${file}`) @@ -702,7 +703,7 @@ describe('registered React public previews', () => { const react = getFrontendCapabilityDescriptor(canonical.manifestIdentity as CockpitManifestIdentity, 'react'); expect(react).toMatchObject({ id: 'ag-ui-client-tools-python-react', frontend: 'react', runtimeAdapter: 'ag-ui', runtimeUrl: 'ag-ui/client-tools/react', devPort: 4640, docsPath: '/docs/react/ag-ui/guides/client-tools', backendAssetPaths: canonical.backendAssetPaths, promptAssetPaths: canonical.promptAssetPaths }); expect(react?.codeAssetPaths).toEqual([ - ...['app.tsx', 'tools.ts', 'application.ts', 'projection.ts', 'weather-card.tsx', 'connection.ts', 'main.tsx', 'styles.css'].map(file => `cockpit/ag-ui/client-tools/react/src/${file}`), + ...['app.tsx', 'tools.ts', 'booking.tsx', 'application.ts', 'projection.ts', 'weather-card.tsx', 'connection.ts', 'main.tsx', 'styles.css'].map(file => `cockpit/ag-ui/client-tools/react/src/${file}`), 'cockpit/ag-ui/client-tools/react/project.json', 'cockpit/ag-ui/client-tools/python/prompts/client-tools.md', ]); diff --git a/libs/react/src/chat/chat.tsx b/libs/react/src/chat/chat.tsx index fb33090e5..dfee62e84 100644 --- a/libs/react/src/chat/chat.tsx +++ b/libs/react/src/chat/chat.tsx @@ -14,6 +14,11 @@ import { type ChatInputHandle, type ChatInputProps, } from './chat-input.js'; +import { + useClientToolCalls, + usePendingClientToolCalls, + type ChatClientTools, +} from './client-tools.js'; import { ChatError } from './error.js'; import { useMessageContent } from './internal/use-message-content.js'; import { @@ -49,6 +54,13 @@ export interface ChatProps /** App-owned presentation for one tool call; see `MessageListProps.renderToolCall`. Keep stable. */ readonly renderToolCall?: MessageListProps['renderToolCall']; readonly renderToolResult?: MessageListProps['renderToolResult']; + /** + * Interactive client tools from `createClientTools`. While one of its calls waits for the person, + * its view is drawn below the message's tool calls and the call keeps its row; the answer + * becomes the tool result, the view goes, and focus returns to the composer. The + * app passes `clientTools.tools` to the session; Chat never runs a tool. Off unless set. + */ + readonly clientTools?: ChatClientTools; /** Child agents shown as subagent cards in place of the tool calls that started them. Keep stable. */ readonly subagents?: MessageListProps['subagents']; /** Application-owned handler for a retry declared by `toolOutcome`; Chat never re-runs a call. Keep stable. */ @@ -119,6 +131,7 @@ export function Chat({ toolOutcome, renderToolCall, renderToolResult, + clientTools, subagents, onToolRetry, onRetry, @@ -168,17 +181,21 @@ export function Chat({ const pending = approval !== undefined && approval !== null && approval !== false; const disabled = input.disabled ?? false; - const hadApproval = useRef(pending); + // An answered client tool leaves the transcript the same way. + const renderPrompt = useClientToolCalls(clientTools); + const asked = usePendingClientToolCalls(clientTools).length > 0; + const awaited = pending || asked; + const hadApproval = useRef(awaited); const focusOwed = useRef(false); useEffect(() => { - if (hadApproval.current && !pending) focusOwed.current = true; - if (pending) focusOwed.current = false; - hadApproval.current = pending; + if (hadApproval.current && !awaited) focusOwed.current = true; + if (awaited) focusOwed.current = false; + hadApproval.current = awaited; if (focusOwed.current && !disabled) { focusOwed.current = false; composer.current?.focus(); } - }, [pending, disabled]); + }, [awaited, disabled]); const rows = useMessageContent(snapshot, session, content); // A failed call already shows these words, and the notice would add no action or detail of its own. // A custom renderMessage owns that display, so the notice stays whenever one is in use. @@ -262,6 +279,7 @@ export function Chat({ toolLabel={toolLabel} toolOutcome={toolOutcome} renderToolCall={renderToolCall} + renderToolCallPrompt={renderPrompt} renderToolResult={renderToolResult} subagents={subagents} onToolRetry={onToolRetry} diff --git a/libs/react/src/chat/client-tools.spec.tsx b/libs/react/src/chat/client-tools.spec.tsx new file mode 100644 index 000000000..a2ee82d3f --- /dev/null +++ b/libs/react/src/chat/client-tools.spec.tsx @@ -0,0 +1,388 @@ +import { act, cleanup, fireEvent, render } from '@testing-library/react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { renderToString } from 'react-dom/server'; +import { + completeDelivery, + type AgentSession, + type AgentSnapshot, +} from '@threadplane/core'; +import { createMessageContent } from '@threadplane/content/messages'; +import { + Chat, + MessageList, + ask, + createClientTools, + useClientToolCalls, + type ChatClientTools, + type MessageListProps, +} from './index'; + +afterEach(cleanup); + +type Calls = AgentSnapshot['toolCalls']; +interface DayArgs { + days: string[]; +} +function dayTools() { + return createClientTools({ + pick_day: ask({ + description: 'Ask which day to plan.', + parameters: { type: 'object' }, + render: ({ args, answer, toolCallId }) => ( +
+ {args.days.map((day) => ( + + ))} +
+ ), + }), + }); +} +const running = (id: string, days: string[], name = 'pick_day') => ({ + id, + name, + args: { days }, + status: 'running', +}); +const transcript = (calls: readonly object[], status = 'running') => + ({ + status, + messages: [ + { + id: 'a', + role: 'assistant', + content: 'Which day?', + delivery: completeDelivery('g', 'success'), + toolCallIds: (calls as { id: string }[]).map((call) => call.id), + }, + ], + toolCalls: calls as unknown as Calls, + } as AgentSnapshot); + +function fakeSession(initial: AgentSnapshot) { + let snapshot = initial; + const listeners = new Set<() => void>(); + const raw = { + getSnapshot: () => snapshot, + subscribe(notify: () => void) { + listeners.add(notify); + return () => listeners.delete(notify); + }, + submit: vi.fn(async () => 'success' as const), + stop: vi.fn(async () => undefined), + dispose: vi.fn(async () => undefined), + }; + const set = (next: AgentSnapshot) => { + snapshot = next; + act(() => listeners.forEach((notify) => notify())); + }; + return { session: raw as unknown as AgentSession, set }; +} +/** Starts a handler the way a session does, and reports how it settles. */ +function start( + tools: ReturnType, + days: string[], + signal = new AbortController().signal +) { + const settled = vi.fn(); + const failed = vi.fn(); + act(() => { + void Promise.resolve( + tools.tools.pick_day.handler({ days }, { signal }) + ).then(settled, failed); + }); + return { settled, failed }; +} +const flush = () => act(async () => undefined); + +describe('createClientTools', () => { + it('exposes each ask tool to the session as a function tool with its metadata', () => { + const tools = createClientTools({ + pick_day: ask({ + description: 'Ask which day to plan.', + parameters: { type: 'object' }, + followUp: false, + render: () => null, + }), + }); + expect(Object.keys(tools.tools)).toEqual(['pick_day']); + expect(tools.tools.pick_day).toMatchObject({ + description: 'Ask which day to plan.', + parameters: { type: 'object' }, + followUp: false, + }); + expect(tools.tools.pick_day).not.toHaveProperty('render'); + }); + + it('keeps a call waiting until the first answer, which becomes the tool result', async () => { + const tools = dayTools(); + const notify = vi.fn(); + tools.subscribe(notify); + const call = start(tools, ['Mon', 'Tue']); + expect(tools.getSnapshot()).toEqual([ + { name: 'pick_day', args: { days: ['Mon', 'Tue'] } }, + ]); + expect(notify).toHaveBeenCalledTimes(1); + await flush(); + expect(call.settled).not.toHaveBeenCalled(); + + const { container } = render( + <>{tools.render(running('c1', ['Mon', 'Tue']))} + ); + const [monday, tuesday] = container.querySelectorAll('button'); + fireEvent.click(tuesday); + fireEvent.click(monday); + await flush(); + expect(call.settled).toHaveBeenCalledTimes(1); + expect(call.settled).toHaveBeenCalledWith({ day: 'Tue' }); + expect(tools.getSnapshot()).toEqual([]); + expect(notify).toHaveBeenCalledTimes(2); + // The answered call has no view any more, even while the session still reports it running. + expect(tools.render(running('c1', ['Mon', 'Tue']))).toBeUndefined(); + }); + + it('rejects a waiting call when its signal aborts and ignores a late answer', async () => { + const tools = dayTools(); + const stop = new AbortController(); + const call = start(tools, ['Mon'], stop.signal); + const { container } = render(<>{tools.render(running('c1', ['Mon']))}); + act(() => stop.abort()); + await flush(); + expect(call.failed).toHaveBeenCalledTimes(1); + expect(call.failed.mock.calls[0][0]).toMatchObject({ name: 'AbortError' }); + expect(tools.getSnapshot()).toEqual([]); + fireEvent.click(container.querySelector('button') as HTMLElement); + await flush(); + expect(call.settled).not.toHaveBeenCalled(); + + const late = start(tools, ['Mon'], stop.signal); + await flush(); + expect(late.failed).toHaveBeenCalledTimes(1); + expect(tools.getSnapshot()).toEqual([]); + }); + + it('pairs parallel calls by their arguments and keeps each pairing', async () => { + const tools = dayTools(); + const first = start(tools, ['Mon']); + const second = start(tools, ['Tue']); + // The transcript lists them in the other order. + const view = () => + render( + <> + {tools.render(running('c2', ['Tue']))} + {tools.render(running('c1', ['Mon']))} + + ).container; + expect( + [...view().querySelectorAll('[data-ask]')].map( + (el) => `${el.getAttribute('data-ask')}:${el.textContent}` + ) + ).toEqual(['c2:Tue', 'c1:Mon']); + cleanup(); + fireEvent.click( + view().querySelector('[data-ask="c1"] button') as HTMLElement + ); + await flush(); + expect(first.settled).toHaveBeenCalledWith({ day: 'Mon' }); + expect(second.settled).not.toHaveBeenCalled(); + expect(tools.render(running('c2', ['Tue']))).toBeDefined(); + }); + + it('gives identical calls one waiting handler each', async () => { + const tools = dayTools(); + const first = start(tools, ['Mon']); + const second = start(tools, ['Mon']); + const { container } = render( + <> + {tools.render(running('c1', ['Mon']))} + {tools.render(running('c2', ['Mon']))} + {tools.render(running('c3', ['Mon']))} + + ); + expect(container.querySelectorAll('[data-ask]')).toHaveLength(2); + fireEvent.click( + container.querySelector('[data-ask="c2"] button') as HTMLElement + ); + await flush(); + expect( + first.settled.mock.calls.length + second.settled.mock.calls.length + ).toBe(1); + }); + + it('draws nothing for other tools, settled calls, or a call with no handler waiting', () => { + const tools = dayTools(); + expect(tools.render(running('c1', ['Mon']))).toBeUndefined(); + start(tools, ['Mon']); + expect(tools.render(running('c1', ['Mon'], 'lookup'))).toBeUndefined(); + expect( + tools.render({ ...running('c1', ['Mon']), status: 'complete' }) + ).toBeUndefined(); + expect( + tools.render({ ...running('c1', ['Mon']), status: 'error' }) + ).toBeUndefined(); + expect(tools.render(running('c1', ['Mon']))).toBeDefined(); + }); +}); + +describe('Chat clientTools', () => { + it('shows a waiting ask below the call, which keeps its row, and returns the answer', async () => { + const tools = dayTools(); + const { session, set } = fakeSession( + transcript([running('c1', ['Mon', 'Tue'])]) + ); + const { container } = render( + + ); + // The session reports the call before its handler starts: only the built-in row shows. + expect(container.querySelector('[data-ask]')).toBeNull(); + const row = container.querySelector('.tp-tool-activity'); + expect(row).not.toBeNull(); + + const call = start(tools, ['Mon', 'Tue']); + const card = container.querySelector( + '.tp-chat-tool-call[data-tool-prompt="c1"] [data-ask="c1"]' + ); + expect(card).not.toBeNull(); + // The call keeps its row, and the view follows it. + expect(container.querySelector('.tp-tool-activity')).toBe(row); + expect( + (row as Element).compareDocumentPosition(card as Element) & + Node.DOCUMENT_POSITION_FOLLOWING + ).toBeTruthy(); + + const button = card?.querySelectorAll('button')[1] as HTMLElement; + button.focus(); + fireEvent.click(button); + await flush(); + expect(call.settled).toHaveBeenCalledWith({ day: 'Tue' }); + expect(container.querySelector('[data-ask]')).toBeNull(); + expect(container.querySelector('.tp-tool-activity')).not.toBeNull(); + expect(document.activeElement).toBe(container.querySelector('textarea')); + + set( + transcript( + [ + { + ...running('c1', ['Mon', 'Tue']), + status: 'complete', + result: { day: 'Tue' }, + }, + ], + 'idle' + ) + ); + expect(container.querySelector('[data-ask]')).toBeNull(); + expect(container.querySelector('.tp-tool-activity')).not.toBeNull(); + }); + + it('adds a waiting ask without taking any call from renderToolCall', () => { + const tools = dayTools(); + const { session } = fakeSession( + transcript([running('c1', ['Mon']), running('c2', ['x'], 'lookup')]) + ); + const renderToolCall: NonNullable = ( + call + ) =>

App view

; + const { container } = render( + + ); + expect( + [...container.querySelectorAll('[data-app]')].map((el) => + el.getAttribute('data-app') + ) + ).toEqual(['c1', 'c2']); + start(tools, ['Mon']); + expect(container.querySelector('[data-ask="c1"]')).not.toBeNull(); + expect( + [...container.querySelectorAll('[data-app]')].map((el) => + el.getAttribute('data-app') + ) + ).toEqual(['c1', 'c2']); + }); + + it('keeps the waiting call in its running group, with the ask after the group', () => { + const tools = dayTools(); + const { session } = fakeSession( + transcript([ + { ...running('c0', ['x'], 'lookup'), status: 'complete', result: 1 }, + running('c1', ['Mon']), + { ...running('c2', ['y'], 'lookup'), status: 'complete', result: 2 }, + ]) + ); + const { container } = render( + + ); + start(tools, ['Mon']); + const groups = container.querySelectorAll('.tp-tool-activity-group'); + expect(groups).toHaveLength(1); + expect(groups[0].getAttribute('data-active')).toBe('true'); + const ask = container.querySelector('[data-ask="c1"]') as Element; + expect(groups[0].contains(ask)).toBe(false); + expect( + groups[0].compareDocumentPosition(ask) & Node.DOCUMENT_POSITION_FOLLOWING + ).toBeTruthy(); + }); + + it('shows no ask without the clientTools prop, even while a handler waits', () => { + const tools = dayTools(); + const { session } = fakeSession(transcript([running('c1', ['Mon'])])); + const { container } = render(); + start(tools, ['Mon']); + expect(container.querySelector('[data-ask]')).toBeNull(); + expect(container.querySelector('.tp-tool-activity')).not.toBeNull(); + }); + + it('removes the ask when the run is stopped', async () => { + const tools = dayTools(); + const stop = new AbortController(); + const { session } = fakeSession(transcript([running('c1', ['Mon'])])); + const { container } = render( + + ); + const call = start(tools, ['Mon'], stop.signal); + expect(container.querySelector('[data-ask="c1"]')).not.toBeNull(); + act(() => stop.abort()); + await flush(); + expect(call.failed).toHaveBeenCalledTimes(1); + expect(container.querySelector('[data-ask]')).toBeNull(); + }); +}); + +describe('useClientToolCalls', () => { + function List({ tools }: { readonly tools?: ChatClientTools }) { + const rows = createMessageContent().project( + transcript([running('c1', ['Mon'])]) + ); + return ( + + ); + } + it('lets MessageList draw a waiting ask and re-renders when it starts', () => { + const tools = dayTools(); + const { container } = render(); + expect(container.querySelector('[data-ask]')).toBeNull(); + start(tools, ['Mon']); + expect(container.querySelector('[data-ask="c1"]')).not.toBeNull(); + }); + it('renders a waiting ask on the server', () => { + const tools = dayTools(); + void tools.tools.pick_day.handler( + { days: ['Mon'] }, + { signal: new AbortController().signal } + ); + expect(renderToString()).toContain('data-ask="c1"'); + }); + it('is inert without client tools', () => { + const { container } = render(); + expect(container.querySelector('.tp-tool-activity')).not.toBeNull(); + }); +}); diff --git a/libs/react/src/chat/client-tools.ts b/libs/react/src/chat/client-tools.ts new file mode 100644 index 000000000..d6a97c0f8 --- /dev/null +++ b/libs/react/src/chat/client-tools.ts @@ -0,0 +1,271 @@ +'use client'; +import { useMemo, useSyncExternalStore, type ReactNode } from 'react'; +import type { PlainValue } from '@threadplane/core'; +import type { ExecutionContext, FunctionTool } from '@threadplane/core/tools'; + +/** What an ask tool's view receives for one pending call. */ +export interface AskToolViewProps { + readonly toolCallId: string; + readonly name: string; + /** The finalized arguments the tool was called with. */ + readonly args: A; + /** + * Returns the person's answer as the tool result, and the run continues. Only the first answer + * counts; false means the call was already answered or stopped. + */ + readonly answer: (result: R) => boolean; +} + +/** A tool the model calls and the person answers in the transcript; see {@link ask}. */ +export interface AskTool { + readonly kind: 'ask'; + readonly description: string; + /** Optional caller-authored JSON Schema, sent unchanged as metadata. */ + readonly parameters?: PlainValue; + /** Defaults to true; false persists the answer without another run. */ + readonly followUp?: boolean; + /** Draws the control. Return an element; arguments are not validated before it is called. */ + readonly render: (props: AskToolViewProps) => ReactNode; +} + +/** Storage constraint for a catalog of ask tools with different argument and result types. */ +export interface AskToolDefinition { + readonly kind: 'ask'; + readonly description: string; + readonly parameters?: PlainValue; + readonly followUp?: boolean; + readonly render: (props: never) => ReactNode; +} + +/** A call a handler is waiting on the person to answer. */ +export interface PendingClientToolCall { + readonly name: string; + readonly args: unknown; +} + +/** The part of {@link ClientTools} that `Chat` reads; it never runs a tool itself. */ +export interface ChatClientTools { + /** Calls waiting for an answer, oldest first. A new array whenever one starts or ends. */ + getSnapshot(): readonly PendingClientToolCall[]; + subscribe(notify: () => void): () => void; + /** + * The view for a pending call of one of these tools, or `undefined` when the call is not one of + * them, is already settled, or has no handler waiting (such as a call observed from history). + */ + render(call: ClientToolCallLike): ReactNode | undefined; +} + +/** The fields of a snapshot tool call that match it to a waiting handler. */ +export interface ClientToolCallLike { + readonly id: string; + readonly name: string; + readonly args?: unknown; + readonly status: string; +} + +type AskFunctionTool = T extends { + readonly render: (props: AskToolViewProps) => ReactNode; +} + ? FunctionTool + : never; + +/** Ask tools as session function tools, plus the views `Chat` shows while they wait. */ +export interface ClientTools> + extends ChatClientTools { + /** Pass to the session that runs the conversation, alone or spread beside other function tools. */ + readonly tools: { readonly [K in keyof T]: AskFunctionTool }; +} + +/** + * Declares a tool the person answers. The model fills `args`; `render` draws the control in the + * transcript below the message's tool calls, and the value passed to `answer` becomes the tool result. + * + * @example + * ```tsx + * const clientTools = createClientTools({ + * pick_day: ask<{ days: string[] }, { day: string }>({ + * description: 'Ask which day to plan.', + * render: ({ args, answer }) => answer({ day })} />, + * }), + * }); + * ``` + */ +export function ask(tool: Omit, 'kind'>): AskTool { + return { ...tool, kind: 'ask' }; +} + +interface Waiting { + readonly name: string; + readonly args: unknown; + readonly key: string; + readonly answer: (result: unknown) => boolean; + callId?: string; +} + +/** Stable text for comparing a handler's arguments with a snapshot call's arguments. */ +function argumentsKey(value: unknown): string { + return ( + JSON.stringify(value, (_key, item: unknown) => + item && typeof item === 'object' && !Array.isArray(item) + ? Object.fromEntries( + Object.entries(item).sort(([a], [b]) => + a < b ? -1 : a > b ? 1 : 0 + ) + ) + : item + ) ?? '' + ); +} + +const cancelled = () => + new DOMException('Client tool cancelled.', 'AbortError'); + +/** + * Turns ask tools into function tools for an app-owned session and keeps the calls that wait for + * an answer. Create it once, pass `tools` to the session and the whole object to `Chat` as + * `clientTools`. Stopping the run aborts a waiting call; nothing is persisted here. + * + * A handler is not told its call ID, so a waiting call is paired with the transcript call of the + * same name and equal arguments, or else the oldest waiting call of that name. Identical calls + * are interchangeable, and a view always answers the arguments it was drawn with. + */ +export function createClientTools< + const T extends Record +>(definitions: T): ClientTools { + const owned = new Map(Object.entries(definitions)); + const listeners = new Set<() => void>(); + const waiting: Waiting[] = []; + const claimed = new Map(); + let snapshot: readonly PendingClientToolCall[] = Object.freeze([]); + function publish() { + snapshot = Object.freeze( + waiting.map(({ name, args }) => Object.freeze({ name, args })) + ); + for (const notify of [...listeners]) notify(); + } + function handler(name: string) { + return (args: unknown, { signal }: ExecutionContext) => + new Promise((resolve, reject) => { + if (signal.aborted) { + reject(cancelled()); + return; + } + let open = true; + const close = () => { + open = false; + signal.removeEventListener('abort', abort); + waiting.splice(waiting.indexOf(request), 1); + if (request.callId !== undefined) claimed.delete(request.callId); + publish(); + }; + const abort = () => { + if (!open) return; + close(); + reject(cancelled()); + }; + const request: Waiting = { + name, + args, + key: argumentsKey(args), + answer(result) { + if (!open) return false; + close(); + resolve(result); + return true; + }, + }; + signal.addEventListener('abort', abort, { once: true }); + waiting.push(request); + publish(); + }); + } + const tools = Object.freeze( + Object.fromEntries( + [...owned].map(([name, definition]) => [ + name, + Object.freeze({ + description: definition.description, + ...(definition.parameters !== undefined + ? { parameters: definition.parameters } + : {}), + ...(definition.followUp !== undefined + ? { followUp: definition.followUp } + : {}), + handler: handler(name), + }), + ]) + ) + ) as ClientTools['tools']; + return Object.freeze({ + tools, + getSnapshot: () => snapshot, + subscribe(notify: () => void) { + listeners.add(notify); + return () => { + listeners.delete(notify); + }; + }, + render(call: ClientToolCallLike) { + if (call.status !== 'pending' && call.status !== 'running') + return undefined; + const definition = owned.get(call.name); + if (!definition) return undefined; + let request = claimed.get(call.id); + if (!request) { + // Pairing is idempotent, so a repeated or discarded render reaches the same result. + const free = waiting.filter( + (item) => item.name === call.name && item.callId === undefined + ); + const key = argumentsKey(call.args); + request = free.find((item) => item.key === key) ?? free[0]; + if (!request) return undefined; + request.callId = call.id; + claimed.set(call.id, request); + } + const render = definition.render as ( + props: AskToolViewProps + ) => ReactNode; + return render({ + toolCallId: call.id, + name: call.name, + args: request.args, + answer: request.answer, + }); + }, + }); +} + +const NONE: readonly PendingClientToolCall[] = Object.freeze([]); +const noSubscription = () => () => undefined; +const none = () => NONE; + +/** Calls waiting for the person, re-read whenever one starts or ends. Empty without `clientTools`. */ +export function usePendingClientToolCalls( + clientTools: ChatClientTools | undefined +): readonly PendingClientToolCall[] { + const read = clientTools?.getSnapshot ?? none; + return useSyncExternalStore( + clientTools?.subscribe ?? noSubscription, + read, + read + ); +} + +/** + * A `renderToolCallPrompt` for `MessageList` that draws waiting ask tools below the message's tool + * calls. `Chat` does this itself through its `clientTools` prop. The function changes only when a + * call starts or stops waiting, so rows keep their memo otherwise. + */ +export function useClientToolCalls( + clientTools: ChatClientTools | undefined +): ((call: TCall) => ReactNode) | undefined { + // Read for its identity: a new array is a new set of waiting calls, so a new function. + const pending = usePendingClientToolCalls(clientTools); + return useMemo( + () => + clientTools && pending + ? (call: TCall) => clientTools.render(call) + : undefined, + [clientTools, pending] + ); +} diff --git a/libs/react/src/chat/client-tools.type-test.tsx b/libs/react/src/chat/client-tools.type-test.tsx new file mode 100644 index 000000000..6fdf555df --- /dev/null +++ b/libs/react/src/chat/client-tools.type-test.tsx @@ -0,0 +1,74 @@ +import type { AgentSession } from '@threadplane/core'; +import type { + CheckedTools, + FunctionTool, + ToolContracts, +} from '@threadplane/core/tools'; +import { + Chat, + MessageList, + ask, + createClientTools, + type AskToolViewProps, + type ChatClientTools, +} from './index.js'; + +declare const session: AgentSession; +interface DayArgs { + days: string[]; +} +interface DayResult { + day: string; +} +const clientTools = createClientTools({ + pick_day: ask({ + description: 'Ask which day to plan.', + render: ({ args, answer }) => ( + + ), + }), + confirm: ask<{ summary: string }, boolean>({ + description: 'Confirm.', + followUp: false, + render: (props: AskToolViewProps<{ summary: string }, boolean>) => + props.answer(true) ? null : props.args.summary, + }), +}); + +// Each ask is the function tool a session accepts, with its authored types. +const pick: FunctionTool = clientTools.tools.pick_day; +void pick; +// A session's `tools` option is `T & CheckedTools`. +const checked: CheckedTools = clientTools.tools; +void checked; +type Contracts = ToolContracts; +const contract: Contracts['confirm'] = { + args: { summary: 'Trip' }, + result: true, +}; +void contract; +// @ts-expect-error The result type follows the declaration. +const wrong: Contracts['pick_day']['result'] = { day: 1 }; +void wrong; +// @ts-expect-error Only declared tools exist. +void clientTools.tools.missing; + +const face: ChatClientTools = clientTools; +; +; +; + face.render(call)} />; +// @ts-expect-error A prompt is a function of the call, not the controller. +; +// @ts-expect-error The function-tool catalog alone has no views. +; + +createClientTools({ + bad: ask({ + description: 'Wrong answer type.', + // @ts-expect-error The answer must match the declared result. + render: ({ answer }) => (answer({ day: 2 }) ? null : null), + }), +}); diff --git a/libs/react/src/chat/index.ts b/libs/react/src/chat/index.ts index f1c196027..82e25e308 100644 --- a/libs/react/src/chat/index.ts +++ b/libs/react/src/chat/index.ts @@ -108,6 +108,19 @@ export { type MessageListScrollControls, } from './message-list.js'; export { Reasoning, type ReasoningProps } from './reasoning.js'; +export { + ask, + createClientTools, + useClientToolCalls, + usePendingClientToolCalls, + type AskTool, + type AskToolDefinition, + type AskToolViewProps, + type ChatClientTools, + type ClientToolCallLike, + type ClientTools, + type PendingClientToolCall, +} from './client-tools.js'; export { Trace, type TraceProps, type TraceState } from './trace.js'; export { Citations, type CitationsProps } from './citations.js'; export { CitationCard, type CitationCardProps } from './citation-card.js'; diff --git a/libs/react/src/chat/message-list.tsx b/libs/react/src/chat/message-list.tsx index 2dd7befc3..e362612d7 100644 --- a/libs/react/src/chat/message-list.tsx +++ b/libs/react/src/chat/message-list.tsx @@ -116,6 +116,15 @@ export interface MessageListProps { call: NoInfer>['toolCalls'][number], activity: ToolActivityInfo ) => ReactNode; + /** + * App-owned control for a tool call that waits on the person, drawn below the message's tool calls. Unlike + * `renderToolCall` the call keeps its place: its row, group, progress and Stop stay as they are. Return `undefined` + * for a call with nothing to ask. Keep stable like renderMessage; custom renderMessage retains full ownership. + */ + readonly renderToolCallPrompt?: ( + call: NoInfer>['toolCalls'][number], + activity: ToolActivityInfo + ) => ReactNode; /** App-owned rich result or action for one tool call, rendered outside technical Details. Keep stable like renderMessage; custom renderMessage retains full ownership. */ readonly renderToolResult?: (activity: ToolActivityInfo) => ReactNode; /** @@ -333,6 +342,7 @@ function RowView({ toolLabel, toolOutcome, renderToolCall, + renderToolCallPrompt, renderToolResult, onToolRetry, staleRetries, @@ -364,6 +374,10 @@ function RowView({ call: TRow['toolCalls'][number], activity: ToolActivityInfo ) => ReactNode; + readonly renderToolCallPrompt?: ( + call: TRow['toolCalls'][number], + activity: ToolActivityInfo + ) => ReactNode; readonly renderToolResult?: (activity: ToolActivityInfo) => ReactNode; readonly onToolRetry?: (activity: ToolActivityInfo) => void; /** "*" while work is active, otherwise the row's superseded call IDs joined by newlines. A string keeps the memo stable. */ @@ -431,6 +445,9 @@ function RowView({ | { readonly activities: ToolActivityInfo[] } | { readonly child: SubagentInfo } > = []; + // Controls for calls that wait on the person follow the runs, so no group is split. + const prompts: Array<{ readonly prompt: ReactNode; readonly id: string }> = + []; const activityById = new Map( activities.map((activity) => [activity.id, activity]) ); @@ -442,6 +459,9 @@ function RowView({ } const activity = activityById.get(call.id); if (!activity) return; + const prompt = renderToolCallPrompt?.(call, activity); + if (prompt != null && prompt !== false) + prompts.push({ prompt, id: activity.id }); const custom = renderToolCall?.(call, activity); if (custom !== undefined) { runs.push({ custom, id: activity.id }); @@ -537,6 +557,16 @@ function RowView({ )) ) )} + {row.role !== 'tool' && + prompts.map(({ prompt, id }) => ( +
+ {prompt} +
+ ))} {assistant && messageActions !== undefined && messageActions !== false && @@ -579,6 +609,7 @@ export function MessageList({ toolLabel, toolOutcome, renderToolCall, + renderToolCallPrompt, renderToolResult, onToolRetry, plan, @@ -734,6 +765,7 @@ export function MessageList({ toolLabel={toolLabel} toolOutcome={toolOutcome} renderToolCall={renderToolCall} + renderToolCallPrompt={renderToolCallPrompt} renderToolResult={renderToolResult} onToolRetry={onToolRetry} staleRetries={staleRetries?.[index]} diff --git a/scripts/react-parity/dispositions.json b/scripts/react-parity/dispositions.json index 9d695b0fc..cb9d163fe 100644 --- a/scripts/react-parity/dispositions.json +++ b/scripts/react-parity/dispositions.json @@ -2,6 +2,78 @@ "schemaVersion": 1, "purpose": "Planning ownership for the reviewed migration scope. Existing task assignments are preserved; in-progress records identify bounded runtime/configuration subsets, not whole-task completion. Inventory validation is not React parity.", "rows": [ + { + "id": "export:libs/react/src/chat/index.ts#ask", + "taskIds": ["T15"], "treatment": "react", "status": "in-progress", + "target": "libs/react/src/chat/client-tools.ts", + "reason": "Declares a tool the person answers, like Angular ask(): the model fills the arguments and the value the view passes to answer becomes the tool result. React takes authored argument and result types and a render function; there is no schema DSL or argument validation." + }, + { + "id": "export:libs/react/src/chat/index.ts#createClientTools", + "taskIds": ["T15"], "treatment": "react", "status": "in-progress", + "target": "libs/react/src/chat/client-tools.ts", + "reason": "Turns ask tools into core function tools for an app-owned session and keeps the calls that wait for an answer, the React counterpart of Angular tools() plus the chat coordinator for ask tools. Execution, follow-up and persistence stay with the session; view tools, a continuation policy and an execution guard are not part of it." + }, + { + "id": "export:libs/react/src/chat/index.ts#useClientToolCalls", + "taskIds": ["T15"], "treatment": "react", "status": "in-progress", + "target": "libs/react/src/chat/client-tools.ts", + "reason": "React-only seam: a renderToolCall for MessageList that draws waiting ask tools and changes only when a call starts or stops waiting. Chat applies it through its opt-in clientTools prop, as Angular chat does through its clientTools input." + }, + { + "id": "export:libs/react/src/chat/index.ts#usePendingClientToolCalls", + "taskIds": ["T15"], "treatment": "react", "status": "in-progress", + "target": "libs/react/src/chat/client-tools.ts", + "reason": "React-only seam: the calls waiting for the person, for an app that composes its own transcript or status; Angular reads the same from the agent's clientTools.pending signal." + }, + { + "id": "export:libs/react/src/chat/index.ts#AskTool", + "taskIds": ["T15"], "treatment": "react", "status": "in-progress", + "target": "libs/react/src/chat/client-tools.ts", + "reason": "Typed ask-tool declaration, the counterpart of Angular AskToolDef with a render function in place of a component and authored types in place of a schema." + }, + { + "id": "export:libs/react/src/chat/index.ts#AskToolDefinition", + "taskIds": ["T15"], "treatment": "react", "status": "in-progress", + "target": "libs/react/src/chat/client-tools.ts", + "reason": "Storage constraint for a catalog of ask tools with different argument and result types, as Angular ClientToolDef is for its registry." + }, + { + "id": "export:libs/react/src/chat/index.ts#AskToolViewProps", + "taskIds": ["T15"], "treatment": "react", "status": "in-progress", + "target": "libs/react/src/chat/client-tools.ts", + "reason": "What an ask view receives: the call ID, name, finalized arguments and an answer function. Angular passes the same through component inputs and an emitted value." + }, + { + "id": "export:libs/react/src/chat/index.ts#ChatClientTools", + "taskIds": ["T15"], "treatment": "react", "status": "in-progress", + "target": "libs/react/src/chat/client-tools.ts", + "reason": "The read-only face Chat takes as clientTools: waiting calls, a subscription and the view for a call. Chat never runs a tool." + }, + { + "id": "export:libs/react/src/chat/index.ts#ClientToolCallLike", + "taskIds": ["T15"], "treatment": "react", "status": "in-progress", + "target": "libs/react/src/chat/client-tools.ts", + "reason": "The snapshot tool-call fields used to pair a transcript call with a waiting handler, since a core function-tool handler is not told its call ID." + }, + { + "id": "export:libs/react/src/chat/index.ts#ClientTools", + "taskIds": ["T15"], "treatment": "react", "status": "in-progress", + "target": "libs/react/src/chat/client-tools.ts", + "reason": "Result of createClientTools: the function-tool catalog for the session plus the Chat face, the counterpart of Angular ClientToolRegistry for ask tools." + }, + { + "id": "export:libs/react/src/chat/index.ts#PendingClientToolCall", + "taskIds": ["T15"], "treatment": "react", "status": "in-progress", + "target": "libs/react/src/chat/client-tools.ts", + "reason": "One call waiting for an answer, by name and arguments; Angular exposes pending client tool calls on the agent capability." + }, + { + "id": "source:libs/react/src/chat/client-tools.ts", + "taskIds": ["T15"], "treatment": "react", "status": "in-progress", + "target": "libs/react/src/chat/client-tools.ts", + "reason": "Interactive client tools for React Chat, first slice: ask tools become core function tools whose handler waits for the person, and Chat shows the app-rendered view in place of the pending call. Opt-in through clientTools; view tools, schema validation, a continuation policy and composer wording are left." + }, { "id": "component:libs/chat/src/lib/primitives/chat-status-panel/chat-status-panel.component.ts#ChatStatusPanelComponent", "taskIds": ["T28"], "treatment": "react", "status": "in-progress", diff --git a/scripts/react-parity/verify-packages.mjs b/scripts/react-parity/verify-packages.mjs index 8435c8822..7c86f0b4c 100644 --- a/scripts/react-parity/verify-packages.mjs +++ b/scripts/react-parity/verify-packages.mjs @@ -503,6 +503,10 @@ const SUPPORTED_EXPORTS = { 'toolOutcomes', 'citationsWithToolSources', 'StatusPanel', + 'ask', + 'createClientTools', + 'useClientToolCalls', + 'usePendingClientToolCalls', 'ToolObservation', 'SubagentCard', 'subagentsFromEvidence', diff --git a/scripts/react-parity/verify-packages.spec.mjs b/scripts/react-parity/verify-packages.spec.mjs index e2621fbee..c7b14292e 100644 --- a/scripts/react-parity/verify-packages.spec.mjs +++ b/scripts/react-parity/verify-packages.spec.mjs @@ -1061,6 +1061,7 @@ test('React chat requires its real supported export', () => { supported.ChatMessage = component; supported.isTyping = component; supported.ApprovalRecord = component; + for (const name of ['ask', 'createClientTools', 'useClientToolCalls', 'usePendingClientToolCalls']) supported[name] = component; assert.throws(() => packageVerifier.assertSupportedExports('react/chat', {}), /ApprovalCard/); for (const name of Object.keys(supported)) { const { [name]: _omitted, ...rest } = supported;