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
14 changes: 14 additions & 0 deletions libs/react/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -839,6 +839,20 @@ focus survive, and when a chosen suggestion disappears with the greeting, focus
moves to the composer. It is off unless set, and `--tp-welcome-max-width`,
`--tp-welcome-gap` and `--tp-welcome-padding` adjust it.

`renderRunActivity` replaces the typing indicator between a submit and the
run's first assistant message, a window that can be long when the first model
call is slow. It receives the current run's messages (those after the last
user message) and renders in a polite status region after the last message.
Once an assistant message arrives it leaves, and that message's reasoning and
tool area takes over. Returning `null` keeps the typing indicator.

```tsx
<Chat
session={session}
renderRunActivity={({ messages }) => <TurnActivity messages={messages} />}
/>
```

`renderMessageActivity` (on `Chat` and `MessageList`) replaces the reasoning
disclosure and tool-call area of an assistant message with your own content,
shown above the message text. It receives the `row`, its `toolCalls` and the
Expand Down
38 changes: 36 additions & 2 deletions libs/react/src/chat/chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
useState,
type ReactNode,
} from 'react';
import type { AgentSession } from '@threadplane/core';
import type { AgentSession, AgentSnapshot } from '@threadplane/core';
import type { MessageContent } from '@threadplane/content/messages';
import { useAgent } from '../use-agent.js';
import {
Expand Down Expand Up @@ -117,6 +117,15 @@ export interface ChatProps
* `inputFooter`, so the run is not read twice.
*/
readonly typingIndicator?: MessageListProps['typingIndicator'];
/**
* Replaces the typing indicator between a submit and the run's first
* assistant message, which can be long when the first model call is slow.
* It receives the current run's messages (those after the last user message)
* and renders in a polite status region after the last message. Once an
* assistant message arrives it leaves, and the message's own reasoning and
* tool area takes over. Define it outside render or keep it stable.
*/
readonly renderRunActivity?: (context: ChatRunActivityContext) => ReactNode;
/** App-owned content before the draft; see `ChatInputProps.leading`. */
readonly inputLeading?: ChatInputProps['leading'];
/** App-owned controls before Stop and Send; see `ChatInputProps.trailing`. */
Expand Down Expand Up @@ -151,6 +160,12 @@ export interface ChatProps
readonly runStatus?: boolean;
}

/** What `renderRunActivity` receives while a run has no assistant message yet. */
export interface ChatRunActivityContext {
/** The current run's messages: every message after the last user message. */
readonly messages: AgentSnapshot['messages'];
}

/** The options, controlled value and labels of the composer's model picker. */
export interface ChatModelPicker {
readonly options: readonly SelectOption[];
Expand Down Expand Up @@ -225,6 +240,7 @@ export function Chat({
mergeReasoning,
renderMessageActivity,
typingIndicator,
renderRunActivity,
welcome,
runStatus = false,
...input
Expand Down Expand Up @@ -347,6 +363,19 @@ export function Chat({
suggestionFocus.current = false;
composer.current?.focus();
}, [greeted]);
// The run's messages keep their identity while only later snapshots change.
const messages = snapshot.messages;
const runMessages = useMemo(() => {
let from = messages.length;
while (from > 0 && messages[from - 1].role !== 'user') from--;
return messages.slice(from);
}, [messages]);
const runActivity =
renderRunActivity &&
snapshot.status === 'running' &&
!runMessages.some((message) => message.role === 'assistant')
? renderRunActivity({ messages: runMessages })
: null;
const chat = (
<div
className={['tp-chat', greeting && 'tp-chat--welcome', className]
Expand Down Expand Up @@ -387,7 +416,7 @@ export function Chat({
markdownComponents={markdownComponents}
mergeReasoning={mergeReasoning}
renderMessageActivity={renderMessageActivity}
typingIndicator={typingIndicator}
typingIndicator={runActivity === null ? typingIndicator : false}
renderScrollControl={(controls) =>
controls.pinned ? null : (
<ScrollBubble
Expand All @@ -400,6 +429,11 @@ export function Chat({
)
}
>
{runActivity === null ? null : (
<div className="tp-chat__run-activity" role="status" aria-atomic="false">
{runActivity}
</div>
)}
{pending ? approval : null}
{showStopped ? (
<p className="tp-chat__stopped">
Expand Down
11 changes: 11 additions & 0 deletions libs/react/src/chat/chat.type-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,17 @@ ok.className = 'x';
<Chat session={session} header={<h2>Support</h2>} />;
// @ts-expect-error The header is content, not a render function.
<Chat session={session} header={() => null} />;
<Chat
session={session}
renderRunActivity={({ messages }) => <p>{messages.length} so far</p>}
/>;
// @ts-expect-error Run activity is a render function, not content.
<Chat session={session} renderRunActivity={<p />} />;
<Chat
session={session}
// @ts-expect-error The run's messages are readonly.
renderRunActivity={({ messages }) => messages.push(messages[0])}
/>;
<Chat
session={session}
renderMessageActivity={({ row, toolCalls, subagents }) =>
Expand Down
7 changes: 6 additions & 1 deletion libs/react/src/chat/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,12 @@ export {
type ApprovalRecordEntry,
type ApprovalRecordProps,
} from './approval-card.js';
export { Chat, type ChatModelPicker, type ChatProps } from './chat.js';
export {
Chat,
type ChatModelPicker,
type ChatProps,
type ChatRunActivityContext,
} from './chat.js';
export { ChatError, type ChatErrorProps } from './error.js';
export { ChatPopup, type ChatPopupProps } from './chat-popup.js';
export { LauncherButton, type LauncherButtonProps } from './launcher-button.js';
Expand Down
130 changes: 130 additions & 0 deletions libs/react/src/chat/run-activity.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import { act, cleanup, render } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
completeDelivery,
streamingDelivery,
type AgentSession,
type AgentSnapshot,
} from '@threadplane/core';
import { Chat, type ChatRunActivityContext } from './index';

afterEach(cleanup);

function fakeSession(initial: Partial<AgentSnapshot> = {}) {
let snapshot = Object.freeze({
status: 'idle',
messages: [],
toolCalls: [],
...initial,
}) as AgentSnapshot;
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: Partial<AgentSnapshot>) => {
snapshot = Object.freeze({ ...snapshot, ...next }) as AgentSnapshot;
act(() => listeners.forEach((notify) => notify()));
};
return { session: raw as unknown as AgentSession, set };
}
type Messages = AgentSnapshot['messages'];
const user = (id: string, content: string): Messages[number] => ({
id,
role: 'user',
content,
delivery: completeDelivery(id, 'success'),
});
const answered: Messages = [
user('u0', 'Earlier'),
{ id: 'a0', role: 'assistant', content: 'Earlier answer', delivery: completeDelivery('a0', 'success') },
];
const asked: Messages = [...answered, user('u1', 'Next')];
const streaming: Messages = [
...asked,
{ id: 'a1', role: 'assistant', content: 'Work', delivery: streamingDelivery('a1') },
];
const activity = ({ messages }: ChatRunActivityContext) => (
<p data-testid="activity">Working on {messages.length} run messages</p>
);
const region = (view: ReturnType<typeof render>) =>
view.container.querySelector('.tp-chat__run-activity');
const typing = (view: ReturnType<typeof render>) =>
view.container.querySelector('.tp-typing-indicator');

describe('Chat run activity', () => {
it('keeps the typing indicator when the app passes no renderer', () => {
const { session } = fakeSession({ status: 'running', messages: asked });
const view = render(<Chat session={session} />);
expect(region(view)).toBeNull();
expect(typing(view)).not.toBeNull();
});

it('replaces the typing indicator, in a polite status region after the last message', () => {
const { session } = fakeSession({ status: 'running', messages: asked });
const view = render(<Chat session={session} renderRunActivity={activity} />);
const host = region(view)!;
expect(host.getAttribute('role')).toBe('status');
expect(host.getAttribute('aria-atomic')).toBe('false');
expect(host.textContent).toBe('Working on 0 run messages');
expect(typing(view)).toBeNull();
const rows = view.container.querySelectorAll('.tp-chat-message');
expect(
rows[rows.length - 1].compareDocumentPosition(host) & Node.DOCUMENT_POSITION_FOLLOWING
).toBeTruthy();
});

it('is not shown while idle, and appears when the run starts', () => {
const { session, set } = fakeSession({ messages: answered });
const view = render(<Chat session={session} renderRunActivity={activity} />);
expect(region(view)).toBeNull();
set({ status: 'running', messages: asked });
expect(region(view)).not.toBeNull();
});

it('passes only the messages after the last user message', () => {
const tool = { id: 't1', role: 'tool', content: 'ok', delivery: completeDelivery('t1', 'success') } as unknown as Messages[number];
const { session } = fakeSession({ status: 'running', messages: [...asked, tool] });
const seen = vi.fn(activity);
render(<Chat session={session} renderRunActivity={seen} />);
expect(seen.mock.lastCall?.[0].messages.map((message) => message.id)).toEqual(['t1']);
});

it('leaves when the first assistant message arrives and does not return for that run', () => {
const { session, set } = fakeSession({ status: 'running', messages: asked });
const view = render(<Chat session={session} renderRunActivity={activity} />);
expect(region(view)).not.toBeNull();
set({ messages: streaming });
expect(region(view)).toBeNull();
set({ status: 'idle' });
expect(region(view)).toBeNull();
});

it('never shows for a run that continues an existing assistant message', () => {
const { session } = fakeSession({ status: 'running', messages: answered });
const view = render(<Chat session={session} renderRunActivity={activity} />);
expect(region(view)).toBeNull();
});

it('falls back to the typing indicator when the renderer returns null', () => {
const { session } = fakeSession({ status: 'running', messages: asked });
const view = render(<Chat session={session} renderRunActivity={() => null} />);
expect(region(view)).toBeNull();
expect(typing(view)).not.toBeNull();
});

it('gives the renderer the same run messages while only the status changes', () => {
const { session, set } = fakeSession({ status: 'running', messages: asked });
const seen = vi.fn(activity);
render(<Chat session={session} renderRunActivity={seen} />);
const first = seen.mock.lastCall?.[0].messages;
set({ toolCalls: [] });
expect(seen.mock.lastCall?.[0].messages).toBe(first);
});
});
4 changes: 4 additions & 0 deletions libs/react/src/chat/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,10 @@
.tp-approval-card .tp-approval-card__action--primary,
.tp-approval-card .tp-approval-card__action--danger { border: 1px solid ButtonText; }
}
.tp-chat__run-activity {
display: block;
min-inline-size: 0;
}
.tp-chat__header {
display: flex;
flex: none;
Expand Down
11 changes: 11 additions & 0 deletions scripts/react-parity/dispositions.json
Original file line number Diff line number Diff line change
Expand Up @@ -14754,6 +14754,17 @@
"reason": "Options, controlled value and labels for the opt-in model picker Chat renders in the composer before inputTrailing.",
"note": "Placement, choice reporting, declined change, labels, empty options, running state and disabled state are verified with real DOM tests. Chat sends nothing about the value to the session."
},
{
"id": "export:libs/react/src/chat/index.ts#ChatRunActivityContext",
"taskIds": [
"T22",
"T23"
],
"treatment": "react",
"status": "in-progress",
"reason": "The current run's messages passed to Chat's renderRunActivity, which replaces the typing indicator until the run's first assistant message.",
"note": "The window, the status region, typing-indicator replacement, the hand-off to the first assistant message and a continued run are verified with real DOM tests."
},
{
"id": "export:libs/react/src/chat/index.ts#ChatProps",
"taskIds": [
Expand Down
Loading