# Read / Watch Together — Plan

One client hosts a **room** on yokan-hub; others join and follow the host's position in real time.
Works for anime (playback), manga (page), and novels (scroll progress). Builds on what the hub already
has: accounts, permissions, the WebSocket stack, the in-process broadcast hub.

## 0. Shape of the feature

- A room is **ephemeral and in-memory** on the hub. No table, no history. Server restart ends every
  room; clients show "room closed" and can re-create. `ponytail:` add a `rooms` table only if
  persistent rooms or replay are ever asked for.
- Everyone in a room has an **account on the same hub**. The server is invite-gated already, so
  "guest without account" is not a case we need.
- The hub is the **authority for membership and the latest state**, and a **relay for everything
  else**. It never touches media: each client resolves the title/episode locally through its own
  installed source. A joiner without that source is told which extension to install.
- The host drives. Followers can be granted control (`co_host`), and can temporarily **detach**
  locally (browse pages on their own) and re-attach.
- Every room has a **chat** (text with emoji, per-message reactions, live reaction bursts) and a
  **playlist**. The host and co-hosts add, remove, reorder and pick what plays next; followers
  **suggest** items the host accepts or rejects, or add directly when the room's playlist policy
  allows it. The hub keeps the last 200 chat messages and the playlist in memory so a late joiner
  sees both; nothing is persisted.

## 1. Lifecycle and join policy

```
host  POST /api/v1/rooms {media, policy, playlist_policy?, max_participants?}   → 201 {code, join_url}
any   GET  /api/v1/rooms/{code}                                → {code, host, media, policy, participants, created_at}
any   WS   /api/v1/rooms/{code}/ws  (Bearer or ?token=)         → join flow below
host  DELETE /api/v1/rooms/{code}                              → close
admin GET  /api/v1/admin/rooms · DELETE /api/v1/admin/rooms/{code}
```

`code` is 6 chars from the same look-alike-free alphabet as invite codes. `join_url` is
`PUBLIC_URL/room?code=ABC123`; the panel's `/room` page shows the title and a deep link
`yokan://room/ABC123?hub=<PUBLIC_URL>` for the app.

**Policy** (chosen by the host at creation, changeable while open):

| policy | Joiner opens the socket… |
|---|---|
| `open` | …and is a participant immediately. |
| `approve` (default) | …and sits in `pending`. Host (or co-host) gets `join_request`; answers `approve`/`deny`. Pending times out after 2 min. |
| `locked` | …and gets `denied {reason:"locked"}`. Existing participants stay. Host can lock a running session. |

Host also gets `kick {user}` and `ban {user}` (ban = denied for the life of the room).

**Playlist policy** (independent of the join policy, changeable while open):

| playlist_policy | Followers can… |
|---|---|
| `host_only` | …only watch the queue. |
| `suggest` (default) | …propose items; they appear as `suggested` until a host/co-host accepts or rejects. |
| `anyone` | …add directly to the end of the queue. Only host/co-hosts remove, move and pick what plays. |

Co-hosts always have full playlist control.

**Host disconnect**: room stays alive for 5 min waiting for the host to reconnect (same user id, any
device). If a co-host exists they drive meanwhile. After 5 min without a host the room closes.
`ponytail:` no host hand-over voting; promote a co-host beforehand if you want continuity.

**Limits** (server settings, defaults): 2 open rooms per user, 20 participants per room, 100 rooms per
server, 100 playlist items, 200 retained chat messages, 1 chat message per second per user (excess
gets `error {msg:"slow down"}` and is dropped). Creating rooms needs `together:host`; joining needs
`together:join`. Both are in the default user permission set.

## 2. Wire protocol (WebSocket, JSON, one message per frame)

Server → client on connect: `{"type":"hello","room":{…metadata…},"you":{"id","email","role":"host|co_host|participant|pending"}}`
then, once admitted: `state` (current position), `playlist` (full queue), and `chat_history`
(the retained messages with their reactions).

### Client → server

| type | who | payload |
|---|---|---|
| `state` | host / co_host | see §3 — the authoritative position |
| `approve` / `deny` / `kick` / `ban` | host / co_host | `{user}` |
| `promote` / `demote` | host | `{user}` (co_host) |
| `set_policy` | host | `{policy?, playlist_policy?}` |
| `media` | host / co_host | `{…media…}` — switch to something outside the playlist (also becomes the `playing` item) |
| **Playlist** | | |
| `pl_add` | host / co_host, or anyone under `anyone` | `{media, at?}` — `at` omitted = end |
| `pl_suggest` | any participant under `suggest` | `{media, note?}` → item with status `suggested` |
| `pl_accept` / `pl_reject` | host / co_host | `{id}` — accepted items move to the end of the queue |
| `pl_remove` | host / co_host; a follower may remove **their own** suggestion | `{id}` |
| `pl_move` | host / co_host | `{id, to}` — index within queued items |
| `pl_play` | host / co_host | `{id}` — makes it `playing` and emits `media` |
| `pl_next` | host / co_host | `{}` — host's player ended: mark `done`, play the next queued item |
| **Chat** | | |
| `chat` | any participant | `{text, reply_to?}` — text ≤ 500 chars; emoji are just Unicode in the text |
| `react` | any participant | `{msg_id, emoji}` — toggles this user's reaction on a message (emoji = one grapheme cluster, ≤ 32 bytes so ZWJ sequences fit) |
| `burst` | any participant | `{emoji}` — a live floating reaction over the player/reader; relayed, never stored |
| `presence` | any participant | `{detached: bool, position?}` — "I'm browsing on my own" / where I am |
| `ping` | any | `{t}` → server echoes `pong {t, server_ms}` for RTT + clock offset |

### Server → client

`hello`, `state`, `media`, `participant_joined`, `participant_left`, `join_request` (to host/co-hosts),
`approved`, `denied {reason}`, `role {user, role}`, `policy {policy, playlist_policy}`,
`playlist {items, playing}` (full snapshot after every change — ≤ 100 items, diffing isn't worth it),
`chat_history {messages}`, `chat {id, from, text, reply_to, at}`, `reaction {msg_id, emoji, user, on}`,
`burst {emoji, from}`, `presence {user, detached, position}`, `host_away {until}`, `host_back`,
`closed {reason}`, `pong`, `error {msg}`.

```jsonc
"playlist": {
  "playing": 12,
  "items": [ { "id": 12, "media": {…}, "added_by": "<user>", "status": "playing" },
             { "id": 13, "media": {…}, "added_by": "<user>", "status": "queued" },
             { "id": 14, "media": {…}, "added_by": "<user>", "note": "the OVA is better", "status": "suggested" } ]
}
"chat_history": { "messages": [ { "id": 1, "from": {"id","email"}, "text": "hi 👋", "reply_to": null, "at": 1756…,
                                  "reactions": { "❤️": ["<user>", "<user>"], "😂": ["<user>"] } } ] }
```

The server **stamps** every relayed `state`/`media` with `server_ms`, assigns `id`s to playlist
items and chat messages (per-room counters), rejects control messages from anyone without the role,
and enforces the playlist policy. Everything else is validated for size and relayed.

## 3. Media identity and position

```jsonc
"media": {
  "itemType": "anime",            // manga | anime | novel
  "sourceId": 123456789,          // stable per extension (same on every device)
  "sourceName": "…", "lang": "en",
  "title": "…", "cover": "https://…",   // display only, so a joiner sees what they're joining
  "link": "/series/abc",          // manga.link  → deterministic manga id on the client
  "chapter": { "url": "/series/abc/ep-3", "name": "Episode 3" }
}
"state": {                        // one of the three shapes, by itemType
  "positionMs": 812345, "playing": true, "rate": 1.0,        // anime
  "page": 17, "pages": 42,                                     // manga
  "progress": 0.63                                             // novel (0..1 within the chapter)
  , "server_ms": …               // added by the hub
}
```

Client-side follow rules, kept deliberately simple:

- **Anime**: host sends `state` on play/pause/seek/rate change and every 5 s while playing. Follower
  target = `positionMs + (now - server_ms - offset)` when playing. Drift > 1 s → seek; 0.3–1 s → nudge
  rate ±5 % for a few seconds; else nothing. `offset` comes from `ping/pong`.
- **Manga**: host sends `state` on page change. Follower turns to the page unless `detached`. Preload
  next 3 pages as usual.
- **Novel**: host sends `state` on scroll settle (debounced 500 ms). Follower scrolls to `progress`
  unless `detached`.
- **`media` change**: follower resolves `(sourceId, link, chapter.url)` locally. Not in library →
  offer to add. Source missing → show "install <sourceName>" and stay in the room, muted.
- **Playlist advance**: the hub does not know when playback ends. The host's player sends `pl_next`
  on end-of-media (manga: on "next chapter" past the last page; novel: same). Followers never advance
  on their own; they receive the resulting `media`.
- **Auto-add on switch**: a `media` sent by the host that isn't in the playlist becomes a `playing`
  item, so the queue always reflects what has actually been watched (`done` items stay, capped by the
  100-item limit, oldest `done` dropped first).

## 4. Hub implementation (yokan-hub)

```
src/rooms.rs        Room registry: RwLock<HashMap<code, Room>>; Room { code, host, co_hosts, policy,
                    playlist_policy, media, state, participants: HashMap<user, Participant{tx, role, device,
                    last_chat_at}>, pending, banned, playlist: Vec<Item>, playing: Option<id>,
                    chat: VecDeque<Msg> (cap 200), next_item_id, next_msg_id, created_at, host_away_since }
src/routes/rooms.rs create / get / close / ws handler / admin list+close
```

Chat and playlist are plain `Vec`/`VecDeque` mutations under the room's write lock, followed by one
relay. `react` toggles a `BTreeMap<emoji, BTreeSet<user>>` on the message. Emoji validation =
"one extended grapheme cluster, ≤ 8 bytes" via the `unicode-segmentation` crate (one dep, ~no code).
Text is length-checked and relayed verbatim; rendering is the client's job.

- One `tokio::sync::mpsc` sender per participant socket; relay = iterate participants. No broadcast
  channel needed; a room is ≤ 20 sockets.
- Room registry cleanup task piggybacks on the hourly `jobs::tick`: close rooms with no participants
  for 10 min or a host away > 5 min. Away-host timing is checked on every relay too, so it's prompt.
- `together:host` / `together:join` added to `perms.rs` and to `DEFAULT_USER`; `admin:rooms` for the panel.
- Audit: `room.create`, `room.close`, `room.ban`. Not joins/chat.
- Maintenance mode closes all rooms (`closed {reason:"maintenance"}`).

Test: one `#[tokio::test]` driving three sockets through `tower::ServiceExt` is awkward for WS; use a
real `TcpListener` on `127.0.0.1:0` inside the test and `tokio-tungstenite` (dev-dep) — host creates,
A joins under `approve` and is admitted, B joins and is denied, host sends `state`, A receives it with
`server_ms`; A suggests an item, host accepts it and `pl_next` makes it `playing` (A gets `media`);
A chats and reacts, B (re-admitted) gets `chat_history` with the reaction; host disconnects, A gets
`host_away`.

## 5. Admin panel

- `/rooms` page (perm `admin:rooms`): live table (code, host, title, policies, participants, queue
  length, age) with Close. Polls `GET /admin/rooms` every 5 s; no socket for the panel.
- `/room?code=…` public landing page: title, cover, host, participant count, what's playing and up
  next, "Open in Yokan" deep link, code in big type for typing on a TV.
- Dashboard tile: open rooms / people in rooms (from `stats`).

## 6. Client (this repo)

| # | Change | Where |
|---|---|---|
| 1 | `RoomClient` (Ktor WS, reconnect, ping/offset, message types) | `services/together/RoomClient.kt` |
| 2 | Together screen: create (pick title + episode from library, join + playlist policy), join by code / deep link, participant list with approve/deny/kick/promote, "detach / follow" toggle | `ui/screens/together/*` |
| 2a | **Chat**: side panel in landscape / bottom sheet in portrait; message list with reply, long-press → reaction row; composer uses the **OS emoji keyboard** (no emoji picker lib) plus a fixed quick row (👍 ❤️ 😂 😮 😢 🔥 👏 💀) that sends `burst`; bursts float up over the player/reader for ~2 s | `ui/screens/together/Chat.kt` |
| 2b | **Playlist**: tab next to chat. Everyone sees queued / playing / done; suggestions shown in their own section. Add = the same library picker as "create room" (title → episode/chapter). Host/co-host: accept / reject, remove, **move with ▲▼ and "play next"**, tap → play. Follower: suggest with optional note, remove own suggestion | `ui/screens/together/Playlist.kt` |
| 3 | Player hook: when hosting, emit `state` on play/pause/seek/5 s tick and `pl_next` on end-of-media; when following, apply target with the drift rules | player runtime (`player-runtime.md` invariants apply) |
| 4 | Reader hooks: manga page change / novel scroll settle ↔ `state` | manga reader, novel reader |
| 5 | Deep link `yokan://room/<code>?hub=` on Android/iOS/desktop; the app must be logged in to that hub | platform launchers |
| 6 | Sync-settings screen: "Together" section is only enabled when a hub is configured | `settings/sync/SyncSettingsScreen.kt` |

## 7. Phases

> **Status (2026-09-02):** phase 1 (hub) and phase 4 (panel) are implemented in `../yokan-hub`:
> `src/rooms.rs`, `src/routes/rooms.rs`, `tests/rooms_flow.rs`, panel `/rooms` and `/room`.
> Client phase 2, protocol half: `together/RoomModels.kt`, `RoomReducer.kt` (pure, tested),
> `RoomClient.kt` (WS + reconnect + ping/offset + every command), `RoomApi` (create/info/close).
> UI half: `ui/screens/TogetherScreen.kt` (join by code, waiting/denied/closed panes, chat with reactions and
> replies, playlist with accept/reject/move/play, people with approve/deny/kick/promote, join + playlist
> policy chips, follow switch, co-host "take control", quick-reaction row), `together/TogetherSession.kt`
> (the one active room; hub creds from the sync preference), `ui/together/TogetherHooks.kt` (anime
> position sync, manga page sync, novel progress sync, follow-media-switch), title ⋮ menu → start room /
> add / suggest, More → Together, deep link `yokan://room/CODE`. Not compiled in the sandbox (Compose):
> run `:composeApp:desktopTest` and open a room on two devices. Not done: auto `pl_next` on end-of-media
> (the player has no end-file event yet; the host opening the next episode switches the room instead),
> a reader-side chat overlay (chat lives on the Together screen), rate-nudge soft sync (seek-only).
> Hook contract: host calls `RoomClient.sendPlayback/sendPage/sendProgress` and `playlistNext()` on
> end-of-media; followers read `RoomState.position` and `RoomReducer.expectedPositionMs(state, now)`.

| Phase | Scope | Size |
|---|---|---|
| 1 | hub: rooms module, REST, WS, approve flow, relay, playlist + chat state, limits, test | 4 days |
| 2 | client: RoomClient + Together screen + anime hosting/following | 1 week |
| 2a/2b | chat + reactions + bursts, playlist tab with suggest/accept/move | 4 days |
| 3 | manga + novel hooks, detach/follow, deep links | 3 days |
| 4 | panel `/rooms`, `/room` landing, dashboard tile | 1 day |

## 8. Skipped, and when to add

- **Persistent rooms / scheduled sessions / replay.** In-memory is enough for "let's watch this now".
  Add a table when someone wants a standing weekly room.
- **Voice / video.** A WebRTC signalling relay is a separate feature; the room WS could carry the
  signalling later without protocol changes.
- **Guests without accounts.** Invite-gated server; give them an invite instead.
- **Host hand-over election.** Co-hosts cover it.
- **Cross-source matching** (host on source A, follower only has source B). Needs title metadata
  matching; revisit when the metadata server work lands.
- **Persistent chat history.** The last 200 messages live in memory for late joiners; nothing
  survives the room. Add storage only if someone asks to read yesterday's chat.
- **Custom emotes, stickers, GIFs, an emoji picker library.** Unicode emoji via the OS keyboard plus
  a fixed quick row cover it. A picker lib is the first thing to add if users ask for search.
- **Drag-to-reorder** on the playlist. ▲▼ and "play next" are lazy and accessible; drag when it itches.
- **Per-user playlist grants.** The three-level room policy plus co-host promotion covers "if permitted".
- **Votes / skip polls** on the queue. Suggestions + host decision first.
