From 0b9b3318ec8ef65bf35f9cf21cec53e793826153 Mon Sep 17 00:00:00 2001 From: Brian Love Date: Tue, 17 Nov 2026 15:40:48 -0800 Subject: [PATCH] feat(react): report the Chat lifecycle to content inside it and to the app Chat now tracks componentReady, firstMessageSent, messageCount and inputSubmittedAt. Content rendered inside the chat reads them with useChatLifecycle(); an app outside it passes onLifecycleChange. The values live in a small store, so Chat itself does not render again when one changes. messageCount and inputSubmittedAt start again when the session prop changes. firstMessageSent also turns true when a run the composer did not start is seen running, and stays true while the Chat is mounted. --- libs/react/README.md | 27 +++ libs/react/src/chat/chat-lifecycle.spec.tsx | 159 ++++++++++++++++++ libs/react/src/chat/chat.tsx | 68 ++++++-- libs/react/src/chat/chat.type-test.tsx | 10 ++ libs/react/src/chat/index.ts | 1 + libs/react/src/chat/lifecycle.ts | 75 +++++++++ scripts/react-parity/dispositions.json | 18 ++ scripts/react-parity/verify-packages.mjs | 1 + scripts/react-parity/verify-packages.spec.mjs | 2 +- 9 files changed, 347 insertions(+), 14 deletions(-) create mode 100644 libs/react/src/chat/chat-lifecycle.spec.tsx create mode 100644 libs/react/src/chat/lifecycle.ts diff --git a/libs/react/README.md b/libs/react/README.md index b12ea107b..01cff5ab1 100644 --- a/libs/react/README.md +++ b/libs/react/README.md @@ -615,6 +615,33 @@ You hold the value: `Chat` sends nothing about it to the session, so pass the chosen model to your backend yourself. `label` (default "Model") names the list and `placeholder` (default "Choose a model") shows while no option matches. +`Chat` also reports its own lifecycle, for a badge, a debug panel or telemetry. +Content you render inside it, such as `header`, the `welcome` suggestions or a +composer slot, reads the values with `useChatLifecycle()`: + +```tsx +function SentBadge() { + const lifecycle = useChatLifecycle(); + return {lifecycle?.messageCount ?? 0} sent; +} + +} />; +``` + +| Value | Meaning | +| ------------------ | -------------------------------------------------------------------------- | +| `componentReady` | True once the `Chat` has mounted. | +| `firstMessageSent` | True after the first composer submit, or once a run is seen running. | +| `messageCount` | Messages sent from the composer. | +| `inputSubmittedAt` | Epoch milliseconds of the latest composer submit, or null before the first. | + +`messageCount` and `inputSubmittedAt` start again when you pass another +`session`. `firstMessageSent` stays true for as long as the `Chat` is mounted. +Only the composer counts: a message your own code sends with `session.submit` +sets `firstMessageSent` when its run starts and leaves the other two alone. +The hook returns null outside a `Chat`. From there, pass `onLifecycleChange`, +which is called with all four values each time one changes. + Slot content sits inside the composer form and is otherwise untouched: it keeps its own state across drafts and submissions, stays enabled while the composer is `disabled` or `busy`, and supplies its own names and focus styles. Give slot diff --git a/libs/react/src/chat/chat-lifecycle.spec.tsx b/libs/react/src/chat/chat-lifecycle.spec.tsx new file mode 100644 index 000000000..0a2520cf6 --- /dev/null +++ b/libs/react/src/chat/chat-lifecycle.spec.tsx @@ -0,0 +1,159 @@ +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { AgentSession, AgentSnapshot } from '@threadplane/core'; +import { Chat, useChatLifecycle, type ChatLifecycle } from './index'; + +afterEach(() => { + cleanup(); + vi.useRealTimers(); +}); + +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 }; +} + +function send(text: string) { + const draft = screen.getByRole('textbox'); + fireEvent.change(draft, { target: { value: text } }); + fireEvent.keyDown(draft, { key: 'Enter' }); +} + +function Probe() { + const lifecycle = useChatLifecycle(); + return {JSON.stringify(lifecycle)}; +} +const probed = () => + JSON.parse(screen.getByTestId('probe').textContent ?? '') as ChatLifecycle | null; + +describe('Chat lifecycle', () => { + it('is null outside a Chat', () => { + render(); + expect(probed()).toBeNull(); + }); + + it('is ready after mount, with nothing sent', () => { + const { session } = fakeSession(); + const seen: ChatLifecycle[] = []; + render( + } + onLifecycleChange={(next) => seen.push(next)} + /> + ); + const ready = { + componentReady: true, + firstMessageSent: false, + messageCount: 0, + inputSubmittedAt: null, + }; + expect(probed()).toEqual(ready); + expect(seen).toEqual([ready]); + expect(Object.isFrozen(seen[0])).toBe(true); + }); + + it('counts each composer submit and records when it happened', () => { + vi.useFakeTimers(); + vi.setSystemTime(1_000); + const { session } = fakeSession(); + const seen: ChatLifecycle[] = []; + render( + } + onLifecycleChange={(next) => seen.push(next)} + /> + ); + send('Hello'); + expect(session.submit).toHaveBeenCalledWith('Hello'); + expect(probed()).toEqual({ + componentReady: true, + firstMessageSent: true, + messageCount: 1, + inputSubmittedAt: 1_000, + }); + vi.setSystemTime(5_000); + send('Again'); + expect(probed()).toMatchObject({ messageCount: 2, inputSubmittedAt: 5_000 }); + // Ready, then one report per submit. + expect(seen.map((next) => next.messageCount)).toEqual([0, 1, 2]); + // A blank draft is not a submit. + send(' '); + expect(probed()).toMatchObject({ messageCount: 2 }); + }); + + it('marks the first message when a run the composer did not start is running', () => { + const { session, set } = fakeSession(); + render(} />); + set({ status: 'running' }); + expect(probed()).toEqual({ + componentReady: true, + firstMessageSent: true, + messageCount: 0, + inputSubmittedAt: null, + }); + }); + + it('starts the counts again for another session and keeps firstMessageSent', () => { + const first = fakeSession(); + const second = fakeSession(); + const seen: ChatLifecycle[] = []; + const onChange = (next: ChatLifecycle) => seen.push(next); + const view = render( + } onLifecycleChange={onChange} /> + ); + send('Hello'); + view.rerender( + } onLifecycleChange={onChange} /> + ); + const reset = { + componentReady: true, + firstMessageSent: true, + messageCount: 0, + inputSubmittedAt: null, + }; + expect(probed()).toEqual(reset); + expect(seen[seen.length - 1]).toEqual(reset); + }); + + it('reports nothing when a render changes no value', () => { + const { session } = fakeSession(); + const onChange = vi.fn(); + const view = render(); + view.rerender(); + expect(onChange).toHaveBeenCalledTimes(1); + }); + + it('reaches content in the header and beside a threads sidebar', () => { + const { session } = fakeSession(); + render( + } + threads={[{ id: 't1', title: 'Trip' }]} + /> + ); + expect(probed()).toMatchObject({ componentReady: true }); + }); +}); diff --git a/libs/react/src/chat/chat.tsx b/libs/react/src/chat/chat.tsx index 46a9fe400..5eaebeb86 100644 --- a/libs/react/src/chat/chat.tsx +++ b/libs/react/src/chat/chat.tsx @@ -22,6 +22,11 @@ import { } from './client-tools.js'; import { ChatError } from './error.js'; import { useMessageContent } from './internal/use-message-content.js'; +import { + ChatLifecycleContext, + createChatLifecycleStore, + type ChatLifecycle, +} from './lifecycle.js'; import { MessageList, repeatsToolFailure, @@ -149,6 +154,12 @@ export interface ChatProps * `approval` is left to those to announce. Off unless set. */ readonly runStatus?: boolean; + /** + * Called with the chat's lifecycle each time one of its values changes, + * starting with `componentReady` after mount. Content rendered inside the + * chat reads the same values with `useChatLifecycle`. + */ + readonly onLifecycleChange?: (lifecycle: ChatLifecycle) => void; } /** The options, controlled value and labels of the composer's model picker. */ @@ -227,9 +238,23 @@ export function Chat({ typingIndicator, welcome, runStatus = false, + onLifecycleChange, ...input }: ChatProps) { const snapshot = useAgent(session); + const lifecycleChanged = useRef(onLifecycleChange); + lifecycleChanged.current = onLifecycleChange; + const [lifecycle] = useState(() => + createChatLifecycleStore((next) => lifecycleChanged.current?.(next)) + ); + // Another session is another conversation: its counts start again. + useEffect(() => { + lifecycle.set({ + componentReady: true, + messageCount: 0, + inputSubmittedAt: null, + }); + }, [lifecycle, session]); // A session that can regenerate gets the built-in action, unless the app // handles it itself. Built-in actions stay off until `messageActions` is set. const actions = useMemo(() => { @@ -331,6 +356,10 @@ export function Chat({ : welcome : null; const running = snapshot.status === 'running'; + // A run the composer did not start still means a message was sent. + useEffect(() => { + if (running) lifecycle.set({ firstMessageSent: true }); + }, [lifecycle, running]); const showStopped = runStatus && !running && endedStopped(snapshot, session, stopped); // A new run clears the stopped turn and the last announcement, so a repeat is read again. @@ -488,6 +517,11 @@ export function Chat({ footer={inputFooter} busy={snapshot.status === 'running'} onSubmit={(text) => { + lifecycle.set({ + firstMessageSent: true, + messageCount: lifecycle.getSnapshot().messageCount + 1, + inputSubmittedAt: Date.now(), + }); session.submit(text.trim()).catch(ignore); }} onStop={stop} @@ -511,20 +545,28 @@ export function Chat({ ); // The prop's presence, not its length, decides the wrapper, so a list that loads later never remounts the chat. - if (threads === undefined) return chat; + if (threads === undefined) { + return ( + + {chat} + + ); + } return ( -
- {threads.length > 0 ? ( - - ) : null} - {chat} -
+ +
+ {threads.length > 0 ? ( + + ) : null} + {chat} +
+
); } diff --git a/libs/react/src/chat/chat.type-test.tsx b/libs/react/src/chat/chat.type-test.tsx index d9ee94be4..493b833f5 100644 --- a/libs/react/src/chat/chat.type-test.tsx +++ b/libs/react/src/chat/chat.type-test.tsx @@ -129,3 +129,13 @@ const renderToolCall: NonNullable = ( ; // @ts-expect-error A tool-call renderer is a function. ; + { + const sent: number = lifecycle.messageCount; + const at: number | null = lifecycle.inputSubmittedAt; + void [sent, at, lifecycle.componentReady, lifecycle.firstMessageSent]; + }} +/>; +// @ts-expect-error The lifecycle is reported to a function. +; diff --git a/libs/react/src/chat/index.ts b/libs/react/src/chat/index.ts index 068d41860..7ab704235 100644 --- a/libs/react/src/chat/index.ts +++ b/libs/react/src/chat/index.ts @@ -154,6 +154,7 @@ export { type ApprovalRecordProps, } from './approval-card.js'; export { Chat, type ChatModelPicker, type ChatProps } from './chat.js'; +export { useChatLifecycle, type ChatLifecycle } from './lifecycle.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/lifecycle.ts b/libs/react/src/chat/lifecycle.ts new file mode 100644 index 000000000..380fd3be9 --- /dev/null +++ b/libs/react/src/chat/lifecycle.ts @@ -0,0 +1,75 @@ +'use client'; +import { createContext, useContext, useSyncExternalStore } from 'react'; + +/** Readiness and composer submissions of one `Chat`. */ +export interface ChatLifecycle { + /** True once the `Chat` has mounted. */ + readonly componentReady: boolean; + /** + * True after the first message sent from the composer, or once a run is seen + * running, which covers a message the app sent itself, such as a welcome + * suggestion. It stays true for the life of the `Chat`, across sessions. + */ + readonly firstMessageSent: boolean; + /** Messages sent from the composer. Starts again at 0 when `session` changes. */ + readonly messageCount: number; + /** Epoch milliseconds of the latest composer submit. Null again when `session` changes. */ + readonly inputSubmittedAt: number | null; +} + +export interface ChatLifecycleStore { + readonly getSnapshot: () => ChatLifecycle; + readonly subscribe: (notify: () => void) => () => void; + /** Publishes only when a value differs. */ + readonly set: (next: Partial) => void; +} + +/** Holds the values outside React state, so only components that read them render again. */ +export function createChatLifecycleStore( + onChange: (lifecycle: ChatLifecycle) => void +): ChatLifecycleStore { + let snapshot: ChatLifecycle = Object.freeze({ + componentReady: false, + firstMessageSent: false, + messageCount: 0, + inputSubmittedAt: null, + }); + const listeners = new Set<() => void>(); + return { + getSnapshot: () => snapshot, + subscribe(notify) { + listeners.add(notify); + return () => { + listeners.delete(notify); + }; + }, + set(next) { + const keys = Object.keys(next) as (keyof ChatLifecycle)[]; + if (keys.every((key) => next[key] === snapshot[key])) return; + snapshot = Object.freeze({ ...snapshot, ...next }); + for (const notify of [...listeners]) notify(); + onChange(snapshot); + }, + }; +} + +export const ChatLifecycleContext = createContext( + null +); + +const nothing = () => () => undefined; +const absent = () => null; + +/** + * The lifecycle of the `Chat` this component is rendered inside, such as from + * its `header`, `welcome` or composer slots. Null outside a `Chat`; there, use + * the `onLifecycleChange` prop of `Chat` instead. + */ +export function useChatLifecycle(): ChatLifecycle | null { + const store = useContext(ChatLifecycleContext); + return useSyncExternalStore( + store?.subscribe ?? nothing, + store?.getSnapshot ?? absent, + store?.getSnapshot ?? absent + ); +} diff --git a/scripts/react-parity/dispositions.json b/scripts/react-parity/dispositions.json index e1f6dc073..ff6eb0c79 100644 --- a/scripts/react-parity/dispositions.json +++ b/scripts/react-parity/dispositions.json @@ -68,6 +68,24 @@ "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": "export:libs/react/src/chat/index.ts#useChatLifecycle", + "taskIds": ["T03", "T04"], "treatment": "react", "status": "in-progress", + "target": "libs/react/src/chat/lifecycle.ts", + "reason": "Reads the lifecycle of the enclosing Chat, or null outside one; Angular injects the CHAT_LIFECYCLE token from content projected into the chat." + }, + { + "id": "export:libs/react/src/chat/index.ts#ChatLifecycle", + "taskIds": ["T03", "T04"], "treatment": "react", "status": "in-progress", + "target": "libs/react/src/chat/lifecycle.ts", + "reason": "The four lifecycle values as plain readonly fields; Angular's ChatLifecycle holds the same four as signals." + }, + { + "id": "source:libs/react/src/chat/lifecycle.ts", + "taskIds": ["T03", "T04"], "treatment": "react", "status": "in-progress", + "target": "libs/react/src/chat/lifecycle.ts", + "reason": "Chat lifecycle for React: componentReady, firstMessageSent, messageCount and inputSubmittedAt as plain values, read inside Chat with useChatLifecycle and outside it through onLifecycleChange. Angular provides the same four as signals on the CHAT_LIFECYCLE token. Counts start again when the session prop changes, where Angular resets them in clearThread. The LangGraph agent lifecycle timestamps are separate and not covered." + }, { "id": "source:libs/react/src/chat/client-tools.ts", "taskIds": ["T15"], "treatment": "react", "status": "in-progress", diff --git a/scripts/react-parity/verify-packages.mjs b/scripts/react-parity/verify-packages.mjs index 5b8206711..34f207f88 100644 --- a/scripts/react-parity/verify-packages.mjs +++ b/scripts/react-parity/verify-packages.mjs @@ -512,6 +512,7 @@ const SUPPORTED_EXPORTS = { 'createClientTools', 'useClientToolCalls', 'usePendingClientToolCalls', + 'useChatLifecycle', 'ToolObservation', 'SubagentCard', 'subagentsFromEvidence', diff --git a/scripts/react-parity/verify-packages.spec.mjs b/scripts/react-parity/verify-packages.spec.mjs index 6992509e5..85f00f1eb 100644 --- a/scripts/react-parity/verify-packages.spec.mjs +++ b/scripts/react-parity/verify-packages.spec.mjs @@ -1068,7 +1068,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; + for (const name of ['ask', 'createClientTools', 'useClientToolCalls', 'usePendingClientToolCalls', 'useChatLifecycle']) supported[name] = component; assert.throws(() => packageVerifier.assertSupportedExports('react/chat', {}), /ApprovalCard/); for (const name of Object.keys(supported)) { const { [name]: _omitted, ...rest } = supported;