From f3a6d29476702379200cd0ef2a010a78c222ed8d Mon Sep 17 00:00:00 2001 From: Brian Love Date: Sun, 15 Nov 2026 21:44:06 -0800 Subject: [PATCH] feat(react): add a run-activity slot to Chat --- libs/react/README.md | 14 +++ libs/react/src/chat/chat.tsx | 39 ++++++- libs/react/src/chat/chat.type-test.tsx | 11 ++ libs/react/src/chat/index.ts | 6 +- libs/react/src/chat/run-activity.spec.tsx | 130 ++++++++++++++++++++++ libs/react/src/chat/styles.css | 4 + scripts/react-parity/dispositions.json | 11 ++ 7 files changed, 212 insertions(+), 3 deletions(-) create mode 100644 libs/react/src/chat/run-activity.spec.tsx diff --git a/libs/react/README.md b/libs/react/README.md index 3fd270b7d..ee19e2b79 100644 --- a/libs/react/README.md +++ b/libs/react/README.md @@ -753,6 +753,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 + } +/> +``` + `WelcomeSuggestion` requires literal `label`, exact string `value` and `onSelect(value)`. Its native `type="button"` never submits a surrounding form; an enabled, unclaimed click emits the value without trimming or transformation. diff --git a/libs/react/src/chat/chat.tsx b/libs/react/src/chat/chat.tsx index 49551f450..0a675ad69 100644 --- a/libs/react/src/chat/chat.tsx +++ b/libs/react/src/chat/chat.tsx @@ -2,11 +2,12 @@ import { useCallback, useEffect, + useMemo, useRef, 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 { @@ -83,6 +84,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`. */ @@ -110,6 +120,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']; +} + const ignore = () => undefined; /** Transcript, error and composer wired to an app-owned `AgentSession`. */ @@ -139,6 +155,7 @@ export function Chat({ markdownComponents, mergeReasoning, typingIndicator, + renderRunActivity, welcome, runStatus = false, ...input @@ -245,6 +262,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; return (
controls.pinned ? null : ( + {runActivity === null ? null : ( +
+ {runActivity} +
+ )} {pending ? approval : null} {showStopped ? (

diff --git a/libs/react/src/chat/chat.type-test.tsx b/libs/react/src/chat/chat.type-test.tsx index 3a561c18f..c893e5159 100644 --- a/libs/react/src/chat/chat.type-test.tsx +++ b/libs/react/src/chat/chat.type-test.tsx @@ -40,6 +40,17 @@ ok.className = 'x'; } />; // @ts-expect-error Slots are content, not render functions. null} />; +

{messages.length} so far

} +/>; +// @ts-expect-error Run activity is a render function, not content. +} />; + messages.push(messages[0])} +/>; void missing; import type { ReactNode } from 'react'; diff --git a/libs/react/src/chat/index.ts b/libs/react/src/chat/index.ts index ca92d95f6..12fbdc18f 100644 --- a/libs/react/src/chat/index.ts +++ b/libs/react/src/chat/index.ts @@ -137,7 +137,11 @@ export { type ApprovalRecordEntry, type ApprovalRecordProps, } from './approval-card.js'; -export { Chat, type ChatProps } from './chat.js'; +export { + Chat, + 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'; diff --git a/libs/react/src/chat/run-activity.spec.tsx b/libs/react/src/chat/run-activity.spec.tsx new file mode 100644 index 000000000..6e46d9f82 --- /dev/null +++ b/libs/react/src/chat/run-activity.spec.tsx @@ -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 = {}) { + 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) => { + 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) => ( +

Working on {messages.length} run messages

+); +const region = (view: ReturnType) => + view.container.querySelector('.tp-chat__run-activity'); +const typing = (view: ReturnType) => + 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + 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( 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(); + const first = seen.mock.lastCall?.[0].messages; + set({ toolCalls: [] }); + expect(seen.mock.lastCall?.[0].messages).toBe(first); + }); +}); diff --git a/libs/react/src/chat/styles.css b/libs/react/src/chat/styles.css index da5ae7e01..ec432db3e 100644 --- a/libs/react/src/chat/styles.css +++ b/libs/react/src/chat/styles.css @@ -504,6 +504,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__stopped { display: flex; align-items: center; diff --git a/scripts/react-parity/dispositions.json b/scripts/react-parity/dispositions.json index df0d46461..093222181 100644 --- a/scripts/react-parity/dispositions.json +++ b/scripts/react-parity/dispositions.json @@ -14669,6 +14669,17 @@ "reason": "Chat composition wiring useAgent, an owned or app-passed message projection, MessageList and ChatInput to an app-owned AgentSession, with opt-in scoped styles.", "note": "Streaming Markdown, trimmed submit, swallowed submit/stop rejections, error alert, session-keyed draft reset, owned-projection disposal, StrictMode remount and never disposing app content are verified with real DOM tests. Interrupts, attachments, threads, SSR and publication remain incomplete." }, + { + "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": [