docs / ctx.live
api reference

ctx.live

Rooms where several people edit the same thing at the same time — Figma-style. One shared table, pushed to everyone the moment it changes.

pubpushed, not polleddirect lines

Calls

ctx.live
const room = await ctx.live.join('a name only your people know');
room.get(key);  room.all();                 // the shared table, as it is right now
await room.set(key, value);                 // for everyone in the room — any JSON value but null, up to 8 KB
await room.del(key);
room.cursor({ x, y });                      // where you are — not saved, sent at most every 40 ms
room.peers();                               // who's here — initial and color, never a name
room.me;  room.open;  room.seq;             // you in this room · connected right now · the change counter
const off = room.on('change', (c) => …);    // also 'peer' · 'open' · 'close' · 'error' · 'direct'
const line = await room.direct(sid);        // a direct line to one person — below
await room.leave();

A room is one table of key → value, kept on Fave1. Anyone who joins a room with the same name gets the same table and every change to it as it happens — yours included, so you draw once and let the change event do the rest. When everybody leaves, the table stays; join again a day later and it is still there (a room empties itself 45 days after the last write — joining and cursors don’t count).

It uses the pub permission — nothing new to declare. Like posting, it needs a signed-in person who added your app and hasn’t switched pub off (ctx.can('pub')), and on someone else’s site the first join asks once: Join the room on <your app>? — the same yes that covers ctx.pub, so an app that already posts from that site is already in. In app mode it never asks. If your app calls a room something else, pass the word: ctx.live.join(name, { what: 'project' }) makes the line Join the project on <your app>? (up to 20 letters, spaces or dashes — anything else says room).

Naming a room

Same app, same name, same room. The name is hashed on the way out — Fave1 never sees what you called it — and it is yours per app: another app using the word lobby gets a different room. Up to 200 characters. Put into the name exactly what should separate one group from another:

Room forNameWho meets
this pagepage:<hostname><pathname> — everyone with your app on the same pagestrangers
an invitepage:…#K7QX2M — the page plus a code one person made and sent to the othersfriends
a shared thingdoc:<id> — the id of a ctx.shared value; the link opens the thing, the room is where people meet on itpeople with the link
one personme: + ctx.user.id — their own tabs and devices, nobody elsethemselves

A room anyone can guess is a room anyone can join and write to — a page-wide room is fine for cursors and reactions, not for a document. For editing, carry a code in the URL hash the way Fave1’s Collab does, and let people share the link. Don’t put the whole page URL with its query string in a name: two people on the same product page with different tracking tails should meet.

Editing a page together

src/index.ts
// Everyone who opens this page with your app and the same code is in one room.
if (!ctx.page.document) return;
const code = location.hash.match(/room=([A-Z0-9]{6})/)?.[1] ?? 'LOBBY';
const room = await ctx.live.join(`page:${location.hostname}${location.pathname}#${code}`);

// Draw the table — now, and every time it changes (your own writes come through here too).
const draw = (key: string, value: unknown) => { /* find the element for key, show value */ };
for (const [k, v] of Object.entries(room.all())) draw(k, v);
room.on('change', (c) => draw(c.key, c.value));

// Someone edits the heading: write it once, for everyone.
const h1 = ctx.page.query('h1');
if (h1) await room.set('h1', { text: h1.textContent });

// Show the others where you are — a pill with their initial, in their color.
const layer = ctx.page.layer();
const pills = new Map<string, HTMLElement>();
ctx.page.on('pointermove', (e) => room.cursor({ x: e.clientX, y: e.clientY }));
// A drop forgets everyone without leave events — clear the pills; the reconnect brings them back.
room.on('close', () => { for (const p of pills.values()) p.remove(); pills.clear(); });
room.on('peer', (ev) => {
  if (ev.type === 'leave') { pills.get(ev.peer.sid)?.remove(); pills.delete(ev.peer.sid); return; }
  const at = ev.peer.data as { x: number; y: number } | null;
  if (!at) return;
  let pill = pills.get(ev.peer.sid);
  if (!pill) {
    pill = document.createElement('div');
    pill.textContent = ev.peer.initial;
    pill.style.cssText = `position:fixed;left:0;top:0;padding:2px 8px;border-radius:10px;color:#fff;background:${ev.peer.color}`;
    layer.append(pill);
    pills.set(ev.peer.sid, pill);
  }
  pill.style.transform = `translate(${at.x}px, ${at.y}px)`;
});

What a change looks like

a change
{
  key: 'h1',
  value: { text: 'Packing list' },   // undefined when the key was deleted
  by: { sid: 'k3f9q2', id: 'f3a91c0d2b7e44a1c9d0e2b7' },   // who — null for what the room handed you on join or after a reconnect
  me: false,                         // true for your own set() · del(), which come through here first
  seq: 418,                          // the room's change counter after this one — also room.seq
}

One handler draws everything: the table you get on join() is in room.all() (no events for it), and from then on every write — theirs and yours — is one change. Your own set() fires it at once with me: true, before Fave1 confirms; if the room then refuses the write, Fave1 puts the room’s value back at once with a change (me: false, by: null) and an error event names the key. After a reconnect the differences arrive as changes with by: null, then open — so a handler that only reacts to change stays correct through a drop.

seq only ever grows. Keep the last one you drew if you need to know whether anything moved since — comparing values is slower and tells you less.

How the room settles things

One key, one owner at a time. Keep keys small — one element, one property. If two people set the same key in the same instant, the one Fave1 receives last wins and both see that value; there is no merging inside a value. For text, that means per-element replacement, not per-letter editing — fine for a caption, a price, a title; not a shared essay.

Your writes show at once. set() applies locally and fires change with me: true before the server answers. If the room refuses it (too large, over quota), Fave1 puts the room’s value back at once with a change (me: false, by: null), then an error event names the key.

Drops are handled. If the connection goes, Fave1 reconnects for you — after 1 s, then 2, 4, up to 30 — and fires open (join() itself resolves once the room is open, so open only ever means a reconnect) after change events for whatever moved meanwhile. Writes made while closed show locally but are never sent — the room’s table replaces them on reconnect. Check room.open before writing, and grey out the editor on close with reason lost.

Presence — cursor()

cursor(data) is for what is true right now and worthless in a minute: where the pointer is, what they selected, “typing…”, which tab they are on. It is never written to the table — nobody who joins later sees it — and it goes out at most every 40 ms, last value wins, up to 1 KB as JSON. The others get it as a peer event with type: 'cursor', and the latest value sits on peer.data (so room.peers() is enough to draw everyone at once).

src/index.ts
// Send what you're on; draw what they're on.
const room = await ctx.live.join('doc:k3f9q2m8x1pz');
room.cursor({ on: 'title', typing: false });

const marked = new Set<string>();
room.on('peer', (ev) => {
  const at = ev.peer.data as { on: string; typing: boolean } | null;
  if (ev.type === 'leave' || !at) { unmark(ev.peer.sid); marked.delete(ev.peer.sid); return; }
  mark(ev.peer.sid, at.on, ev.peer.initial, ev.peer.color, at.typing);   // a colored outline on that field
  marked.add(ev.peer.sid);
});
for (const p of room.peers()) {
  const at = p.data as { on: string; typing: boolean } | null;
  if (at) { mark(p.sid, at.on, p.initial, p.color, at.typing); marked.add(p.sid); }
}
// A drop forgets everyone without leave events — the reconnect brings them back with new sids.
room.on('close', () => { marked.forEach(unmark); marked.clear(); });

A person with two tabs open is two peers — key everything you draw by sid, and use id only to say “that’s you” or to match a ctx.pub row.

A direct line — room.direct(sid)

Everything above goes through the room — a server — and comes back in tens of milliseconds, or a few hundred from far away. Fine for a title, a cursor, a turn. Not for a fighting game, where the other player’s input has to arrive within a frame or two. For that, two people in a room open a direct line: their browser to yours, with nothing of Fave1’s in between.

room.direct
room.on('direct', (line) => …);                      // take lines others open to you
const line = await room.direct(sid, { lossy: true });   // open one to a person in the room
line.send({ f: 1204, keys: 5 });                        // JSON up to 1 KB
line.on('message', (data) => …);
line.via;  line.rtt;                                    // 'direct' · 'relay' · 'room' — round trip in ms

It always opens — browser to browser, through a relay, or through the room when neither works — and your code is the same on all three. Both apps have to want it: the other side listens with room.on('direct'), or direct() rejects with declined. The room stays where you meet, keep score and say who won. Everything else — opening, lossy or reliable, a lockstep game loop, reconnecting, testing — is in the guide: room.direct.

Who people are in a room

a peer
{
  sid: 'k3f9q2',         // this tab — two tabs are two peers
  id: 'f3a91c0d2b7e44a1c9d0e2b7', // opaque, per app — equals their ctx.user.id and their ctx.pub row id
  initial: 'M',          // one letter for an avatar
  color: 'linear-gradient(…)',
  avatar: 'data:image/svg+xml,…', // the avatar they picked — <img src>
  avatarStill: 'data:image/svg+xml,…', // the same, standing still — for small circles
  data: { x: 420, y: 130 }, // whatever they last sent with cursor()
}

No names. A room is read on other people’s sites, so what travels is what the launcher already shows there — a letter, a color and the avatar they picked. Draw from those; don’t ask people for a name inside your app and store it in the table. room.me has the same shape for the person at this keyboard — id and sid fill in once the room is open.

Leaving

leave() closes the connection and fires close with reason left; the table stays on Fave1 for the next person. Closing your app leaves every room it opened — you don’t have to track them in onDestroy. Handlers you registered stop firing after any close except lost, which is followed by a reconnect.

reasonWhat happenedThen
lostThe connection dropped. Fave1 is reconnectingwait for open
replacedThis person opened the room in a fifth tab or device (4 at most), so the one that hasn’t spoken longest — this one — was let go. It doesn’t reconnect, or it would push the other tab out in turn. Say they’re in the room elsewhere, and offer a button that calls ctx.live.join() againjoin() on a tap
leftYou called leave()done
serverThe room closed it — nobody wrote to it for 45 daysjoin() again
goneYour app closed, or the page took Fave1’s frame awaynothing

Limits

8 KB

Per value

Measured as JSON text. Keys up to 160 characters, no control characters.

256 KB

Per room

Up to 2,000 keys. Over either, the write comes back as an error event with quota — delete something or open another room.

40 / s

Writes

Per connection — each tab counts on its own. Over that, writes come back as rate. Cursors are throttled for you (every 40 ms, 1 KB).

48

People

Per room, and 4 connections per person (tabs and devices) — a fifth lets the quietest go with close reason replaced. The 49th join fails with unreachable.

Errors

Two kinds. join(), set() and del() reject with a Fave1Error for what can be known before anything is sent. What the room refuses after the fact arrives as an error event — the write already showed locally, and Fave1 puts the room’s value back with a change just before it.

join() rejectsWhat happenedTry
deniedpub isn’t in your manifest, or they switched it offctx.perms.open()
signed-outNobody’s signed in to Fave1 herefold the feature
not-installedThey haven’t added your app — a sideloaded run or Try it from the storesay so
cancelledThey chose Not now on the first-join promptleave it
invalidA name that isn’t a string, is empty, or is over 200 charactersfix it
unreachableThis page blocks Fave1’s frame, or the room is fullsay so
timeoutNo answer in 15 seconds — nothing is left openjoin() again
serverFave1 had a problem on its side — nothing is left openjoin() again
set() · del() rejectWhat happenedTry
too-largeA value over 8 KB — checked before it leaves the pagetrim it
invalidNot JSON, a value of undefined (use del), or a key that’s empty, over 160 characters, or has control charactersfix it
error eventWhat the room refused — ev.key says which writeTry
quotaThe room is at 2,000 keys or 256 KBdel() something
rateMore than 40 writes in a second on this connectionbatch, then retry
too-largeA cursor over 1 KB, or a value the room measured larger than you didtrim it
invalidSomething the room couldn’t readfix it

While you build

DEV builds get a sandbox room. From fave1 dev or a review link, a room lives in this browser — open the same site in two tabs and they share it, which is enough to see two cursors move and two tables agree. There is no server in the loop, so nothing drops and nothing is rate-limited, so you never see open or lost there. With Data on My account it is a real room on your team’s DEV slot — the way it will run live, and never the live room.