Skip to content
Merged
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
35 changes: 35 additions & 0 deletions package/src/ai-components/__tests__/conversation.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import React, { type ReactElement, useEffect } from 'react';
import { StyleSheet, Text } from 'react-native';

import { act, fireEvent, render, screen } from '@testing-library/react-native';
import type { LocalMessage, MessageResponse } from 'stream-chat';

import {
AIConversation,
Expand Down Expand Up @@ -719,6 +720,40 @@ describe('fromStreamMessage', () => {
);
});

it('takes a LocalMessage, and hands isAssistant the same type', () => {
const local = {
attachments: [],
created_at: new Date(0),
id: 'm3',
status: 'received',
text: 'From the agent',
type: 'regular',
updated_at: new Date(0),
user: { id: 'juno' },
} as unknown as LocalMessage;
expect(
fromStreamMessage(local, { isAssistant: (message) => message.user?.id === 'juno' }),
).toMatchObject({ role: 'assistant', text: 'From the agent' });
});

it('takes a MessageResponse, such as an event has', () => {
const response = {
ai_generated: true,
attachments: [],
created_at: '1970-01-01T00:00:00.000Z',
generating: true,
id: 'm4',
text: 'Writing',
type: 'regular',
updated_at: '1970-01-01T00:00:00.000Z',
} as unknown as MessageResponse;
expect(fromStreamMessage(response)).toMatchObject({
isGenerating: true,
role: 'assistant',
text: 'Writing',
});
});

it('adapts the person’s message', () => {
expect(fromStreamMessage({ attachments: [], id: 'u1', text: 'Hi' })).toMatchObject({
isGenerating: false,
Expand Down
33 changes: 20 additions & 13 deletions package/src/ai-components/conversation-state/fromStreamMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,12 @@ import { parseMessageParts } from '../message-parts/parseMessageParts';
export type AIStreamMessage = Pick<LocalMessage | MessageResponse, 'attachments' | 'id' | 'text'> &
Record<string, unknown>;

export type FromStreamMessageOptions = {
/** What the adapter reads of a message: a `LocalMessage` or a `MessageResponse` will do. */
type AdaptableMessage = Pick<LocalMessage | MessageResponse, 'attachments' | 'id' | 'text'>;

export type FromStreamMessageOptions<M extends AdaptableMessage = AIStreamMessage> = {
/** Whether the agent wrote it. Defaults to the message's `ai_generated` field. */
isAssistant?: (message: AIStreamMessage) => boolean;
isAssistant?: (message: M) => boolean;
/** The whole of a reasoning step's thinking, when the app has it, such as from live updates. */
reasoningText?: (messageId: string, stepId: string) => string | undefined;
};
Expand Down Expand Up @@ -77,23 +80,25 @@ const responseIdOf = (mark: unknown) =>
* (`{ response_id, of, index, count }`), read as `branch` and `responseId`. A copy the backend
* re-sent of an earlier message has `resent_from`, read as `resentFrom`.
*/
export const fromStreamMessage = (
message: AIStreamMessage,
{ isAssistant, reasoningText }: FromStreamMessageOptions = {},
export const fromStreamMessage = <M extends AdaptableMessage>(
message: M,
{ isAssistant, reasoningText }: FromStreamMessageOptions<M> = {},
): AIMessage => {
const attachments = message.attachments ?? [];
const assistant = isAssistant ? isAssistant(message) : message.ai_generated === true;
const uiDocument = assistant ? parseAIUIDocument(message[AI_UI_CUSTOM_DATA_KEY]) : undefined;
const mark = message[AI_BRANCH_CUSTOM_DATA_KEY];
// The fields past `attachments`, `id` and `text`, which `M` need not declare.
const fields = message as unknown as Record<string, unknown>;
const assistant = isAssistant ? isAssistant(message) : fields.ai_generated === true;
const uiDocument = assistant ? parseAIUIDocument(fields[AI_UI_CUSTOM_DATA_KEY]) : undefined;
const mark = fields[AI_BRANCH_CUSTOM_DATA_KEY];
const branch = branchOf(mark);
const responseId = responseIdOf(mark);
const resentFrom = message[AI_RESENT_FROM_CUSTOM_DATA_KEY];
const resentFrom = fields[AI_RESENT_FROM_CUSTOM_DATA_KEY];
return {
attachments: attachments
.map(attachmentOf)
.filter((attachment): attachment is AIMessageAttachmentData => !!attachment),
id: message.id,
isGenerating: message.generating === true,
isGenerating: fields.generating === true,
parts: parseMessageParts(attachments),
reasoningText: reasoningText
? (stepId: string) => reasoningText(message.id, stepId)
Expand All @@ -113,9 +118,11 @@ export const fromStreamMessage = (
* on every update leaves the others as they were, and `AIConversation` renders only the changed
* ones again. Make one per conversation, such as with `useState(() => createFromStreamMessage())`.
*/
export const createFromStreamMessage = (options?: FromStreamMessageOptions) => {
const cache = new WeakMap<AIStreamMessage, AIMessage>();
return (message: AIStreamMessage) => {
export const createFromStreamMessage = <M extends AdaptableMessage = AIStreamMessage>(
options?: FromStreamMessageOptions<M>,
) => {
const cache = new WeakMap<M, AIMessage>();
return (message: M) => {
let adapted = cache.get(message);
if (!adapted) {
adapted = fromStreamMessage(message, options);
Expand Down
Loading