Yokan / rebuild
Course 1 8624561

TOGETHER_PLAN.md

docs/TOGETHER_PLAN.md

documentation / design asset252 lines
1# Read / Watch Together — Plan23One client hosts a **room** on yokan-hub; others join and follow the host's position in real time.4Works for anime (playback), manga (page), and novels (scroll progress). Builds on what the hub already5has: accounts, permissions, the WebSocket stack, the in-process broadcast hub.67## 0. Shape of the feature89- A room is **ephemeral and in-memory** on the hub. No table, no history. Server restart ends every10  room; clients show "room closed" and can re-create. `ponytail:` add a `rooms` table only if11  persistent rooms or replay are ever asked for.12- Everyone in a room has an **account on the same hub**. The server is invite-gated already, so13  "guest without account" is not a case we need.14- The hub is the **authority for membership and the latest state**, and a **relay for everything15  else**. It never touches media: each client resolves the title/episode locally through its own16  installed source. A joiner without that source is told which extension to install.17- The host drives. Followers can be granted control (`co_host`), and can temporarily **detach**18  locally (browse pages on their own) and re-attach.19- Every room has a **chat** (text with emoji, per-message reactions, live reaction bursts) and a20  **playlist**. The host and co-hosts add, remove, reorder and pick what plays next; followers21  **suggest** items the host accepts or rejects, or add directly when the room's playlist policy22  allows it. The hub keeps the last 200 chat messages and the playlist in memory so a late joiner23  sees both; nothing is persisted.2425## 1. Lifecycle and join policy2627```28host  POST /api/v1/rooms {media, policy, playlist_policy?, max_participants?}   → 201 {code, join_url}29any   GET  /api/v1/rooms/{code}                                → {code, host, media, policy, participants, created_at}30any   WS   /api/v1/rooms/{code}/ws  (Bearer or ?token=)         → join flow below31host  DELETE /api/v1/rooms/{code}                              → close32admin GET  /api/v1/admin/rooms · DELETE /api/v1/admin/rooms/{code}33```3435`code` is 6 chars from the same look-alike-free alphabet as invite codes. `join_url` is36`PUBLIC_URL/room?code=ABC123`; the panel's `/room` page shows the title and a deep link37`yokan://room/ABC123?hub=<PUBLIC_URL>` for the app.3839**Policy** (chosen by the host at creation, changeable while open):4041| policy | Joiner opens the socket… |42|---|---|43| `open` | …and is a participant immediately. |44| `approve` (default) | …and sits in `pending`. Host (or co-host) gets `join_request`; answers `approve`/`deny`. Pending times out after 2 min. |45| `locked` | …and gets `denied {reason:"locked"}`. Existing participants stay. Host can lock a running session. |4647Host also gets `kick {user}` and `ban {user}` (ban = denied for the life of the room).4849**Playlist policy** (independent of the join policy, changeable while open):5051| playlist_policy | Followers can… |52|---|---|53| `host_only` | …only watch the queue. |54| `suggest` (default) | …propose items; they appear as `suggested` until a host/co-host accepts or rejects. |55| `anyone` | …add directly to the end of the queue. Only host/co-hosts remove, move and pick what plays. |5657Co-hosts always have full playlist control.5859**Host disconnect**: room stays alive for 5 min waiting for the host to reconnect (same user id, any60device). If a co-host exists they drive meanwhile. After 5 min without a host the room closes.61`ponytail:` no host hand-over voting; promote a co-host beforehand if you want continuity.6263**Limits** (server settings, defaults): 2 open rooms per user, 20 participants per room, 100 rooms per64server, 100 playlist items, 200 retained chat messages, 1 chat message per second per user (excess65gets `error {msg:"slow down"}` and is dropped). Creating rooms needs `together:host`; joining needs66`together:join`. Both are in the default user permission set.6768## 2. Wire protocol (WebSocket, JSON, one message per frame)6970Server → client on connect: `{"type":"hello","room":{…metadata…},"you":{"id","email","role":"host|co_host|participant|pending"}}`71then, once admitted: `state` (current position), `playlist` (full queue), and `chat_history`72(the retained messages with their reactions).7374### Client → server7576| type | who | payload |77|---|---|---|78| `state` | host / co_host | see §3 — the authoritative position |79| `approve` / `deny` / `kick` / `ban` | host / co_host | `{user}` |80| `promote` / `demote` | host | `{user}` (co_host) |81| `set_policy` | host | `{policy?, playlist_policy?}` |82| `media` | host / co_host | `{…media…}` — switch to something outside the playlist (also becomes the `playing` item) |83| **Playlist** | | |84| `pl_add` | host / co_host, or anyone under `anyone` | `{media, at?}` — `at` omitted = end |85| `pl_suggest` | any participant under `suggest` | `{media, note?}` → item with status `suggested` |86| `pl_accept` / `pl_reject` | host / co_host | `{id}` — accepted items move to the end of the queue |87| `pl_remove` | host / co_host; a follower may remove **their own** suggestion | `{id}` |88| `pl_move` | host / co_host | `{id, to}` — index within queued items |89| `pl_play` | host / co_host | `{id}` — makes it `playing` and emits `media` |90| `pl_next` | host / co_host | `{}` — host's player ended: mark `done`, play the next queued item |91| **Chat** | | |92| `chat` | any participant | `{text, reply_to?}` — text ≤ 500 chars; emoji are just Unicode in the text |93| `react` | any participant | `{msg_id, emoji}` — toggles this user's reaction on a message (emoji = one grapheme cluster, ≤ 32 bytes so ZWJ sequences fit) |94| `burst` | any participant | `{emoji}` — a live floating reaction over the player/reader; relayed, never stored |95| `presence` | any participant | `{detached: bool, position?}` — "I'm browsing on my own" / where I am |96| `ping` | any | `{t}` → server echoes `pong {t, server_ms}` for RTT + clock offset |9798### Server → client99100`hello`, `state`, `media`, `participant_joined`, `participant_left`, `join_request` (to host/co-hosts),101`approved`, `denied {reason}`, `role {user, role}`, `policy {policy, playlist_policy}`,102`playlist {items, playing}` (full snapshot after every change — ≤ 100 items, diffing isn't worth it),103`chat_history {messages}`, `chat {id, from, text, reply_to, at}`, `reaction {msg_id, emoji, user, on}`,104`burst {emoji, from}`, `presence {user, detached, position}`, `host_away {until}`, `host_back`,105`closed {reason}`, `pong`, `error {msg}`.106107```jsonc108"playlist": {109  "playing": 12,110  "items": [ { "id": 12, "media": {…}, "added_by": "<user>", "status": "playing" },111             { "id": 13, "media": {…}, "added_by": "<user>", "status": "queued" },112             { "id": 14, "media": {…}, "added_by": "<user>", "note": "the OVA is better", "status": "suggested" } ]113}114"chat_history": { "messages": [ { "id": 1, "from": {"id","email"}, "text": "hi 👋", "reply_to": null, "at": 1756…,115                                  "reactions": { "❤️": ["<user>", "<user>"], "😂": ["<user>"] } } ] }116```117118The server **stamps** every relayed `state`/`media` with `server_ms`, assigns `id`s to playlist119items and chat messages (per-room counters), rejects control messages from anyone without the role,120and enforces the playlist policy. Everything else is validated for size and relayed.121122## 3. Media identity and position123124```jsonc125"media": {126  "itemType": "anime",            // manga | anime | novel127  "sourceId": 123456789,          // stable per extension (same on every device)128  "sourceName": "…", "lang": "en",129  "title": "…", "cover": "https://…",   // display only, so a joiner sees what they're joining130  "link": "/series/abc",          // manga.link  → deterministic manga id on the client131  "chapter": { "url": "/series/abc/ep-3", "name": "Episode 3" }132}133"state": {                        // one of the three shapes, by itemType134  "positionMs": 812345, "playing": true, "rate": 1.0,        // anime135  "page": 17, "pages": 42,                                     // manga136  "progress": 0.63                                             // novel (0..1 within the chapter)137  , "server_ms": …               // added by the hub138}139```140141Client-side follow rules, kept deliberately simple:142143- **Anime**: host sends `state` on play/pause/seek/rate change and every 5 s while playing. Follower144  target = `positionMs + (now - server_ms - offset)` when playing. Drift > 1 s → seek; 0.3–1 s → nudge145  rate ±5 % for a few seconds; else nothing. `offset` comes from `ping/pong`.146- **Manga**: host sends `state` on page change. Follower turns to the page unless `detached`. Preload147  next 3 pages as usual.148- **Novel**: host sends `state` on scroll settle (debounced 500 ms). Follower scrolls to `progress`149  unless `detached`.150- **`media` change**: follower resolves `(sourceId, link, chapter.url)` locally. Not in library →151  offer to add. Source missing → show "install <sourceName>" and stay in the room, muted.152- **Playlist advance**: the hub does not know when playback ends. The host's player sends `pl_next`153  on end-of-media (manga: on "next chapter" past the last page; novel: same). Followers never advance154  on their own; they receive the resulting `media`.155- **Auto-add on switch**: a `media` sent by the host that isn't in the playlist becomes a `playing`156  item, so the queue always reflects what has actually been watched (`done` items stay, capped by the157  100-item limit, oldest `done` dropped first).158159## 4. Hub implementation (yokan-hub)160161```162src/rooms.rs        Room registry: RwLock<HashMap<code, Room>>; Room { code, host, co_hosts, policy,163                    playlist_policy, media, state, participants: HashMap<user, Participant{tx, role, device,164                    last_chat_at}>, pending, banned, playlist: Vec<Item>, playing: Option<id>,165                    chat: VecDeque<Msg> (cap 200), next_item_id, next_msg_id, created_at, host_away_since }166src/routes/rooms.rs create / get / close / ws handler / admin list+close167```168169Chat and playlist are plain `Vec`/`VecDeque` mutations under the room's write lock, followed by one170relay. `react` toggles a `BTreeMap<emoji, BTreeSet<user>>` on the message. Emoji validation =171"one extended grapheme cluster, ≤ 8 bytes" via the `unicode-segmentation` crate (one dep, ~no code).172Text is length-checked and relayed verbatim; rendering is the client's job.173174- One `tokio::sync::mpsc` sender per participant socket; relay = iterate participants. No broadcast175  channel needed; a room is ≤ 20 sockets.176- Room registry cleanup task piggybacks on the hourly `jobs::tick`: close rooms with no participants177  for 10 min or a host away > 5 min. Away-host timing is checked on every relay too, so it's prompt.178- `together:host` / `together:join` added to `perms.rs` and to `DEFAULT_USER`; `admin:rooms` for the panel.179- Audit: `room.create`, `room.close`, `room.ban`. Not joins/chat.180- Maintenance mode closes all rooms (`closed {reason:"maintenance"}`).181182Test: one `#[tokio::test]` driving three sockets through `tower::ServiceExt` is awkward for WS; use a183real `TcpListener` on `127.0.0.1:0` inside the test and `tokio-tungstenite` (dev-dep) — host creates,184A joins under `approve` and is admitted, B joins and is denied, host sends `state`, A receives it with185`server_ms`; A suggests an item, host accepts it and `pl_next` makes it `playing` (A gets `media`);186A chats and reacts, B (re-admitted) gets `chat_history` with the reaction; host disconnects, A gets187`host_away`.188189## 5. Admin panel190191- `/rooms` page (perm `admin:rooms`): live table (code, host, title, policies, participants, queue192  length, age) with Close. Polls `GET /admin/rooms` every 5 s; no socket for the panel.193- `/room?code=…` public landing page: title, cover, host, participant count, what's playing and up194  next, "Open in Yokan" deep link, code in big type for typing on a TV.195- Dashboard tile: open rooms / people in rooms (from `stats`).196197## 6. Client (this repo)198199| # | Change | Where |200|---|---|---|201| 1 | `RoomClient` (Ktor WS, reconnect, ping/offset, message types) | `services/together/RoomClient.kt` |202| 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/*` |203| 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` |204| 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` |205| 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) |206| 4 | Reader hooks: manga page change / novel scroll settle ↔ `state` | manga reader, novel reader |207| 5 | Deep link `yokan://room/<code>?hub=` on Android/iOS/desktop; the app must be logged in to that hub | platform launchers |208| 6 | Sync-settings screen: "Together" section is only enabled when a hub is configured | `settings/sync/SyncSettingsScreen.kt` |209210## 7. Phases211212> **Status (2026-09-02):** phase 1 (hub) and phase 4 (panel) are implemented in `../yokan-hub`:213> `src/rooms.rs`, `src/routes/rooms.rs`, `tests/rooms_flow.rs`, panel `/rooms` and `/room`.214> Client phase 2, protocol half: `together/RoomModels.kt`, `RoomReducer.kt` (pure, tested),215> `RoomClient.kt` (WS + reconnect + ping/offset + every command), `RoomApi` (create/info/close).216> UI half: `ui/screens/TogetherScreen.kt` (join by code, waiting/denied/closed panes, chat with reactions and217> replies, playlist with accept/reject/move/play, people with approve/deny/kick/promote, join + playlist218> policy chips, follow switch, co-host "take control", quick-reaction row), `together/TogetherSession.kt`219> (the one active room; hub creds from the sync preference), `ui/together/TogetherHooks.kt` (anime220> position sync, manga page sync, novel progress sync, follow-media-switch), title ⋮ menu → start room /221> add / suggest, More → Together, deep link `yokan://room/CODE`. Not compiled in the sandbox (Compose):222> run `:composeApp:desktopTest` and open a room on two devices. Not done: auto `pl_next` on end-of-media223> (the player has no end-file event yet; the host opening the next episode switches the room instead),224> a reader-side chat overlay (chat lives on the Together screen), rate-nudge soft sync (seek-only).225> Hook contract: host calls `RoomClient.sendPlayback/sendPage/sendProgress` and `playlistNext()` on226> end-of-media; followers read `RoomState.position` and `RoomReducer.expectedPositionMs(state, now)`.227228| Phase | Scope | Size |229|---|---|---|230| 1 | hub: rooms module, REST, WS, approve flow, relay, playlist + chat state, limits, test | 4 days |231| 2 | client: RoomClient + Together screen + anime hosting/following | 1 week |232| 2a/2b | chat + reactions + bursts, playlist tab with suggest/accept/move | 4 days |233| 3 | manga + novel hooks, detach/follow, deep links | 3 days |234| 4 | panel `/rooms`, `/room` landing, dashboard tile | 1 day |235236## 8. Skipped, and when to add237238- **Persistent rooms / scheduled sessions / replay.** In-memory is enough for "let's watch this now".239  Add a table when someone wants a standing weekly room.240- **Voice / video.** A WebRTC signalling relay is a separate feature; the room WS could carry the241  signalling later without protocol changes.242- **Guests without accounts.** Invite-gated server; give them an invite instead.243- **Host hand-over election.** Co-hosts cover it.244- **Cross-source matching** (host on source A, follower only has source B). Needs title metadata245  matching; revisit when the metadata server work lands.246- **Persistent chat history.** The last 200 messages live in memory for late joiners; nothing247  survives the room. Add storage only if someone asks to read yesterday's chat.248- **Custom emotes, stickers, GIFs, an emoji picker library.** Unicode emoji via the OS keyboard plus249  a fixed quick row cover it. A picker lib is the first thing to add if users ask for search.250- **Drag-to-reorder** on the playlist. ▲▼ and "play next" are lazy and accessible; drag when it itches.251- **Per-user playlist grants.** The three-level room policy plus co-host promotion covers "if permitted".252- **Votes / skip polls** on the queue. Suggestions + host decision first.253

Search chapters, reference and source filenames.