Skip to content

The actions the rules offer ​

At each moment the rules of a world state what is happening, what can come next and which actions the person may choose (for example voting, bidding, passing or starting a new round). world.now holds these three things and world.act(name) asks the rules for one of the actions. A view reads now to show the current moment and to offer the available actions as buttons (with arguments when an action needs them) and calls act when the person presses one of them. A third field, world.canSend, is true when the person may send a message.

What is happening now ​

world.now has three fields: (1) text with the description of the current moment ("Place your bets"), (2) next with the names of what can come next and (3) actions with the actions the person may choose (below).

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

// A fake world: what its rules say now, and what can come next.
const roulette = {
	name: 'Roulette',
	now: { text: 'Place your bets', next: ['spinning', 'paying'] },
};

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

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	// `now` is null when the rules say nothing (an ended world, an agent without rules).
	if (!world.now) return <h2>Nothing is happening.</h2>;
	return (
		<>
			<h2>Now: {world.now.text ?? '…'}</h2>
			<p>What can come next: {world.now.next.join(', ') || 'nothing'}</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world: what its rules say now, and what can come next.
const roulette = {
	name: 'Roulette',
	now: { text: 'Place your bets', next: ['spinning', 'paying'] },
};

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

const text = document.createElement('h2');
const next = document.createElement('p');
document.body.append(text, next);

// Called at once, then after every change of the world.
world.subscribe((node) => {
	// `now` is null when the rules say nothing (an ended world, an agent without rules).
	if (!node.now) {
		text.textContent = 'Nothing is happening.';
		next.textContent = '';
		return;
	}
	text.textContent = `Now: ${node.now.text ?? '…'}`;
	next.textContent = `What can come next: ${node.now.next.join(', ') || 'nothing'}`;
});
Live, on a fake world
Open
  • now can be null when the rules say nothing (an agent with no rules or a world that ended). Test it before reading its fields.
  • now.text is null when the rules have no description for the current moment.
  • now.next holds the internal names of the rules ('spinning', 'paying') and includes the destination of every action. These names suit a progress bar or the choice of a picture. The text to show the person, on the other hand, is in now.text and in the text of each action.

When the rules move on, now changes and your subscribe listener runs again as it does on any other change.

The actions the person may choose ​

world.now.actions lists the actions that the person may ask for now. Each action has these fields:

FieldWhat it is
nameThe name you give to act.
textThe label of its button. Show name when it is null.
toThe name of what comes after it (one of now.next).
argsIts arguments as the rules give them.
canChoosetrue when the person may ask for it, false when it happens on its own and null when the world does not say.
isRequestedtrue when somebody has already asked for it.

Draw one button for each action. When the rules move on, the actions change and the buttons follow them.

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

// A fake council: two actions to choose, and the votes in `data`.
let yes = 0;
let no = 0;
const council = {
	name: 'Council',
	now: {
		text: 'Vote on the new park',
		actions: [
			{ name: 'vote-yes', text: 'Vote yes', to: 'counting' },
			{ name: 'vote-no', text: 'Vote no', to: 'counting' },
		],
	},
	data: { yes: { every: 200, value: () => yes }, no: { every: 200, value: () => no } },
	// Called when the person chooses one of `now.actions`. Its answer arrives as a message.
	onAction: (name) => {
		if (name === 'vote-yes') yes += 1;
		if (name === 'vote-no') no += 1;
		return 'Your vote is counted.';
	},
};

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: council } });
	// What the rules said to the person's last request, kept by the view and not by the world.
	const [request, setRequest] = useState('');

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

	// Asks the rules for an action, and shows what they said.
	async function choose(name) {
		const result = await world.act(name);
		setRequest(`Your request: ${result}`);
	}

	const news = world.messages.filter((message) => !message.fromMe).at(-1);
	return (
		<>
			<h2>{world.now?.text}</h2>
			{/* One button per action the rules offer the person now. */}
			<div>
				{(world.now?.actions ?? []).map((action) => (
					// canChoose false: the action happens on its own and the person cannot ask for it.
					<button key={action.name} disabled={action.canChoose === false} onClick={() => choose(action.name)}>
						{action.text ?? action.name}
					</button>
				))}
			</div>
			<p>{request}</p>
			<p>Yes: {world.data.yes} · No: {world.data.no}</p>
			<p>{news?.text ?? ''}</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake council: two actions to choose, and the votes in `data`.
let yes = 0;
let no = 0;
const council = {
	name: 'Council',
	now: {
		text: 'Vote on the new park',
		actions: [
			{ name: 'vote-yes', text: 'Vote yes', to: 'counting' },
			{ name: 'vote-no', text: 'Vote no', to: 'counting' },
		],
	},
	data: { yes: { every: 200, value: () => yes }, no: { every: 200, value: () => no } },
	// Called when the person chooses one of `now.actions`. Its answer arrives as a message.
	onAction: (name) => {
		if (name === 'vote-yes') yes += 1;
		if (name === 'vote-no') no += 1;
		return 'Your vote is counted.';
	},
};

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

const title = document.createElement('h2');
const buttons = document.createElement('div');
const request = document.createElement('p');
const votes = document.createElement('p');
const news = document.createElement('p');
document.body.append(title, buttons, request, votes, news);

// Asks the rules for an action, and shows what they said.
async function choose(name) {
	const result = await world.act(name);
	request.textContent = `Your request: ${result}`;
}

// The actions that the buttons show. The buttons are made again only when the actions change,
// because the votes change often and new buttons at every vote would lose the keyboard focus.
let shownActions = null;

// Called at once, then after every change of the world.
world.subscribe((node) => {
	title.textContent = node.now?.text ?? '';
	votes.textContent = `Yes: ${node.data.yes} · No: ${node.data.no}`;
	news.textContent = node.messages.filter((message) => !message.fromMe).at(-1)?.text ?? '';

	const actions = node.now?.actions ?? [];
	if (JSON.stringify(actions) === shownActions) return;
	shownActions = JSON.stringify(actions);
	// One button per action the rules offer the person now.
	buttons.replaceChildren(...actions.map((action) => {
		const button = document.createElement('button');
		button.textContent = action.text ?? action.name;
		// canChoose false: the action happens on its own and the person cannot ask for it.
		button.disabled = action.canChoose === false;
		button.onclick = () => choose(action.name);
		return button;
	}));
});
Live, on a fake world
Open
  • Draw the buttons from now.actions and never from a list of your own. A view that follows this rule never offers an action that the rules do not offer now.
  • canChoose: false marks an action that happens on its own when the rules decide. Show it as information or leave it out. An action whose canChoose is null (the world does not say) is offered like any other.
  • isRequested: true means that the person or someone else has already asked for the action and that it is waiting. Show that it is waiting ("Waiting for the vote to close") instead of offering it again (Show which action is waiting).
  • The world answers with a message (the line under the votes) and writes the new tally in data.
  • In plain JavaScript rebuild the buttons only when the actions change. Because the world changes often (in the example the votes change every 200 ms), buttons rebuilt on every change would lose the keyboard focus while the person is using them.

Asking for an action: act ​

world.act(name) asks the rules for one of now.actions. The rules decide whether and when the action happens and the call is therefore only a request. The Promise returned by act resolves with a value that tells whether the rules accepted the request. The action itself, once it happens, reaches the view through subscribe like every other change.

ResultMeansWhat to do
'requested'The rules accepted the request.Nothing. The world changes when the action happens and the view may show "Sent" until then.
'refused'The action is offered. The rules did not accept a request for it at this moment or did not answer within 10 seconds.Tell the person. now.text usually gives the reason.
'not-allowed'now.actions has no action with this name.Draw the buttons from now.actions to avoid it.

Inside the webapp, the webapp forwards act to the rules as it does with send. When the webapp cannot pass the request to the rules, the promise of act rejects with an error whose code is 'failed'.

js
async function choose(name) {
  try {
    const result = await world.act(name);
    if (result === 'refused') notice.textContent = 'Not now: the rules did not take it.';
  } catch (error) {
    notice.textContent = `Could not act (${error.code}).`;
  }
}

A 'requested' result does not mean that the action is done. The view shows it as done only after the world changes (Thinking in views).

Actions with arguments ​

Some actions need details such as the amount of a bid or the target of a move. Pass them in an object as the second argument of act (world.act('bid', { amount: 25 })). The world decides which arguments each action takes. The owner of the world tells you which ones and action.args lists them in the form the rules give.

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

// A fake auction: one action, `bid`, that takes an amount.
let best = 0;
const auction = {
	name: 'Auction',
	now: { text: 'A painting is for sale', actions: [{ name: 'bid', text: 'Bid' }] },
	data: { best: { every: 200, value: () => best } },
	// `args` holds what the view gave to `act`.
	onAction: (name, args) => {
		if (args.amount <= best) return `${args.amount} is not enough.`;
		best = args.amount;
		return `You bid ${args.amount}. You lead!`;
	},
};

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: auction } });
	// The amount the person is typing, kept by the view and not by the world.
	const [amount, setAmount] = useState('10');

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

	// The button works only while the rules offer the action.
	const bid = world.now?.actions.find((action) => action.name === 'bid');
	const news = world.messages.filter((message) => !message.fromMe).at(-1);
	return (
		<>
			<h2>{world.now?.text}</h2>
			<p>Best bid: {world.data.best}</p>
			<label>
				Amount <input type="number" value={amount} onChange={(event) => setAmount(event.target.value)} />
			</label>
			{/* The action with its arguments. The amount is a number, not the text of the field. */}
			<button disabled={!bid || bid.canChoose === false} onClick={() => world.act('bid', { amount: Number(amount) })}>
				{bid?.text ?? 'Bid'}
			</button>
			<p>{news?.text ?? ''}</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake auction: one action, `bid`, that takes an amount.
let best = 0;
const auction = {
	name: 'Auction',
	now: { text: 'A painting is for sale', actions: [{ name: 'bid', text: 'Bid' }] },
	data: { best: { every: 200, value: () => best } },
	// `args` holds what the view gave to `act`.
	onAction: (name, args) => {
		if (args.amount <= best) return `${args.amount} is not enough.`;
		best = args.amount;
		return `You bid ${args.amount}. You lead!`;
	},
};

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

const title = document.createElement('h2');
const bestLine = document.createElement('p');
const label = document.createElement('label');
const amount = document.createElement('input');
amount.type = 'number';
amount.value = '10';
label.append('Amount ', amount);
const button = document.createElement('button');
const news = document.createElement('p');
document.body.append(title, bestLine, label, button, news);

// The action with its arguments. The amount is a number, not the text of the field.
button.onclick = () => world.act('bid', { amount: Number(amount.value) });

// Called at once, then after every change of the world.
world.subscribe((node) => {
	title.textContent = node.now?.text ?? '';
	bestLine.textContent = `Best bid: ${node.data.best}`;
	// The button works only while the rules offer the action.
	const bid = node.now?.actions.find((action) => action.name === 'bid');
	button.textContent = bid?.text ?? 'Bid';
	button.disabled = !bid || bid.canChoose === false;
	news.textContent = node.messages.filter((message) => !message.fromMe).at(-1)?.text ?? '';
});
Live, on a fake world
Open

The value of an <input> is a string even with type="number". Convert it with Number(amount) to pass the world the number 25 instead of the string '25'.

canSend: may the person send now? ​

The rules of the world decide world.canSend. It is false when the person may not send a message now: (1) it is not their turn, (2) the world is offline or (3) one of their messages is still pending (for a moment after each send). A send called while it is false resolves with 'not-allowed'.

Bind the message box and every button that sends to canSend and show next to them a line that tells the person why they cannot send.

js
world.subscribe((node) => {
  sendButton.disabled = !node.canSend;
  hint.textContent = node.canSend ? '' : 'Wait for your turn.';
});

canSend concerns messages only. Actions follow now.actions instead and every action in that list can be asked for. The recipe Disable the message box when the person cannot send has a complete message box bound to canSend.

Actions in a fake world ​

A fake world lists its actions in its now and answers them with onAction.

js
const council = {
  name: 'Council',
  now: {
    text: 'Vote on the new park',
    actions: [{ name: 'vote-yes', text: 'Vote yes', to: 'counting' }],
  },
  // name: the action; args: what the view gave to act(); sender: who asked.
  onAction: (name, args, sender) => `${sender.name} asked for ${name}.`,
};
  • Like onMessage, onAction returns the answer of the world or nothing. The answer reaches the view as a message of the rules (with isSystem: true).
  • The now of a fake world is fixed for its whole life and its actions never change. Keep what changes (votes, whose turn it is) in data through a variable that onAction updates (the examples above do so).
  • Every fake action has canChoose: true and isRequested: false. act resolves 'requested' for an action in now.actions and 'not-allowed' for any other name. It never resolves 'refused'.

Testing with fake worlds covers fake worlds in full.

Things to watch ​

  • now can be null. Test it before reading now.text or now.actions.
  • Buttons come from now.actions with the label text ?? name.
  • A result is not an error. act resolves with 'refused' and 'not-allowed'. A call that the webapp could not make rejects instead with the error 'failed'. Handle both.
  • 'requested' is not done. Wait for the world to change.

Next steps ​

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