world.send(value)
Sends a message to the world on behalf of the person: text, an image, a file or a question with a form.
const result = await world.send('left');Parameters
value: a SendValue, one of:
| Value | Message |
|---|---|
string | Text. |
{ image, text? } | An image. image is a data URI or URL (data:image/jpeg;base64,...). |
{ file, text? } | A file of at most 20 MB. file is a File, a Blob or a FileToSend { name, type, url } whose url is a base64 data URI. |
{ text, form } | A question. form is a FormSpec shown after text. |
A message carries at most one attachment and cannot have both image and file.
Returns
A Promise that resolves to a SendResult:
| Result | Meaning |
|---|---|
'sent' | Delivered. A file delivered to the world is not necessarily read by any agent (Caveats). |
'failed' | Not delivered. The message stays in messages with status: 'failed'. retry() sends it again. send also returns it when value holds an image together with a file or a file that cannot be read. In these two cases nothing is sent and messages does not change. |
'not-allowed' | Nothing sent. canSend is false, value is empty or the agent is unreachable. |
The promise rejects with an error whose code is 'too-big' (a file over 20 MB), 'not-allowed-verb' (a webapp that predates file sending) or 'failed' (the webapp could not run the call). See Troubleshooting.
Usage
Send text and see each result
The fake world fails the first message (failNext: true). Pressing Send with the box empty gives 'not-allowed', the first text gives 'failed' and the next one gives 'sent'.
import { useState } from 'react';
import { useWorld } from './useWorld.js';
// A fake world that answers every message. `failNext` makes the first message fail
// to let you see each result of `send`.
const arena = {
name: 'Arena',
failNext: true,
onMessage: (message) => `Got ${message.text}`,
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: arena } });
const [text, setText] = useState('');
const [result, setResult] = useState('Nothing sent yet.');
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
// `send` resolves when the message is delivered ('sent'), not delivered ('failed'),
// or not sent at all ('not-allowed', when it is empty or not the person's turn).
const onSend = async () => {
const outcome = await world.send(text);
setResult(`Result: ${outcome}`);
};
return (
<>
<input placeholder="Message" value={text} onChange={(event) => setText(event.target.value)} />
<button onClick={onSend}>Send</button>
<p>{result}</p>
<ul>
{world.messages.map((message) => (
<li key={message.id}>
{message.from}: {message.text}{message.fromMe ? ` (${message.status})` : ''}
</li>
))}
</ul>
</>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// A fake world that answers every message. `failNext` makes the first message fail
// to let you see each result of `send`.
const arena = {
name: 'Arena',
failNext: true,
onMessage: (message) => `Got ${message.text}`,
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: arena } });
const input = document.createElement('input');
input.placeholder = 'Message';
const button = document.createElement('button');
button.textContent = 'Send';
const result = document.createElement('p');
result.textContent = 'Nothing sent yet.';
const list = document.createElement('ul');
document.body.append(input, button, result, list);
// `send` resolves when the message is delivered ('sent'), not delivered ('failed'),
// or not sent at all ('not-allowed', when it is empty or not the person's turn).
button.onclick = async () => {
const outcome = await world.send(input.value);
result.textContent = `Result: ${outcome}`;
};
// The messages, with the delivery status of those the person sent.
world.subscribe((node) => {
list.replaceChildren(...node.messages.map((message) => {
const item = document.createElement('li');
const delivery = message.fromMe ? ` (${message.status})` : '';
item.textContent = `${message.from}: ${message.text}${delivery}`;
return item;
}));
});The message is added to messages immediately with status: 'sending' and changes to 'sent' or 'failed' when the promise resolves.
Send only when the person may
canSend is true when the rules of the world accept a message from the person. Disable your controls while it is false:
world.subscribe((node) => {
sendButton.disabled = !node.canSend;
});Send a picture
Encode a canvas as JPEG:
const image = canvas.toDataURL('image/jpeg', 0.8);
await world.send({ image, text: 'My drawing' });Send a file
{ file, text } sends a file. The example builds the file from the text in the box. The second button sends a file over 20 MB to trigger 'too-big'. The fake world reads the file from message.files and replies with its name and type.
import { useState } from 'react';
import { useWorld } from './useWorld.js';
// A fake world that finds the file the person sent in `message.files` and answers with its name and type.
const desk = {
name: 'Desk',
onMessage: (message) => {
const file = message.files?.[0];
return file ? `Got ${file.name} (${file.type})` : 'Send me a file.';
},
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: desk } });
const [notes, setNotes] = useState('');
const [result, setResult] = useState('Nothing sent yet.');
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
// Sends a file with words and shows how it ended.
async function sendFile(file, text) {
try {
const outcome = await world.send({ file, text });
setResult(`Result: ${outcome}`);
} catch (sendError) {
// 'too-big' means that the file is over 20 MB and nothing was sent.
setResult(`Error: ${sendError.code}`);
}
}
return (
<>
<textarea placeholder="Notes" value={notes} onChange={(event) => setNotes(event.target.value)} />
{/* The page makes this file. A File from a file field or a drop is sent the same way. */}
<button onClick={() => sendFile(new File([notes], 'notes.txt', { type: 'text/plain' }), 'My notes')}>Send as a file</button>
<button onClick={() => sendFile(new Blob([new Uint8Array(21 * 1024 * 1024)]), 'A big file')}>Send a 21 MB file</button>
<p>{result}</p>
<ul>
{world.messages.map((message) => <MessageLine key={message.id} message={message} />)}
</ul>
</>
);
}
// One message, with the names of its files.
function MessageLine({ message }) {
// Read `files` with a fallback, because an older webapp leaves it out.
const names = (message.files ?? []).map((file) => file.name ?? 'a file');
const attached = names.length > 0 ? ` [${names.join(', ')}]` : '';
return <li>{message.fromMe ? 'You' : message.from}: {message.text ?? ''}{attached}</li>;
}import { connectToHost } from '@unaiverse/gui-kit';
// A fake world that finds the file the person sent in `message.files` and answers with its name and type.
const desk = {
name: 'Desk',
onMessage: (message) => {
const file = message.files?.[0];
return file ? `Got ${file.name} (${file.type})` : 'Send me a file.';
},
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: desk } });
const notes = document.createElement('textarea');
notes.placeholder = 'Notes';
const sendButton = document.createElement('button');
sendButton.textContent = 'Send as a file';
const bigButton = document.createElement('button');
bigButton.textContent = 'Send a 21 MB file';
const result = document.createElement('p');
result.textContent = 'Nothing sent yet.';
const list = document.createElement('ul');
document.body.append(notes, sendButton, bigButton, result, list);
// Sends a file with words and shows how it ended.
async function sendFile(file, text) {
try {
const outcome = await world.send({ file, text });
result.textContent = `Result: ${outcome}`;
} catch (error) {
// 'too-big' means that the file is over 20 MB and nothing was sent.
result.textContent = `Error: ${error.code}`;
}
}
// The page makes this file. A File from a file field or a drop is sent the same way.
sendButton.onclick = () => sendFile(new File([notes.value], 'notes.txt', { type: 'text/plain' }), 'My notes');
bigButton.onclick = () => sendFile(new Blob([new Uint8Array(21 * 1024 * 1024)]), 'A big file');
// The messages, with the names of their files.
world.subscribe((node) => {
list.replaceChildren(...node.messages.map((message) => {
// Read `files` with a fallback, because an older webapp leaves it out.
const names = (message.files ?? []).map((file) => file.name ?? 'a file');
const item = document.createElement('li');
item.textContent = `${message.fromMe ? 'You' : message.from}: ${message.text ?? ''}`;
if (names.length > 0) item.textContent += ` [${names.join(', ')}]`;
return item;
}));
});The message of the person is in messages immediately and holds the file in files as { name, type, url }.
Send a file the person picks
Pass the File from a file input unchanged:
const picker = document.createElement('input');
picker.type = 'file';
picker.accept = '.pdf'; // only what the world takes, if you know it
picker.onchange = async () => {
const file = picker.files[0];
if (!file) return;
try {
await world.send({ file, text: file.name });
} catch (error) {
showError(error.code === 'too-big' ? 'Pick a file under 20 MB.' : error.code);
}
picker.value = ''; // so that the same file can be picked again
};For a dropped file pass event.dataTransfer.files[0] in the same way.
Ask a question with a form
The receiver gets a message with a form and replies with answer:
await world.send({
text: 'Where shall we meet?',
form: { fields: [{ name: 'place', type: 'select', options: ['Square', 'Station'] }] },
});Caveats
- One message at a time.
canSendisfalsewhile a message is pending. If you callsendagain before the first call resolves, the second call resolves'not-allowed'with a world and waits with an agent. Await each call or disable the control until it resolves. - The
Promisewaits for delivery. If delivery is not confirmed within 20 seconds, it resolves'failed'. - Agents are waited for and worlds are not. Right after the view starts an agent may still be
'connecting'. In that casesendwaits up to 20 seconds for it and resolves'not-allowed'if the agent is still not ready. With a world that does not accept a messagesendresolves'not-allowed'immediately. - The message belongs to the person. It also appears in the UNaIVERSE view of the world as an ordinary message of the person with no mark of your view. Send only what the person asked for.
- Large images are slow. Downscale them on a canvas before sending.
- An invalid form is sent as text. A
formthat does not satisfyFormSpecarrives as plain text with no form.
Files
'sent'does not mean that the file is read. Only agents with a file input ('file'or'all') read it. The others ignore it without an error and leave the person with no reply. A world accepts files only when its owner gives one of its agents such an input. Offer a file button only in those worlds.- One attachment per message. An image together with a file resolves
'failed'and nothing is sent. Send two messages. - An image sent as
fileis a file. Only the agents that take files receive it (with its name) and the agents that take images never see it. Send it asimageto show it to the world. - The size is checked first. For a file over 20 MB
sendrejects with'too-big'before reading anything and leavesmessagesunchanged. Below the limit a large file is still slow to read and transfer on a computer and slower still on a phone. - The file is kept only while the view is open. After a reload of the webapp the message keeps the
nameandtypeof the file while itsurlbecomesnull. retry()sends the same file again.- A
FileToSendneeds a base64 data URI (data:...;base64,...). Any otherurlresolves'failed'.
Troubleshooting
| Code | Cause | Fix |
|---|---|---|
'too-big' | The file is over 20 MB. Nothing was sent. | Ask for a smaller file. Check file.size > 20 * 1024 * 1024 before sending. |
'not-allowed-verb' | The webapp predates file sending. Neither the file nor the text was sent. | Hide the file button. Text and images still work. |
'failed' | The webapp could not run the call (rare). | Show an error and let the person retry. |
As results 'failed' and 'not-allowed' are not errors. The Promise resolves with them. send also resolves 'failed' without an error for an image sent together with a file.
try {
const result = await world.send(text);
if (result === 'failed') showRetry();
if (result === 'not-allowed') showNotYourTurn();
} catch (error) {
if (error.code === 'too-big') showError('The file is over 20 MB.');
else showError(error.code);
}See also
message.retry(): sends a failed message again.message.answer(values): answers a question.GuiFile: a file in a message.- Messages and questions and the recipe Show whether a message was delivered.