Skip to content

Messages and questions ​

world.messages is the conversation between the world and the person, sorted from the oldest message to the newest. It contains the messages of the person, of the world and of its members, the notes of its rules and the questions (messages that carry a form). Your view renders every message together with its images, files, media and charts. It also sends text, images, files, questions and answers on behalf of the person and shows the delivery status of each message.

The messages ​

On every change of the world, the full list sorted from the oldest message to the newest arrives in node.messages. The list below renders each message differently depending on its sender:

jsx
import { useWorld } from './useWorld.js';

// A fake world that greets the person by name.
const arena = {
	name: 'Arena',
	onMessage: (message, world, person) => `Hello, ${person.name}! Welcome to the ${world.name}.`,
};

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: arena } });

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return (
		<>
			{/* The whole list, oldest first, with the id of each message as its key. */}
			<div>
				{world.messages.length === 0 && 'No messages yet.'}
				{world.messages.map((message) => <MessageItem key={message.id} message={message} />)}
			</div>
			<button onClick={() => world.send('hello')}>Say hello</button>
		</>
	);
}

// One message, drawn according to who sent it.
function MessageItem({ message }) {
	const time = new Date(message.time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
	let style = {};
	let words = `${message.from}: ${message.text ?? ''}`; // someone else in the world (an agent)
	if (message.fromMe) {
		// The person's own message, on the right.
		style = { textAlign: 'right' };
		words = `You: ${message.text ?? ''}`;
	} else if (message.isSystem) {
		// A note from the rules of the world, in the middle and quieter.
		style = { textAlign: 'center', fontStyle: 'italic' };
		words = message.text ?? '';
	}
	return (
		<p style={style} title={time}>
			{words}
			{message.image && <><br /><img src={message.image} alt="" style={{ maxHeight: 80 }} /></>}
		</p>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world that greets the person by name.
const arena = {
	name: 'Arena',
	onMessage: (message, world, person) => `Hello, ${person.name}! Welcome to the ${world.name}.`,
};

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: arena } });

const list = document.createElement('div');
const button = document.createElement('button');
button.textContent = 'Say hello';
button.onclick = () => world.send('hello');
document.body.append(list, button);

// One message, drawn according to who sent it.
function messageItem(message) {
	const item = document.createElement('p');
	const time = new Date(message.time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
	if (message.fromMe) {
		// The person's own message, on the right.
		item.style.textAlign = 'right';
		item.textContent = `You: ${message.text ?? ''}`;
	} else if (message.isSystem) {
		// A note from the rules of the world, in the middle and quieter.
		item.style.textAlign = 'center';
		item.style.fontStyle = 'italic';
		item.textContent = message.text ?? '';
	} else {
		// Someone else in the world (an agent), with their name and words.
		item.textContent = `${message.from}: ${message.text ?? ''}`;
	}
	item.title = time;
	if (message.image) {
		const picture = document.createElement('img');
		picture.src = message.image;
		picture.alt = '';
		picture.style.maxHeight = '80px';
		item.append(document.createElement('br'), picture);
	}
	return item;
}

// Called at once, then after every change of the world, with the whole list oldest first.
world.subscribe((node) => {
	if (node.messages.length === 0) {
		list.textContent = 'No messages yet.';
		return;
	}
	list.replaceChildren(...node.messages.map(messageItem));
});
Live, on a fake world
Open

Every message has these fields (GuiMessage):

FieldWhat it is
idIdentifier that stays stable for the lifetime of the message. Use it as the React key.
textThe text of the message. It is null for a message without text such as an image alone.
imageURL or data URI of the first image for img.src. It is null when the message has no image.
imagesAll images in order.
filesAttached files as { name, type, url }.
mediaVideos, audio, PDFs and links.
chartsChart data.
fromDisplay name of the sender.
fromIdId of the member or of the world that wrote the message. It is null for the person (People and roles).
timeThe moment of the message in milliseconds since the epoch. Date.now() uses the same unit.
fromMetrue for the messages of the person.
isSystemtrue for the notes of the rules of the world.

These fields exist only on some messages:

FieldOnWhat it is
statusthe person's messages'sending', 'sent' or 'failed'.
retry()the person's messagesResends a failed message.
forma questionThe form to fill.
isAnswereda questiontrue after the question has been answered.
answer(values)a questionAnswers it.
valuesan answerThe answered values keyed by field name.
answersan answerThe id of the question it answers.

A correct list follows four rules:

  • Use id as the key and never the index. loadMore prepends older messages and shifts every index without changing any id.
  • text is nullable. Read it as message.text ?? '' and render images, files, media and charts from their own fields (below).
  • Never use innerHTML. Because the text is untrusted input, assign it to textContent or let React render it.
  • time is a number. new Date(message.time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) formats it in the locale of the person.

Pictures, files, videos and charts ​

Content other than text has its own fields: images, files, charts and media for videos, audio, PDFs and links. In this example a fake agent replies with one item of each kind:

jsx
import { useWorld } from './useWorld.js';

// A small picture as an inline SVG, because a picture in a message is an image source.
const PICTURE = `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="80" height="40"><rect width="80" height="40" fill="teal"/></svg>')}`;

// A fake agent whose answer holds words, a picture, a file, a video and a chart.
const coach = {
	name: 'Coach',
	onMessage: () => ({
		text: 'Here is your week',
		images: [PICTURE],
		files: [{ name: 'plan.txt', type: 'text/plain', url: `data:text/plain;base64,${btoa('Monday: run 5 km')}` }],
		media: [{ url: 'https://example.com/warm-up.mp4', type: 'video/mp4', title: 'Warm-up' }],
		charts: [{ kind: 'bar', series: [{ label: 'Steps', points: [['Mon', 4000], ['Tue', 5200]] }], alt: 'Steps per day' }],
	}),
};

export default function App() {
	// While building: the fake agent. In the webapp: useWorld()
	const { world: agent, error } = useWorld({ fake: { agent: coach } });

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!agent) return <p>Connecting…</p>;
	return (
		<>
			<button onClick={() => agent.send('My week, please')}>Show my week</button>
			<div>
				{agent.messages.map((message) => <MessageItem key={message.id} message={message} />)}
			</div>
		</>
	);
}

// One message, with its words and then its pictures, files, media and charts, each in its own field.
// An older webapp does not give these fields, and `?? []` covers that case.
function MessageItem({ message }) {
	return (
		<div style={{ marginBottom: 12 }}>
			<div>{message.fromMe ? 'You' : message.from}: {message.text ?? ''}</div>
			{(message.images ?? []).map((image, index) => <img key={index} src={image} alt="" />)}
			{(message.files ?? []).map((file, index) => (
				// The file of an agent arrives without a name and needs words of your own.
				<a key={index} href={file.url} download={file.name ?? 'file'}>Download {file.name ?? 'the file'} ({file.type})</a>
			))}
			{(message.media ?? []).map((media, index) => (
				// A link loads nothing until the person opens it.
				<div key={index}><a href={media.url} target="_blank">{media.title ?? media.alt} ({media.type})</a></div>
			))}
			{(message.charts ?? []).map((chart, index) => (
				<div key={index}>
					<div>{chart.alt} ({chart.kind} chart)</div>
					{chart.series.map((series) => (
						<div key={series.label}>{series.label}: {series.points.map(([x, y]) => `${x} ${y}`).join(' · ')}</div>
					))}
				</div>
			))}
		</div>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A small picture as an inline SVG, because a picture in a message is an image source.
const PICTURE = `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="80" height="40"><rect width="80" height="40" fill="teal"/></svg>')}`;

// A fake agent whose answer holds words, a picture, a file, a video and a chart.
const coach = {
	name: 'Coach',
	onMessage: () => ({
		text: 'Here is your week',
		images: [PICTURE],
		files: [{ name: 'plan.txt', type: 'text/plain', url: `data:text/plain;base64,${btoa('Monday: run 5 km')}` }],
		media: [{ url: 'https://example.com/warm-up.mp4', type: 'video/mp4', title: 'Warm-up' }],
		charts: [{ kind: 'bar', series: [{ label: 'Steps', points: [['Mon', 4000], ['Tue', 5200]] }], alt: 'Steps per day' }],
	}),
};

// While building: the fake agent. In the webapp: const agent = await connectToHost();
const agent = await connectToHost({ fake: { agent: coach } });

const button = document.createElement('button');
button.textContent = 'Show my week';
button.onclick = () => agent.send('My week, please');
const list = document.createElement('div');
document.body.append(button, list);

// Adds a line of text to an element.
function addLine(parent, text) {
	const line = document.createElement('div');
	line.textContent = text;
	parent.append(line);
	return line;
}

// One message, with its words and then its pictures, files, media and charts, each in its own field.
// An older webapp does not give these fields, and `?? []` covers that case.
function messageItem(message) {
	const item = document.createElement('div');
	item.style.marginBottom = '12px';
	addLine(item, `${message.fromMe ? 'You' : message.from}: ${message.text ?? ''}`);
	for (const image of message.images ?? []) {
		const picture = document.createElement('img');
		picture.src = image;
		picture.alt = '';
		item.append(picture);
	}
	for (const file of message.files ?? []) {
		// The file of an agent arrives without a name and needs words of your own.
		const link = document.createElement('a');
		link.href = file.url;
		link.download = file.name ?? 'file';
		link.textContent = `Download ${file.name ?? 'the file'} (${file.type})`;
		item.append(link);
	}
	for (const media of message.media ?? []) {
		// A link loads nothing until the person opens it.
		const link = document.createElement('a');
		link.href = media.url;
		link.target = '_blank';
		link.textContent = `${media.title ?? media.alt} (${media.type})`;
		addLine(item, '').append(link);
	}
	for (const chart of message.charts ?? []) {
		addLine(item, `${chart.alt} (${chart.kind} chart)`);
		for (const series of chart.series) {
			addLine(item, `${series.label}: ${series.points.map(([x, y]) => `${x} ${y}`).join(' · ')}`);
		}
	}
	return item;
}

// Called at once, then after every change.
agent.subscribe((node) => {
	list.replaceChildren(...node.messages.map(messageItem));
});
Live, on a fake world
Open

text does not repeat the attachments. Render the attachments from media and charts and render text unchanged. Content of a kind that the kit does not support yet arrives as plain text in text. A view that always renders text therefore never loses it.

Each of the four fields is rendered in its own way:

  • images holds URLs or data URIs that each go in an <img> of their own. The first one is also in image for views that render a single image per message.
  • files holds { name, type, url } objects whose url is a data URI usable as the href of an <a download>. Files sent by an agent have name: null and need a label of your own. After the webapp reloads, a file sent by the person keeps its name but its url becomes null.
  • media holds remote resources. url is the address, type is a MIME type or a provider type ('video/mp4', 'audio/mpeg', 'application/pdf', 'video/youtube', ...) and title and alt describe the resource in text. Render videos and audio in a <video> or <audio> with preload="none" to load nothing before playback starts. An 'image/...' type goes in an <img> and any other type, PDFs included, becomes a link.
  • charts holds data with a kind ('bar', 'line' or 'pie'), a series of [x, y] points and an alt description. Render the data with your own code or with a charting library (Chart) and use alt as the accessible label of the drawing.
js
// A video plays in the page; nothing loads before the person presses play.
const video = document.createElement('video');
video.src = media.url;
video.controls = true;
video.preload = 'none';
video.setAttribute('aria-label', media.alt);

Pitfall

Mount a YouTube or Vimeo player ('video/youtube', 'video/vimeo') only on click. The player is an embedded page of the provider that loads its scripts and may set cookies as soon as it is mounted. Render the title and a play button as the webapp does in its own conversation and replace them with the player when the person clicks.

The four fields have existed since the webapp release of November 2026 and are missing in older webapps such as a phone app that has not been updated. Read them with defaults such as message.images ?? [] and fall back on image and text. Types › GuiMessage describes every field.

Who sent what ​

Messages come from three kinds of sender and a view usually renders each kind differently:

  • The person (fromMe: true). from holds a fixed string and never the nickname of the person (that one is in world.me). Test fromMe and render a label of your own such as "You". Only these messages have a status.
  • The rules of the world (isSystem: true), for example "Round 2 begins" or "It is your turn". Notes, whose from is the name of the world, carry text, media, charts and questions but never images or files. Views usually render them less prominently than the conversation. In a fake world every reply of onMessage and onAction is a note unless its from names a member of the world.
  • Everyone else, whose name is in from: an agent, another member of the world or the agent itself in the view of an agent.

Matching fromId against members gives the member who wrote a message. When showsSenders is false the world asks the view not to show senders (Who wrote it). The recipe Group messages by who sent them groups consecutive messages of one sender.

Sending text ​

world.send(text) sends text on behalf of the person. The message appears in world.messages immediately with status: 'sending' and the view must not append it itself. send then resolves with the outcome:

ResultMeaningWhat the view does
'sent'Delivered.Nothing. The message already shows 'sent'.
'failed'Not delivered. The message stays in the list with status: 'failed'.Nothing. The list offers a retry (below).
'not-allowed'The text was empty or the rules do not accept a message now, for example because it is not the turn of the person. Nothing was added to the list.Restore the text and show the reason.
jsx
import { useState } from 'react';
import { useWorld } from './useWorld.js';

// A fake world that answers every message.
const arena = {
	name: 'Arena',
	onMessage: (message) => `Got it: ${message.text}`,
};

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: arena } });

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return (
		<>
			<ul>
				{world.messages.map((message) => (
					<li key={message.id}>
						{message.fromMe ? 'You' : message.from}: {message.text}
						{/* The person's messages have a status: 'sending', 'sent' or 'failed'. */}
						{message.fromMe && ` (${message.status})`}
					</li>
				))}
			</ul>
			<MessageBox world={world} />
		</>
	);
}

function MessageBox({ world }) {
	const [text, setText] = useState('');
	const [notice, setNotice] = useState('');

	async function handleSubmit(event) {
		event.preventDefault();
		const words = text.trim();
		if (!words) return;
		setText('');
		// 'sent' and 'failed' both leave the message in the list, with its status.
		// 'not-allowed' means the rules did not take it, and the view gives the person their words back.
		const result = await world.send(words);
		if (result === 'not-allowed') {
			setText(words);
			setNotice('You cannot send now.');
		} else {
			setNotice('');
		}
	}

	return (
		<>
			<form onSubmit={handleSubmit}>
				<input value={text} onChange={(event) => setText(event.target.value)} placeholder="Write a message" />
				{/* The rules say when the person may send (their turn, for example). */}
				<button disabled={!world.canSend}>Send</button>
			</form>
			<p>{notice}</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world that answers every message.
const arena = {
	name: 'Arena',
	onMessage: (message) => `Got it: ${message.text}`,
};

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: arena } });

const list = document.createElement('ul');
const form = document.createElement('form');
const input = document.createElement('input');
const button = document.createElement('button');
const notice = document.createElement('p');
input.placeholder = 'Write a message';
button.textContent = 'Send';
form.append(input, button);
document.body.append(list, form, notice);

form.onsubmit = async (event) => {
	event.preventDefault();
	const text = input.value.trim();
	if (!text) return;
	input.value = '';
	// 'sent' and 'failed' both leave the message in the list, with its status.
	// 'not-allowed' means the rules did not take it, and the view gives the person their words back.
	const result = await world.send(text);
	if (result === 'not-allowed') {
		input.value = text;
		notice.textContent = 'You cannot send now.';
	} else {
		notice.textContent = '';
	}
};

// Called at once, then after every change of the world.
world.subscribe((node) => {
	list.replaceChildren(...node.messages.map((message) => {
		const item = document.createElement('li');
		const who = message.fromMe ? 'You' : message.from;
		// The person's messages have a status: 'sending', 'sent' or 'failed'.
		item.textContent = message.fromMe ? `${who}: ${message.text} (${message.status})` : `${who}: ${message.text}`;
		return item;
	}));
	// The rules say when the person may send (their turn, for example).
	button.disabled = !node.canSend;
});
Live, on a fake world
Open
  • Disable the button while canSend is false. canSend reflects the rules and is also false while a message is pending. This prevents double sends (The actions the rules offer).
  • Inside the webapp send can also reject: with 'failed' when the webapp cannot complete the call and with 'too-big' for a file over 20 MB. Errors and the person's controls shows how to catch the error.

Delivery and retry ​

The messages of the person have a status that is 'sending' while they are pending and then becomes 'sent' or 'failed'. On a failed message, retry() resends the same message without adding an entry to the list and resolves with the same values as send.

This fake world fails the first message on purpose (failNext: true):

jsx
import { useWorld } from './useWorld.js';

// A fake world whose first message fails (`failNext`), to let you try a retry.
const arena = {
	name: 'Arena',
	failNext: true,
	onMessage: (message) => `Got it: ${message.text}`,
};

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: arena } });

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return (
		<>
			<ul>
				{world.messages.map((message) => (
					<li key={message.id}>
						{message.fromMe ? `You: ${message.text} (${message.status}) ` : `${message.from}: ${message.text}`}
						{/* A failed message can be sent again, as the same message and not a new one. */}
						{message.status === 'failed' && <button onClick={() => message.retry()}>Retry</button>}
					</li>
				))}
			</ul>
			<button onClick={() => world.send('hello')}>Say hello</button>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world whose first message fails (`failNext`), to let you try a retry.
const arena = {
	name: 'Arena',
	failNext: true,
	onMessage: (message) => `Got it: ${message.text}`,
};

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: arena } });

const list = document.createElement('ul');
const button = document.createElement('button');
button.textContent = 'Say hello';
button.onclick = () => world.send('hello');
document.body.append(list, button);

// Called at once, then after every change of the world.
world.subscribe((node) => {
	list.replaceChildren(...node.messages.map((message) => {
		const item = document.createElement('li');
		if (!message.fromMe) {
			item.textContent = `${message.from}: ${message.text}`;
			return item;
		}
		item.textContent = `You: ${message.text} (${message.status}) `;
		// A failed message can be sent again, as the same message and not a new one.
		if (message.status === 'failed') {
			const retry = document.createElement('button');
			retry.textContent = 'Retry';
			retry.onclick = () => message.retry();
			item.append(retry);
		}
		return item;
	}));
});
Live, on a fake world
Open

Show Retry only when status is 'failed'. The recipes Show whether a message was delivered and Retry a failed message show other ways to render the delivery status.

Sending a picture ​

world.send({ image, text }) sends an image with an optional text. image is a URL or, more often, a data URI that comes from a canvas (canvas.toDataURL('image/jpeg', 0.8)), from a file picked by the person or from the camera.

jsx
import { useEffect, useRef } from 'react';
import { useWorld } from './useWorld.js';

// A fake world that likes pictures.
const gallery = {
	name: 'Gallery',
	onMessage: (message) => (message.image ? 'What a nice picture!' : 'Send me a picture.'),
};

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: gallery } });

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return (
		<>
			<PictureSender world={world} />
			<div>
				{world.messages.map((message) => (
					<p key={message.id}>
						{message.fromMe ? 'You' : message.from}: {message.text ?? ''}
						{message.image && <img src={message.image} alt={message.text ?? 'A picture'} style={{ display: 'block' }} />}
					</p>
				))}
			</div>
		</>
	);
}

function PictureSender({ world }) {
	const canvasRef = useRef(null);

	// The picture to send, drawn here on a canvas. A photo or a file works the same way.
	useEffect(() => {
		const context = canvasRef.current.getContext('2d');
		context.fillStyle = 'crimson';
		context.fillRect(0, 0, 60, 60);
	}, []);

	// A picture is an image source (a data URI), with words that go with it.
	function sendPicture() {
		world.send({ image: canvasRef.current.toDataURL('image/png'), text: 'A red square' });
	}

	return (
		<>
			<canvas ref={canvasRef} width={60} height={60} />
			<button onClick={sendPicture}>Send a picture</button>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world that likes pictures.
const gallery = {
	name: 'Gallery',
	onMessage: (message) => (message.image ? 'What a nice picture!' : 'Send me a picture.'),
};

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: gallery } });

// The picture to send, drawn here on a canvas. A photo or a file works the same way.
const canvas = document.createElement('canvas');
canvas.width = 60;
canvas.height = 60;
const context = canvas.getContext('2d');
context.fillStyle = 'crimson';
context.fillRect(0, 0, 60, 60);

const button = document.createElement('button');
button.textContent = 'Send a picture';
// A picture is an image source (a data URI), with words that go with it.
button.onclick = () => world.send({ image: canvas.toDataURL('image/png'), text: 'A red square' });
const list = document.createElement('div');
document.body.append(canvas, button, list);

// Called at once, then after every change of the world.
world.subscribe((node) => {
	list.replaceChildren(...node.messages.map((message) => {
		const item = document.createElement('p');
		item.textContent = `${message.fromMe ? 'You' : message.from}: ${message.text ?? ''}`;
		if (message.image) {
			const picture = document.createElement('img');
			picture.src = message.image;
			picture.alt = message.text ?? 'A picture';
			picture.style.display = 'block';
			item.append(picture);
		}
		return item;
	}));
});
Live, on a fake world
Open

To send an image picked by the person, read the file as a data URI:

js
const picker = document.createElement('input');
picker.type = 'file';
picker.accept = 'image/*';
picker.onchange = () => {
  const file = picker.files[0];
  if (!file) return;
  const reader = new FileReader();
  reader.onload = () => world.send({ image: reader.result, text: file.name });
  reader.readAsDataURL(file);
};

A phone photo can take several megabytes. Downscale it on a canvas first (a width of 1,000 pixels is enough for most worlds) and send canvas.toDataURL('image/jpeg', 0.8) instead of the original file. The camera is covered in The camera and the rest of the browser and in the recipe Send a photo from the camera.

Sending a file ​

world.send({ file, text }) sends a file of at most 20 MB. Pass the File of a file input or of a drop event as it is and let send read its content.

js
const picker = document.createElement('input');
picker.type = 'file';
picker.onchange = async () => {
  const file = picker.files[0];
  if (!file) return;
  try {
    await world.send({ file, text: file.name });
  } catch (error) {
    if (error.code === 'too-big') showError('Pick a file under 20 MB.');
  }
};
  • Delivered does not mean read. A result of 'sent' means that the world has received the file. Only agents with a file input read it and the others ignore it without an error. Since the owner of the world decides which agents have a file input, ask them before offering a file button.
  • One image or one file per message. A message with both resolves with 'failed' and sends nothing.
  • A file over 20 MB makes send reject with 'too-big' before anything is sent.
  • A webapp that predates file sending makes send reject with 'not-allowed-verb' and sends nothing. Hide the file button when this code arrives.

The message of the person has the file in files immediately. send › Send a file has a live example and the full details.

Sending a question ​

world.send({ text, form }) sends a question on behalf of the person. Its form has the same shape as the forms in the questions of the world (below):

js
await world.send({
  text: 'Which day suits you?',
  form: { fields: [{ name: 'day', type: 'select', options: ['Monday', 'Tuesday'] }] },
});

The message appears in the list with its form and gets isAnswered: true when the receiver answers. Because the form is also sent as plain text, a world or an agent that does not read forms still understands the question.

Questions from the world ​

A question is a message with a form. Your view renders the form and message.answer(values) sends the answer of the person.

jsx
import { useWorld } from './useWorld.js';

// A fake world that asks a question, then replies to the answer.
const arena = {
	name: 'Arena',
	onMessage: (message) => {
		// An answer arrives as a message with `values`, by field name.
		if (message.values) return `You go ${message.values.direction}.`;
		return {
			text: 'Which way?',
			form: { fields: [{ name: 'direction', label: 'Direction', type: 'select', options: ['left', 'right'] }] },
		};
	},
};

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: arena } });

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;

	// The question still open is the newest one from the world with a form that is not answered yet.
	const question = world.messages.findLast((message) => message.form && !message.fromMe && !message.isAnswered);
	return (
		<>
			<ul>
				{world.messages.map((message) => (
					<li key={message.id}>
						{message.values
							? `You answered: ${Object.values(message.values).join(', ')}`
							: `${message.fromMe ? 'You' : message.from}: ${message.text}`}
					</li>
				))}
			</ul>
			<button onClick={() => world.send('start')}>Start the game</button>
			{/* The key keeps the person's choice while the question stays the same. */}
			{question && <QuestionForm key={question.id} message={question} />}
		</>
	);
}

// The form of a question, with one field per field of `message.form`.
function QuestionForm({ message }) {
	function handleSubmit(event) {
		event.preventDefault();
		message.answer(Object.fromEntries(new FormData(event.target)));
	}

	return (
		<form onSubmit={handleSubmit}>
			{message.form.fields.map((field) => (
				<label key={field.name}>
					{field.label ?? field.name}{' '}
					{field.type === 'select' ? (
						<select name={field.name}>
							{/* Options can be plain strings or { value, label }. */}
							{(field.options ?? []).map((option) => {
								const value = typeof option === 'string' ? option : option.value;
								return <option key={value} value={value}>{typeof option === 'string' ? option : option.label}</option>;
							})}
						</select>
					) : (
						<input name={field.name} type={field.type === 'number' ? 'number' : 'text'} />
					)}
				</label>
			))}{' '}
			<button>Answer</button>
		</form>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world that asks a question, then replies to the answer.
const arena = {
	name: 'Arena',
	onMessage: (message) => {
		// An answer arrives as a message with `values`, by field name.
		if (message.values) return `You go ${message.values.direction}.`;
		return {
			text: 'Which way?',
			form: { fields: [{ name: 'direction', label: 'Direction', type: 'select', options: ['left', 'right'] }] },
		};
	},
};

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: arena } });

const list = document.createElement('ul');
const start = document.createElement('button');
start.textContent = 'Start the game';
start.onclick = () => world.send('start');
const formPlace = document.createElement('div');
document.body.append(list, start, formPlace);

// Builds the form of a question, with one field per field of `message.form`.
function questionForm(message) {
	const form = document.createElement('form');
	for (const field of message.form.fields) {
		const label = document.createElement('label');
		const input = document.createElement(field.type === 'select' ? 'select' : 'input');
		input.name = field.name;
		if (field.type === 'number') input.type = 'number';
		// Options can be plain strings or { value, label }.
		for (const option of field.options ?? []) {
			const choice = document.createElement('option');
			choice.value = typeof option === 'string' ? option : option.value;
			choice.textContent = typeof option === 'string' ? option : option.label;
			input.append(choice);
		}
		label.append(`${field.label ?? field.name} `, input);
		form.append(label);
	}
	const button = document.createElement('button');
	button.textContent = 'Answer';
	form.append(' ', button);
	form.onsubmit = (event) => {
		event.preventDefault();
		message.answer(Object.fromEntries(new FormData(form)));
	};
	return form;
}

let shownQuestionId = null;
// Called at once, then after every change of the world.
world.subscribe((node) => {
	list.replaceChildren(...node.messages.map((message) => {
		const item = document.createElement('li');
		item.textContent = message.values
			? `You answered: ${Object.values(message.values).join(', ')}`
			: `${message.fromMe ? 'You' : message.from}: ${message.text}`;
		return item;
	}));
	// The question still open is the newest one from the world with a form that is not answered yet.
	const question = node.messages.findLast((message) => message.form && !message.fromMe && !message.isAnswered);
	// Build the form only when the question changes, to keep what the person chose through other changes.
	if ((question?.id ?? null) === shownQuestionId) return;
	shownQuestionId = question?.id ?? null;
	formPlace.replaceChildren(...(question ? [questionForm(question)] : []));
});
Live, on a fake world
Open

The form. message.form.fields is the list of fields:

FieldWhat it is
nameThe key of the value in values.
type'select', 'text', 'number' or another type that the world uses.
labelThe label to render. Fall back on name when it is missing.
optionsThe options of a choice as { value, label }. Plain strings are accepted only in the forms you send.

The answer. message.answer(values) takes an object keyed by field name such as { direction: 'right' } and resolves like send:

  • a question is answered once, after which isAnswered is true and answer resolves with 'not-allowed'
  • answer resolves with 'not-allowed' when values contains no field of the form
  • the answer appears in the list as a message of the person that carries three things: the answered values, a text version of the answer for views that render only text and the id of the question in answers.

Because FormData yields strings, convert a 'number' field with Number(value).

The open question is the newest unanswered question from the world:

js
const open = node.messages.findLast((message) => message.form && !message.fromMe && !message.isAnswered);

Keep the form mounted while the question does not change. A form rebuilt on every change of the world (a clock, a score) loses the input of the person. In React set key={question.id} on the form. In plain JavaScript the example rebuilds it only when the id of the open question changes.

The recipe Answer a question with a form and the component QuestionForm handle more field types.

Older messages: loadMore ​

world.messages starts with the recent part of the conversation. await world.loadMore() prepends older messages and resolves with the number of messages it added or with 0 once none are left. A fake world has no older messages and always resolves with 0.

js
const older = document.createElement('button');
older.textContent = 'Show older messages';
older.onclick = async () => {
  const added = await world.loadMore();
  if (added === 0) older.remove(); // nothing older: no need for the button
};

The prepended messages arrive through subscribe like any other change. The recipe Load older messages keeps the messages that the person is reading in place while older ones are prepended above them.

Things to watch ​

  • Do not append messages yourself. The message of the person is in world.messages as soon as send is called.
  • Key by id. Indexes change when older messages are prepended.
  • text is nullable and untrusted. Never put it in innerHTML.
  • text does not include attachments. Read images, files, media and charts from their fields with ?? [] for older webapps.
  • Never mutate the list. filter returns a new array but sort works in place and needs a copy first ([...node.messages]).
  • Event handlers read world.get().messages instead of a value captured earlier (Thinking in views).

Next steps ​

The UNaIVERSE GUI kit, released under the Apache License 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.