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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions apps/website/content/docs/react/ag-ui/guides/client-tools.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.

<ExampleCode file="cockpit/ag-ui/client-tools/react/src/tools.ts" />

Expand All @@ -39,7 +39,9 @@ The native session owns the catalog and physical continuations. The app owns a l

<ExampleCode file="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 `<Chat>` 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 `<Chat clientTools>` 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.

<ExampleCode file="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**.

Expand Down
47 changes: 45 additions & 2 deletions apps/website/content/docs/react/chat/guides/client-tools.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
<ExampleCode file="cockpit/langgraph/client-tools/react/src/booking.tsx" />

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.

<ExampleCode file="cockpit/langgraph/client-tools/react/src/app.tsx" />

Expand All @@ -65,6 +67,47 @@ The existing shared backend is used by default. A developer LangGraph target can

<ExampleCode file="cockpit/langgraph/client-tools/react/src/connection.ts" />

## 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 }) => (
<fieldset>
<legend>Which day?</legend>
{args.days.map((day) => (
<button key={day} type="button" onClick={() => answer({ day })}>
{day}
</button>
))}
</fieldset>
),
}),
});

// 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 <Chat session={session} clientTools={clientTools} />;
}
~~~

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
Expand Down
2 changes: 1 addition & 1 deletion apps/website/src/lib/docs-example-code.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'));
Expand Down
6 changes: 4 additions & 2 deletions cockpit/ag-ui/client-tools/react/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand All @@ -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 `<Chat>` 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 `<Chat clientTools>` 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**.

Expand Down
7 changes: 3 additions & 4 deletions cockpit/ag-ui/client-tools/react/e2e/client-tools.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
89 changes: 47 additions & 42 deletions cockpit/ag-ui/client-tools/react/src/app.spec.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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 }));
Expand All @@ -38,7 +40,6 @@ function fixture(
threadId: null,
native: undefined,
views: [],
bookings: [],
busy: false,
canSubmit: true,
activity: 'idle',
Expand All @@ -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);
Expand All @@ -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,
Expand Down Expand Up @@ -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 });
Expand Down Expand Up @@ -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();
});
Loading
Loading