Skip to content

Open the person's camera ​

The view opens the camera of the person when they press a button and offers a sample picture when there is no camera or when the person refuses it.

Two yeses ​

Inside the webapp the view gets the camera after two yeses:

  1. The yes of the webapp covers this view only and is asked before the one of the browser (Features that need the person's yes explains why). agent.webapp.allowed lists the features the person has allowed the view and agent.askFor(['camera']) asks for more.
  2. The yes of the browser is the usual permission prompt of navigator.mediaDevices.getUserMedia({ video: true }).
js
if (!agent.webapp.allowed.includes('camera')) await agent.askFor(['camera']);
stream = await navigator.mediaDevices.getUserMedia({ video: true });
video.srcObject = stream;
  • After a yes the webapp reloads the view with the camera allowed. The person presses Open my camera again and this time webapp.allowed includes 'camera'.
  • After a no askFor rejects with the code 'declined' and the view offers the sample picture instead of asking again (After a no).
  • Because a fake agent lists every feature in webapp.allowed, the view skips askFor and only the browser asks.

Ask on the click of the button and never when the view opens. A person who has just pressed Open my camera knows why the browser asks.

When there is no camera ​

On a computer without a camera, after the person says no or in a browser that cannot open the camera, askFor or getUserMedia rejects. The catch explains what happened and offers the sample picture of a blue tit:

js
} catch (error) {
  const reason = error.code === 'declined' ? 'You did not allow the camera.' : 'Your camera could not open.';
  note.textContent = `${reason} You can use a sample picture instead.`;
}

The Use a sample picture button stays on the page in every case and lets a person without a camera continue.

The video ​

The camera renders in a <video> with three attributes:

  • autoplay: playback starts as soon as the stream is attached.
  • playsinline: a phone plays the video inside the page instead of in full screen.
  • muted: autoplay policies always let a muted video start without a gesture of the person.

In React the <video> stays mounted and hidden until the camera opens. Its ref is then ready when getUserMedia resolves.

Close the camera ​

The camera and its light stay on until every track of the stream is stopped:

js
stream.getTracks().forEach((track) => track.stop());

The view stops the stream when the person picks the sample picture. In React it also stops it in the cleanup of an effect when the component unmounts.

The code ​

The new section ("Show Feeder a bird") sits between the camera of the agent and the conversation.

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

// The camera of the fake agent draws a robin at a bird feeder as an SVG picture.
// Every picture is a little different, because `time` moves the bird.
function frameAt(time) {
	const x = 170 + 70 * Math.sin(time / 800);
	const y = 120 - Math.abs(25 * Math.sin(time / 300));
	const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="320" height="180">
<rect width="320" height="180" fill="#bfe3ff"/><rect y="140" width="320" height="40" fill="#7cc576"/>
<rect x="40" y="70" width="10" height="70" fill="#8b5a2b"/><rect x="18" y="66" width="54" height="8" fill="#8b5a2b"/><polygon points="12,50 78,50 45,30" fill="#a0522d"/>
<circle cx="${x}" cy="${y}" r="14" fill="#d35400"/><circle cx="${x + 12}" cy="${y - 12}" r="8" fill="#6e4b2a"/>
<polygon points="${x + 19},${y - 13} ${x + 28},${y - 10} ${x + 19},${y - 8}" fill="#f1c40f"/>
<text x="310" y="20" font-size="13" font-family="monospace" text-anchor="end">${new Date(time).toLocaleTimeString('en-GB')}</text>
</svg>`;
	return `data:image/svg+xml,${encodeURIComponent(svg)}`;
}

// A fake agent to build with. Its camera sends a new picture every 100 ms,
// and the agent answers every message.
const feeder = {
	name: 'Feeder',
	profile: { description: 'A camera at a bird feeder, in a garden.' },
	data: { camera: { every: 100, value: frameAt } },
	onMessage: () => 'A robin is at the feeder right now. It comes every morning.',
};

// A sample picture of a blue tit, drawn as an SVG picture, for a person with no camera.
const SAMPLE_PICTURE = `data:image/svg+xml,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" width="320" height="240">
<rect width="320" height="240" fill="#e3f1d9"/><rect x="0" y="180" width="320" height="10" fill="#8b5a2b"/>
<polygon points="110,140 50,150 110,165" fill="#3d7ab8"/><ellipse cx="160" cy="145" rx="60" ry="38" fill="#f2cf3a"/>
<circle cx="205" cy="105" r="30" fill="#3d7ab8"/><circle cx="212" cy="112" r="16" fill="#ffffff"/>
<circle cx="216" cy="106" r="4" fill="#1b1b1b"/><polygon points="233,108 248,112 233,116" fill="#444444"/>
</svg>`)}`;

// The camera of the agent, apart from the rest, with its picture, a caption and a button to pause it.
function AgentCamera({ agent }) {
	const picture = useRef(null);
	const [isPaused, setIsPaused] = useState(false);
	const [framesPerSecond, setFramesPerSecond] = useState(null);

	useEffect(() => {
		if (isPaused) return undefined;
		let frames = 0;
		// onData calls this with every new picture of `camera`, and for nothing else.
		// The picture goes straight into the <img>, with no state and no new render.
		const stop = agent.onData('camera', (frame) => {
			picture.current.src = frame;
			frames += 1;
		});
		// Once a second, show how many pictures arrived.
		const timer = setInterval(() => {
			setFramesPerSecond(frames);
			frames = 0;
		}, 1000);
		// A pause stops both, and the picture stays on the last frame.
		return () => {
			stop();
			clearInterval(timer);
		};
		// Start again only after a pause, because `onData` works from any copy of `agent`.
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [isPaused]);

	let caption = `Live: ${framesPerSecond} frames a second`;
	if (isPaused) caption = 'Paused';
	else if (framesPerSecond === null) caption = `Waiting for ${agent.name}'s camera…`;
	return (
		<>
			<img ref={picture} alt={`${agent.name}'s camera`} width="320" height="180" />
			<p>{caption}</p>
			<button onClick={() => setIsPaused(!isPaused)}>{isPaused ? 'Play' : 'Pause'}</button>
		</>
	);
}

// The conversation with the agent, oldest first.
function MessageList({ agent }) {
	if (agent.messages.length === 0) return <div>No messages yet. Ask {agent.name} about the birds.</div>;
	return (
		<div>
			{agent.messages.map((message) => (
				<p key={message.id}>
					<b>{message.fromMe ? 'You' : message.from}:</b> {message.text}
				</p>
			))}
		</div>
	);
}

// The box to write to the agent.
function MessageBox({ agent }) {
	const [text, setText] = useState('');

	function handleSubmit(event) {
		event.preventDefault();
		// send() writes as the person, and the message is in `messages` at once.
		agent.send(text);
		setText('');
	}

	return (
		<form onSubmit={handleSubmit}>
			<input value={text} onChange={(event) => setText(event.target.value)} placeholder={`Ask ${agent.name}`} />
			{/* canSend is false while the agent cannot take a message (still connecting, or busy). */}
			<button disabled={!agent.canSend || !text.trim()}>Send</button>
		</form>
	);
}

// The person's camera, to show the agent a bird, or a sample picture.
function MyCamera({ agent }) {
	const video = useRef(null);
	const stream = useRef(null); // the person's camera, while it is open
	const [source, setSource] = useState(null); // 'camera', 'sample' or null before a choice
	const [note, setNote] = useState('');

	function closeCamera() {
		stream.current?.getTracks().forEach((track) => track.stop());
		stream.current = null;
	}

	// Close the camera when this part of the page goes away.
	useEffect(() => closeCamera, []);

	async function openCamera() {
		setNote('');
		try {
			// In the webapp, the person allows the camera for your view first.
			if (!agent.webapp.allowed.includes('camera')) await agent.askFor(['camera']);
			// Then the browser opens it (and asks the person, the first time).
			stream.current = await navigator.mediaDevices.getUserMedia({ video: true });
			video.current.srcObject = stream.current;
			setSource('camera');
		} catch (error) {
			// No camera here, or the person said no. After a no, `askFor` fails with the code 'declined'.
			const reason = error.code === 'declined' ? 'You did not allow the camera.' : 'Your camera could not open.';
			setNote(`${reason} You can use a sample picture instead.`);
		}
	}

	function showSample() {
		closeCamera();
		setSource('sample');
		setNote('A sample picture of a blue tit.');
	}

	return (
		<>
			<h2>Show {agent.name} a bird</h2>
			{/* Always on the page, to be there when the camera opens, and hidden until then. */}
			<video ref={video} autoPlay playsInline muted width="320" height="240" hidden={source !== 'camera'} />
			{source === 'sample' && <img src={SAMPLE_PICTURE} alt="A sample picture of a blue tit" width="320" height="240" />}
			{note && <p>{note}</p>}
			<button onClick={openCamera}>Open my camera</button>
			<button onClick={showSample}>Use a sample picture</button>
		</>
	);
}

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

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!agent) return <p>Connecting…</p>;
	return (
		<>
			<h1>{agent.name}</h1>
			<p>{agent.profile.description}</p>
			<AgentCamera agent={agent} />
			<MyCamera agent={agent} />
			<MessageList agent={agent} />
			<MessageBox agent={agent} />
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The camera of the fake agent draws a robin at a bird feeder as an SVG picture.
// Every picture is a little different, because `time` moves the bird.
function frameAt(time) {
	const x = 170 + 70 * Math.sin(time / 800);
	const y = 120 - Math.abs(25 * Math.sin(time / 300));
	const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="320" height="180">
<rect width="320" height="180" fill="#bfe3ff"/><rect y="140" width="320" height="40" fill="#7cc576"/>
<rect x="40" y="70" width="10" height="70" fill="#8b5a2b"/><rect x="18" y="66" width="54" height="8" fill="#8b5a2b"/><polygon points="12,50 78,50 45,30" fill="#a0522d"/>
<circle cx="${x}" cy="${y}" r="14" fill="#d35400"/><circle cx="${x + 12}" cy="${y - 12}" r="8" fill="#6e4b2a"/>
<polygon points="${x + 19},${y - 13} ${x + 28},${y - 10} ${x + 19},${y - 8}" fill="#f1c40f"/>
<text x="310" y="20" font-size="13" font-family="monospace" text-anchor="end">${new Date(time).toLocaleTimeString('en-GB')}</text>
</svg>`;
	return `data:image/svg+xml,${encodeURIComponent(svg)}`;
}

// A fake agent to build with. Its camera sends a new picture every 100 ms,
// and the agent answers every message.
const feeder = {
	name: 'Feeder',
	profile: { description: 'A camera at a bird feeder, in a garden.' },
	data: { camera: { every: 100, value: frameAt } },
	onMessage: () => 'A robin is at the feeder right now. It comes every morning.',
};

// A sample picture of a blue tit, drawn as an SVG picture, for a person with no camera.
const SAMPLE_PICTURE = `data:image/svg+xml,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" width="320" height="240">
<rect width="320" height="240" fill="#e3f1d9"/><rect x="0" y="180" width="320" height="10" fill="#8b5a2b"/>
<polygon points="110,140 50,150 110,165" fill="#3d7ab8"/><ellipse cx="160" cy="145" rx="60" ry="38" fill="#f2cf3a"/>
<circle cx="205" cy="105" r="30" fill="#3d7ab8"/><circle cx="212" cy="112" r="16" fill="#ffffff"/>
<circle cx="216" cy="106" r="4" fill="#1b1b1b"/><polygon points="233,108 248,112 233,116" fill="#444444"/>
</svg>`)}`;

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

// ── The agent ──
const title = document.createElement('h1');
const description = document.createElement('p');
document.body.append(title, description);

// Everything but the camera. This listener runs at every change, a new picture included, and must stay light.
agent.subscribe((node) => {
	title.textContent = node.name;
	description.textContent = node.profile.description ?? '';
});

// ── The camera, with its picture, a caption and a button to pause it ──
const picture = document.createElement('img');
picture.alt = `${agent.name}'s camera`;
picture.width = 320;
picture.height = 180;
const caption = document.createElement('p');
const pauseButton = document.createElement('button');
document.body.append(picture, caption, pauseButton);

let frames = 0; // pictures since the last count
let framesPerSecond = null; // the last count, or null before the first one
let stopCamera = null; // stops following the camera, or null while paused

function drawCaption() {
	if (!stopCamera) caption.textContent = 'Paused';
	else if (framesPerSecond === null) caption.textContent = `Waiting for ${agent.name}'s camera…`;
	else caption.textContent = `Live: ${framesPerSecond} frames a second`;
	pauseButton.textContent = stopCamera ? 'Pause' : 'Play';
}

function play() {
	// onData calls this with every new picture of `camera`, and for nothing else.
	stopCamera = agent.onData('camera', (frame) => {
		picture.src = frame;
		frames += 1;
	});
	drawCaption();
}

function pause() {
	stopCamera(); // the picture stays on the last frame
	stopCamera = null;
	drawCaption();
}

pauseButton.onclick = () => (stopCamera ? pause() : play());
play();

// Once a second, show how many pictures arrived.
setInterval(() => {
	if (stopCamera) framesPerSecond = frames;
	frames = 0;
	drawCaption();
}, 1000);

// ── Your camera, to show the agent a bird ──
const heading = document.createElement('h2');
heading.textContent = `Show ${agent.name} a bird`;
const video = document.createElement('video');
video.autoplay = true;
video.playsInline = true;
video.muted = true;
video.width = 320;
video.height = 240;
video.hidden = true;
const sample = document.createElement('img');
sample.src = SAMPLE_PICTURE;
sample.alt = 'A sample picture of a blue tit';
sample.width = 320;
sample.height = 240;
sample.hidden = true;
const note = document.createElement('p');
const openButton = document.createElement('button');
openButton.textContent = 'Open my camera';
const sampleButton = document.createElement('button');
sampleButton.textContent = 'Use a sample picture';
document.body.append(heading, video, sample, note, openButton, sampleButton);

let stream = null; // the person's camera, while it is open

function closeCamera() {
	stream?.getTracks().forEach((track) => track.stop());
	stream = null;
}

openButton.onclick = async () => {
	note.textContent = '';
	try {
		// In the webapp, the person allows the camera for your view first.
		if (!agent.webapp.allowed.includes('camera')) await agent.askFor(['camera']);
		// Then the browser opens it (and asks the person, the first time).
		stream = await navigator.mediaDevices.getUserMedia({ video: true });
		video.srcObject = stream;
		video.hidden = false;
		sample.hidden = true;
	} catch (error) {
		// No camera here, or the person said no. After a no, `askFor` fails with the code 'declined'.
		const reason = error.code === 'declined' ? 'You did not allow the camera.' : 'Your camera could not open.';
		note.textContent = `${reason} You can use a sample picture instead.`;
	}
};

sampleButton.onclick = () => {
	closeCamera();
	video.hidden = true;
	sample.hidden = false;
	note.textContent = 'A sample picture of a blue tit.';
};

// ── The conversation, with its messages and a box to write in ──
const list = document.createElement('div');
const form = document.createElement('form');
const input = document.createElement('input');
input.placeholder = `Ask ${agent.name}`;
const sendButton = document.createElement('button');
sendButton.textContent = 'Send';
form.append(input, sendButton);
document.body.append(list, form);

let canSend = false;
function drawSendButton() {
	// canSend is false while the agent cannot take a message (still connecting, or busy).
	sendButton.disabled = !canSend || !input.value.trim();
}
input.oninput = drawSendButton;

form.onsubmit = (event) => {
	event.preventDefault();
	// send() writes as the person, and the message is in `messages` at once.
	agent.send(input.value);
	input.value = '';
	drawSendButton();
};

let shownMessages = null; // the ids of the messages on the page
agent.subscribe((node) => {
	canSend = node.canSend;
	drawSendButton();
	// This runs for every picture too, and it draws the messages again only when they changed.
	const ids = node.messages.map((message) => message.id).join(' ');
	if (ids === shownMessages) return;
	shownMessages = ids;
	if (node.messages.length === 0) {
		list.textContent = `No messages yet. Ask ${node.name} about the birds.`;
		return;
	}
	list.replaceChildren(...node.messages.map((message) => {
		const line = document.createElement('p');
		const sender = document.createElement('b');
		sender.textContent = `${message.fromMe ? 'You' : message.from}:`;
		line.append(sender, ` ${message.text ?? ''}`);
		return line;
	}));
});
Live, on a fake world
Open

Open my camera makes your browser ask for the camera. If you refuse or have no camera, the view tells you what went wrong.

Next steps ​

Once the camera is open, step 5: Take a photo and send it lets the person take a photo with it and send the photo to Feeder.

The camera and the rest of the browser and askFor cover the other features that need a yes. The recipe Ask for the camera only when needed shows the two yeses in a short example.

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