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
27 changes: 27 additions & 0 deletions libs/react/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <span>{lifecycle?.messageCount ?? 0} sent</span>;
}

<Chat session={session} inputFooter={<SentBadge />} />;
```

| 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
Expand Down
159 changes: 159 additions & 0 deletions libs/react/src/chat/chat-lifecycle.spec.tsx
Original file line number Diff line number Diff line change
@@ -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<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 };
}

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 <output data-testid="probe">{JSON.stringify(lifecycle)}</output>;
}
const probed = () =>
JSON.parse(screen.getByTestId('probe').textContent ?? '') as ChatLifecycle | null;

describe('Chat lifecycle', () => {
it('is null outside a Chat', () => {
render(<Probe />);
expect(probed()).toBeNull();
});

it('is ready after mount, with nothing sent', () => {
const { session } = fakeSession();
const seen: ChatLifecycle[] = [];
render(
<Chat
session={session}
inputFooter={<Probe />}
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(
<Chat
session={session}
inputFooter={<Probe />}
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(<Chat session={session} inputFooter={<Probe />} />);
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(
<Chat session={first.session} inputFooter={<Probe />} onLifecycleChange={onChange} />
);
send('Hello');
view.rerender(
<Chat session={second.session} inputFooter={<Probe />} 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(<Chat session={session} onLifecycleChange={onChange} />);
view.rerender(<Chat session={session} label="Message" onLifecycleChange={onChange} />);
expect(onChange).toHaveBeenCalledTimes(1);
});

it('reaches content in the header and beside a threads sidebar', () => {
const { session } = fakeSession();
render(
<Chat
session={session}
header={<Probe />}
threads={[{ id: 't1', title: 'Trip' }]}
/>
);
expect(probed()).toMatchObject({ componentReady: true });
});
});
68 changes: 55 additions & 13 deletions libs/react/src/chat/chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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. */
Expand Down Expand Up @@ -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(() => {
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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}
Expand All @@ -511,20 +545,28 @@ export function Chat({
</div>
);
// 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 (
<ChatLifecycleContext.Provider value={lifecycle}>
{chat}
</ChatLifecycleContext.Provider>
);
}
return (
<div className="tp-chat-shell">
{threads.length > 0 ? (
<aside className="tp-chat tp-chat-shell__sidebar">
<ThreadList
threads={threads}
activeThreadId={activeThreadId}
onSelect={onThreadSelect}
/>
</aside>
) : null}
{chat}
</div>
<ChatLifecycleContext.Provider value={lifecycle}>
<div className="tp-chat-shell">
{threads.length > 0 ? (
<aside className="tp-chat tp-chat-shell__sidebar">
<ThreadList
threads={threads}
activeThreadId={activeThreadId}
onSelect={onThreadSelect}
/>
</aside>
) : null}
{chat}
</div>
</ChatLifecycleContext.Provider>
);
}

Expand Down
10 changes: 10 additions & 0 deletions libs/react/src/chat/chat.type-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -129,3 +129,13 @@ const renderToolCall: NonNullable<ChatProps['renderToolCall']> = (
<Chat session={session} renderToolCall={renderToolCall} />;
// @ts-expect-error A tool-call renderer is a function.
<Chat session={session} renderToolCall="weather" />;
<Chat
session={session}
onLifecycleChange={(lifecycle) => {
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.
<Chat session={session} onLifecycleChange={true} />;
1 change: 1 addition & 0 deletions libs/react/src/chat/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
Loading
Loading