# 22 — together: file workbook

[Implementation chapter](../chapters/22-together.md) · [Coverage index](README.md)

Each text entry includes the complete pinned file to write at the displayed path, plus an exact-byte download. Read the chapter for implementation order and behavior, then connect callers and reproduce the tests. Platform variants preserve their platform capabilities. Binary assets are retained with applicable licenses or independently recreated, not transcribed as code.

**Pinned baseline for comparison.** Use the reviewed listings in the [implementation chapters](../README.md#reading-order) and the [reviewed source archive](reviewed-source.zip) when reconstructing the app. See the [architecture review](architecture-review.md) for changes.

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/ProfileTogetherSession.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/ProfileTogetherSession.kt) · implementation · 198 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
38: internal sealed interface RoomMediaTarget {
39: data class Open(val mangaId: Long, val chapterId: Long) : RoomMediaTarget
40: data class NotInLibrary(val title: String, val sourceName: String?) : RoomMediaTarget
41: data class NoChapters(val title: String) : RoomMediaTarget
46: internal class ProfileTogetherSession(
86: fun setFollowing(value: Boolean) { if (ownerJob.isActive && job.isActive && _client.value?.isAvailable != false) _following.update { value } }
87: fun setDriving(value: Boolean) { if (ownerJob.isActive && job.isActive && _client.value?.isAvailable != false) _driving.update { value } }
89: private data class RoomAccount(val syncId: Long?, val session: HubSession)
91: private fun account(pref: DbSyncPreference?): RoomAccount? {
99: private fun currentAccount(): RoomAccount? {
104: fun hubSession(): HubSession? = currentAccount()?.session
106: private fun clearCurrent() {
112: private suspend fun closeClients() {
119: private suspend fun <T> runOwned(action: suspend () -> T): T = scope.runJoined { action() }
122: class JoinedRoom(val created: RoomApi.Created, val client: RoomClient)
124: fun owns(candidate: RoomClient): Boolean = ownerJob.isActive && job.isActive &&
132: fun resolveMedia(media: RoomMedia, repository: YokanRepository, settings: DbSettings): RoomMediaTarget? {
146: suspend fun createAndJoin(http: HttpService, media: RoomMedia): Result<JoinedRoom>? = runOwned {
159: suspend fun join(session: HubSession, code: String): RoomClient? = runOwned {
164: private suspend fun joinAccount(captured: RoomAccount, code: String): RoomClient? = operationLock.withLock {
180: suspend fun leave(expectedClient: RoomClient? = null) = runOwned {
188: suspend fun closeAndJoin() {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/ProfileTogetherSession.kt) · SHA-256 `fb9d4d0def7cefac0789d1f9b6e39614a7f52a619c381998611b493055059374`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.together

import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.SyncServerProvider
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.runJoined
import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.library.sortedChapters
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.createPlatformHttpClientEngine
import eu.friedcutlet.yokan.services.http.normalizeHubServer
import io.ktor.client.engine.HttpClientEngine
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext

/** Where following a room's media leads in this profile's library. */
internal sealed interface RoomMediaTarget {
    data class Open(val mangaId: Long, val chapterId: Long) : RoomMediaTarget
    data class NotInLibrary(val title: String, val sourceName: String?) : RoomMediaTarget
    data class NoChapters(val title: String) : RoomMediaTarget
}

/** Mutable room state and transports belong to the captured profile, including external UI calls. */
@OptIn(ExperimentalCoroutinesApi::class)
internal class ProfileTogetherSession(
    val profileId: ProfileId,
    private val database: YokanDatabase,
    ownerScope: CoroutineScope,
    private val engineFactory: (ProfileId) -> HttpClientEngine = ::createPlatformHttpClientEngine,
) {
    private val ownerJob = requireNotNull(ownerScope.coroutineContext[Job]) { "Together requires an owner job" }
    private val job = SupervisorJob(ownerJob)
    private val scope = CoroutineScope(ownerScope.coroutineContext + job)
    private val operationLock = Mutex()
    // Retain clients until successful cleanup, including an interrupted room replacement.
    private val clients = mutableListOf<RoomClient>()
    private var activeAccount: RoomAccount? = null
    private val _client = MutableStateFlow<RoomClient?>(null)
    val client = _client.asStateFlow()
    val state = _client.flatMapLatest { it?.state ?: flowOf(null) }
    private val _following = MutableStateFlow(true)
    val following = _following.asStateFlow()
    private val _driving = MutableStateFlow(false)
    val driving = _driving.asStateFlow()

    init {
        scope.launch {
            database.snapshots().map { account(it.syncPreferences.firstOrNull()) }.distinctUntilChanged().collect {
                catchingNonCancellation {
                    operationLock.withLock {
                        val current = _client.value
                        if (current != null && (activeAccount != currentAccount() || !current.isAvailable)) {
                            clearCurrent()
                            closeClients()
                        }
                    }
                }.onFailure {
                    // Keep failed cleanup targets for explicit leave/join or session retirement.
                    AppLogger.warn("[together] account-change cleanup failed (${it::class.simpleName}); cleanup can be retried")
                }
            }
        }
    }

    fun setFollowing(value: Boolean) { if (ownerJob.isActive && job.isActive && _client.value?.isAvailable != false) _following.update { value } }
    fun setDriving(value: Boolean) { if (ownerJob.isActive && job.isActive && _client.value?.isAvailable != false) _driving.update { value } }

    private data class RoomAccount(val syncId: Long?, val session: HubSession)

    private fun account(pref: DbSyncPreference?): RoomAccount? {
        pref ?: return null
        if (pref.serverProvider != SyncServerProvider.YokanHub) return null
        val server = normalizeHubServer(pref.server) ?: return null
        val token = pref.authToken?.takeIf { it.isNotBlank() } ?: return null
        return RoomAccount(pref.syncId, HubSession(server, token, pref.deviceId ?: "unknown"))
    }

    private fun currentAccount(): RoomAccount? {
        if (!ownerJob.isActive || !job.isActive) return null
        return account(database.syncPreferences().firstOrNull())
    }

    fun hubSession(): HubSession? = currentAccount()?.session

    private fun clearCurrent() {
        _client.value?.revoke()
        _client.update { null }; activeAccount = null
        _following.update { true }; _driving.update { false }
    }

    private suspend fun closeClients() {
        while (clients.isNotEmpty()) {
            clients.first().closeAndJoin()
            clients.removeAt(0)
        }
    }

    private suspend fun <T> runOwned(action: suspend () -> T): T = scope.runJoined { action() }

    /** A completed create operation retains its exact client for guarded UI delivery. */
    class JoinedRoom(val created: RoomApi.Created, val client: RoomClient)

    fun owns(candidate: RoomClient): Boolean = ownerJob.isActive && job.isActive &&
        _client.value === candidate && candidate.isAvailable

    /**
     * Resolves the room's [media] against this profile's library: the matching chapter (or the
     * first unread, or the first) of the local title. Null once the current room no longer shows
     * [media]. Repository reads are synchronous snapshot lookups.
     */
    fun resolveMedia(media: RoomMedia, repository: YokanRepository, settings: DbSettings): RoomMediaTarget? {
        if (_client.value?.state?.value?.media != media) return null
        val manga = repository.snapshots.value.mangas.firstOrNull {
            it.link == media.link &&
                (it.sourceId == media.sourceId || (media.sourceName != null && it.source.equals(media.sourceName, ignoreCase = true)))
        }?.id?.let(repository::manga)
            ?: return RoomMediaTarget.NotInLibrary(media.title ?: media.link, media.sourceName)
        val chapters = sortedChapters(manga, repository.chapters(manga.id), settings)
        val target = media.chapter?.url?.let { url -> chapters.firstOrNull { it.url == url } }
            ?: chapters.firstOrNull { !it.isRead } ?: chapters.firstOrNull()
        return target?.let { RoomMediaTarget.Open(manga.id, it.id) } ?: RoomMediaTarget.NoChapters(manga.name)
    }

    /** Own REST creation and socket replacement as one joined profile/controller call. */
    suspend fun createAndJoin(http: HttpService, media: RoomMedia): Result<JoinedRoom>? = runOwned {
        val captured = currentAccount() ?: return@runOwned null
        val callJob = requireNotNull(currentCoroutineContext()[Job])
        val created = RoomApi(http) { callJob.isActive && currentAccount() == captured }
            .create(captured.session, media)
        val result = created.getOrElse { return@runOwned Result.failure(it) }
        currentCoroutineContext().ensureActive()
        val next = joinAccount(captured, result.code)
            ?: throw CancellationException("Together account changed before joining the created room.")
        Result.success(JoinedRoom(result, next))
    }

    /** Reject an old account snapshot rather than connecting its token after settings changed. */
    suspend fun join(session: HubSession, code: String): RoomClient? = runOwned {
        val captured = currentAccount()?.takeIf { it.session == session } ?: return@runOwned null
        joinAccount(captured, code)
    }

    private suspend fun joinAccount(captured: RoomAccount, code: String): RoomClient? = operationLock.withLock {
        currentCoroutineContext().ensureActive(); ownerJob.ensureActive()
        if (currentAccount() != captured) return@withLock null
        clearCurrent()
        closeClients()
        currentCoroutineContext().ensureActive(); ownerJob.ensureActive()
        if (currentAccount() != captured) return@withLock null
        val next = RoomClient(engineFactory(profileId), captured.session, code, scope) { currentAccount() == captured }
        clients += next
        activeAccount = captured
        _following.update { true }; _driving.update { false }
        _client.update { next }
        next.connect()
        next
    }

    suspend fun leave(expectedClient: RoomClient? = null) = runOwned {
        operationLock.withLock {
            if (expectedClient != null && _client.value !== expectedClient) return@withLock
            clearCurrent()
            closeClients()
        }
    }

    suspend fun closeAndJoin() {
        job.cancel()
        withContext(NonCancellable) {
            job.join()
            operationLock.withLock {
                clearCurrent()
                closeClients()
            }
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/RoomClient.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/RoomClient.kt) · implementation · 340 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
54: data class HubSession(val server: String, val token: String, val deviceId: String) {
60: class RoomApi(
64: data class Created(val code: String, val joinUrl: String)
66: suspend fun create(
89: suspend fun info(session: HubSession, code: String): Result<RoomSummary> = catchingNonCancellation {
97: suspend fun close(session: HubSession, code: String): Result<Unit> = catchingNonCancellation {
105: private suspend fun ensureCurrent() {
110: private fun errorOf(body: String): String? =
122: class RoomClient(
163: internal fun revoke() { lifecycleJob.cancel() }
165: fun connect() {
175: fun close() {
181: suspend fun closeAndJoin() = retirementLock.withLock {
193: private fun release() = lock.withLock {
202: private suspend fun run() {
249: private fun handle(msg: JsonObject) {
271: private fun send(type: String, build: kotlinx.serialization.json.JsonObjectBuilder.() -> Unit = {}) {
283: private fun ping() = send("ping") { put("t", nowMillis()) }
286: fun sendState(fields: Map<String, JsonElement>) = send("state") { fields.forEach { (k, v) -> put(k, v) } }
288: fun sendPlayback(positionMs: Long, playing: Boolean, rate: Double = 1.0) =
291: fun sendPage(page: Int, pages: Int) = sendState(mapOf("page" to JsonPrimitive(page), "pages" to JsonPrimitive(pages)))
293: fun sendProgress(progress: Double) = sendState(mapOf("progress" to JsonPrimitive(progress)))
295: fun setMedia(media: RoomMedia) = send("media") {
299: fun approve(userId: String) = send("approve") { put("user", userId) }
300: fun deny(userId: String) = send("deny") { put("user", userId) }
301: fun kick(userId: String) = send("kick") { put("user", userId) }
302: fun ban(userId: String) = send("ban") { put("user", userId) }
303: fun promote(userId: String) = send("promote") { put("user", userId) }
304: fun demote(userId: String) = send("demote") { put("user", userId) }
305: fun setPolicy(policy: String? = null, playlistPolicy: String? = null) = send("set_policy") {
310: fun playlistAdd(media: RoomMedia, at: Int? = null) = send("pl_add") {
314: fun playlistSuggest(media: RoomMedia, note: String? = null) = send("pl_suggest") {
318: fun playlistAccept(id: Long) = send("pl_accept") { put("id", id) }
319: fun playlistReject(id: Long) = send("pl_reject") { put("id", id) }
320: fun playlistRemove(id: Long) = send("pl_remove") { put("id", id) }
321: fun playlistMove(id: Long, to: Int) = send("pl_move") { put("id", id); put("to", to) }
322: fun playlistPlay(id: Long) = send("pl_play") { put("id", id) }
323: fun playlistNext() = send("pl_next")
325: fun chat(text: String, replyTo: Long? = null) = send("chat") {
329: fun react(messageId: Long, emoji: String) = send("react") { put("msg_id", messageId); put("emoji", emoji) }
330: fun burst(emoji: String) = send("burst") { put("emoji", emoji) }
331: fun presence(detached: Boolean, position: JsonElement? = null) = send("presence") {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/RoomClient.kt) · SHA-256 `e0f4ac02fd704e91cf68bccc489b09d2820a6a3339e2596e724216fa74c0f775`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.together

import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.hubWebSocketBase
import eu.friedcutlet.yokan.util.nowMillis
import eu.friedcutlet.yokan.util.PlatformLock
import io.ktor.client.HttpClient
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.plugins.websocket.DefaultClientWebSocketSession
import io.ktor.client.plugins.websocket.WebSockets
import io.ktor.client.plugins.websocket.webSocket
import io.ktor.client.request.header
import io.ktor.http.HttpHeaders
import io.ktor.websocket.Frame
import io.ktor.websocket.readText
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.withContext
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlin.concurrent.Volatile
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.longOrNull
import kotlinx.serialization.json.put

/** Credentials for one hub; the same ones the sync service stores in `sync_preference`. */
data class HubSession(val server: String, val token: String, val deviceId: String) {
    val wsBase: String get() = hubWebSocketBase(server)
    val headers: Map<String, String> get() = mapOf("Authorization" to "Bearer $token", "X-Device" to deviceId)
}

/** REST side of rooms: create, look up, close. */
class RoomApi(
    private val http: HttpService,
    private val isSessionCurrent: () -> Boolean = { true },
) {
    data class Created(val code: String, val joinUrl: String)

    suspend fun create(
        session: HubSession,
        media: RoomMedia,
        policy: String = "approve",
        playlistPolicy: String = "suggest",
        maxParticipants: Int? = null,
    ): Result<Created> = catchingNonCancellation {
        ensureCurrent()
        val body = buildJsonObject {
            put("media", RoomJson.encodeToJsonElement(RoomMedia.serializer(), media))
            put("policy", policy)
            put("playlist_policy", playlistPolicy)
            if (maxParticipants != null) put("max_participants", maxParticipants)
        }
        ensureCurrent()
        val r = http.request(HttpRequest("${session.server}/api/v1/rooms", "POST", session.headers + ("Content-Type" to "application/json"), body.toString()))
        ensureCurrent()
        check(r.statusCode in 200..299) { errorOf(r.body) ?: "Hub returned HTTP ${r.statusCode}" }
        val o = RoomJson.parseToJsonElement(r.body).jsonObject
        val code = requireNotNull(o["code"]?.jsonPrimitive?.contentOrNull) { "Hub response has no room code." }
        Created(code, o["join_url"]?.jsonPrimitive?.contentOrNull.orEmpty()).also { ensureCurrent() }
    }

    suspend fun info(session: HubSession, code: String): Result<RoomSummary> = catchingNonCancellation {
        ensureCurrent()
        val r = http.request(HttpRequest("${session.server}/api/v1/rooms/${code.uppercase()}", "GET", session.headers))
        ensureCurrent()
        check(r.statusCode in 200..299) { if (r.statusCode == 404) "No room with code ${code.uppercase()}." else errorOf(r.body) ?: "Hub returned HTTP ${r.statusCode}" }
        RoomJson.decodeFromString(RoomSummary.serializer(), r.body).also { ensureCurrent() }
    }

    suspend fun close(session: HubSession, code: String): Result<Unit> = catchingNonCancellation {
        ensureCurrent()
        val r = http.request(HttpRequest("${session.server}/api/v1/rooms/${code.uppercase()}", "DELETE", session.headers))
        ensureCurrent()
        check(r.statusCode in 200..299) { errorOf(r.body) ?: "Hub returned HTTP ${r.statusCode}" }
        ensureCurrent()
    }

    private suspend fun ensureCurrent() {
        currentCoroutineContext().ensureActive()
        if (!isSessionCurrent()) throw CancellationException("Together account changed during room request.")
    }

    private fun errorOf(body: String): String? =
        runCatching { RoomJson.parseToJsonElement(body).jsonObject["error"]?.jsonPrimitive?.contentOrNull }.getOrNull()
}

/**
 * One WebSocket into one room. [state] is the reduced view for the UI, [bursts] the live emoji
 * stream. Reconnects with backoff until [close] or the hub says the room is gone. Owns [engine]:
 * [close] releases it.
 *
 * Every command is fire-and-forget; the hub answers with a state message (or `error`, surfaced as
 * `RoomState.lastError`). The player/reader hooks call [sendState] and read [RoomState.position].
 */
class RoomClient(
    engine: HttpClientEngine,
    private val session: HubSession,
    code: String,
    scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default),
    private val isSessionCurrent: () -> Boolean = { true },
) {
    private val ownerJob = requireNotNull(scope.coroutineContext[Job]) { "Room client requires an owner job" }
    private val lifecycleJob = SupervisorJob(ownerJob)
    private val scope = CoroutineScope(scope.coroutineContext + lifecycleJob)
    private val lock = PlatformLock()
    private val engine = eu.friedcutlet.yokan.services.http.ProfileHttpEngine(engine, lifecycleJob) { isAvailable }
    private val retirementLock = Mutex()
    private var released = false
    val code: String = code.uppercase()
    private val client = HttpClient(this.engine) {
        expectSuccess = false
        install(WebSockets)
    }
    private val _state = MutableStateFlow(RoomState(code = this.code))
    val state: StateFlow<RoomState> = _state.asStateFlow()
    private val _bursts = MutableSharedFlow<RoomBurst>(extraBufferCapacity = 64)
    val bursts: SharedFlow<RoomBurst> = _bursts.asSharedFlow()

    @Volatile
    private var ws: DefaultClientWebSocketSession? = null
    private var job: Job? = null

    /** Checking a revoked account permanently ends this client, even if its credentials return. */
    internal val isAvailable: Boolean
        get() {
            if (!lifecycleJob.isActive || !ownerJob.isActive) return false
            // The guard may read the database. Keep it outside room/engine locks.
            if (!isSessionCurrent()) {
                lifecycleJob.cancel()
                return false
            }
            return lifecycleJob.isActive && ownerJob.isActive
        }

    /** Stop admission immediately; transport release remains in awaited cleanup. */
    internal fun revoke() { lifecycleJob.cancel() }

    fun connect() {
        if (!isAvailable) return
        val pending = lock.withLock {
            if (!lifecycleJob.isActive || !ownerJob.isActive || job?.isCompleted == false) return@withLock null
            // Start outside the lock even with an immediate owner dispatcher.
            scope.launch(start = CoroutineStart.LAZY) { run() }.also { job = it }
        }
        pending?.start()
    }

    fun close() {
        lifecycleJob.cancel()
        release()
    }

    /** Leaves socket/pinger/send finalizers joined before releasing the captured transport. */
    suspend fun closeAndJoin() = retirementLock.withLock {
        withContext(NonCancellable) {
            lifecycleJob.cancelAndJoin()
            // Engine call coroutines can finish outside the room's caller scope.
            val clientJob = client.coroutineContext[Job]
            clientJob?.cancel()
            engine.closeAndJoin()
            clientJob?.join()
            release()
        }
    }

    private fun release() = lock.withLock {
        if (!released) {
            client.close()
            // Ktor leaves an engine it was handed open; this client is its only user.
            engine.close()
            released = true
        }
    }

    private suspend fun run() {
        var backoff = 1_000L
        while (scope.isActive && isAvailable) {
            val terminal = _state.value.connection
            if (terminal is RoomConnection.Denied || terminal is RoomConnection.Closed) return
            try {
                client.webSocket(
                    urlString = "${session.wsBase}/api/v1/rooms/$code/ws",
                    request = {
                        if (!isAvailable) throw CancellationException("Together account changed")
                        header(HttpHeaders.Authorization, "Bearer ${session.token}")
                        header("X-Device", session.deviceId)
                    },
                ) {
                    if (!isAvailable) throw CancellationException("Together account changed")
                    ws = this
                    backoff = 1_000L
                    val pinger = launch {
                        while (isActive) {
                            ping()
                            delay(15_000L)
                        }
                    }
                    try {
                        for (frame in incoming) {
                            val text = (frame as? Frame.Text)?.readText() ?: continue
                            val msg = runCatching { RoomJson.parseToJsonElement(text).jsonObject }.getOrNull() ?: continue
                            handle(msg)
                        }
                    } finally {
                        pinger.cancel()
                        ws = null
                    }
                }
            } catch (cancelled: CancellationException) {
                throw cancelled
            } catch (_: Throwable) {
                // fall through to reconnect
            }
            val after = _state.value.connection
            if (after is RoomConnection.Denied || after is RoomConnection.Closed || !isAvailable) return
            _state.update { it.copy(connection = RoomConnection.Connecting) }
            delay(backoff)
            backoff = (backoff * 2).coerceAtMost(30_000L)
        }
    }

    private fun handle(msg: JsonObject) {
        if (!isAvailable) return
        when (msg["type"]?.jsonPrimitive?.contentOrNull) {
            "burst" -> {
                val emoji = msg["emoji"]?.jsonPrimitive?.contentOrNull ?: return
                _bursts.tryEmit(RoomBurst(emoji, msg["from"]?.jsonPrimitive?.contentOrNull.orEmpty()))
            }
            "pong" -> {
                val t = msg["t"]?.jsonPrimitive?.longOrNull ?: return
                val serverMs = msg["server_ms"]?.jsonPrimitive?.longOrNull ?: return
                // The hub echoes our send time, so no per-ping bookkeeping is shared with the pinger.
                val sent = t
                val now = nowMillis()
                val offset = serverMs - (sent + (now - sent) / 2)
                _state.update { it.copy(clockOffsetMs = offset) }
            }
            else -> _state.update { RoomReducer.reduce(it, msg) }
        }
    }

    // ── commands ────────────────────────────────────────────────────────────

    private fun send(type: String, build: kotlinx.serialization.json.JsonObjectBuilder.() -> Unit = {}) {
        if (!isAvailable) return
        val msg = buildJsonObject {
            put("type", type)
            build()
        }
        val socket = ws ?: return
        scope.launch {
            if (isAvailable) catchingNonCancellation { socket.send(Frame.Text(msg.toString())) }
        }
    }

    private fun ping() = send("ping") { put("t", nowMillis()) }

    /** Host/co-host: authoritative position. Pass the shape for the item type (see `RoomState.position`). */
    fun sendState(fields: Map<String, JsonElement>) = send("state") { fields.forEach { (k, v) -> put(k, v) } }

    fun sendPlayback(positionMs: Long, playing: Boolean, rate: Double = 1.0) =
        sendState(mapOf("positionMs" to JsonPrimitive(positionMs), "playing" to JsonPrimitive(playing), "rate" to JsonPrimitive(rate)))

    fun sendPage(page: Int, pages: Int) = sendState(mapOf("page" to JsonPrimitive(page), "pages" to JsonPrimitive(pages)))

    fun sendProgress(progress: Double) = sendState(mapOf("progress" to JsonPrimitive(progress)))

    fun setMedia(media: RoomMedia) = send("media") {
        RoomJson.encodeToJsonElement(RoomMedia.serializer(), media).jsonObject.forEach { (k, v) -> put(k, v) }
    }

    fun approve(userId: String) = send("approve") { put("user", userId) }
    fun deny(userId: String) = send("deny") { put("user", userId) }
    fun kick(userId: String) = send("kick") { put("user", userId) }
    fun ban(userId: String) = send("ban") { put("user", userId) }
    fun promote(userId: String) = send("promote") { put("user", userId) }
    fun demote(userId: String) = send("demote") { put("user", userId) }
    fun setPolicy(policy: String? = null, playlistPolicy: String? = null) = send("set_policy") {
        policy?.let { put("policy", it) }
        playlistPolicy?.let { put("playlist_policy", it) }
    }

    fun playlistAdd(media: RoomMedia, at: Int? = null) = send("pl_add") {
        put("media", RoomJson.encodeToJsonElement(RoomMedia.serializer(), media))
        at?.let { put("at", it) }
    }
    fun playlistSuggest(media: RoomMedia, note: String? = null) = send("pl_suggest") {
        put("media", RoomJson.encodeToJsonElement(RoomMedia.serializer(), media))
        note?.takeIf { it.isNotBlank() }?.let { put("note", it) }
    }
    fun playlistAccept(id: Long) = send("pl_accept") { put("id", id) }
    fun playlistReject(id: Long) = send("pl_reject") { put("id", id) }
    fun playlistRemove(id: Long) = send("pl_remove") { put("id", id) }
    fun playlistMove(id: Long, to: Int) = send("pl_move") { put("id", id); put("to", to) }
    fun playlistPlay(id: Long) = send("pl_play") { put("id", id) }
    fun playlistNext() = send("pl_next")

    fun chat(text: String, replyTo: Long? = null) = send("chat") {
        put("text", text)
        replyTo?.let { put("reply_to", it) }
    }
    fun react(messageId: Long, emoji: String) = send("react") { put("msg_id", messageId); put("emoji", emoji) }
    fun burst(emoji: String) = send("burst") { put("emoji", emoji) }
    fun presence(detached: Boolean, position: JsonElement? = null) = send("presence") {
        put("detached", detached)
        position?.let { put("position", it) }
    }

    companion object {
        /** The fixed quick-reaction row; the OS emoji keyboard covers everything else. */
        val QUICK_REACTIONS = listOf("👍", "❤️", "😂", "😮", "😢", "🔥", "👏", "💀")
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/RoomModels.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/RoomModels.kt) · implementation · 131 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
17: data class RoomChapter(val url: String, val name: String? = null)
21: data class RoomMedia(
33: data class RoomUser(val id: String, val email: String)
36: data class RoomParticipant(val id: String, val email: String, val role: String, val detached: Boolean = false)
39: data class PlaylistItem(
49: data class ChatMessage(
60: data class RoomSummary(
76: enum class RoomRole { Host, CoHost, Participant, Pending, None;
80: fun parse(s: String?): RoomRole = when (s) {
90: sealed interface RoomConnection {
91: data object Connecting : RoomConnection
92: data object Open : RoomConnection
93: data class Denied(val reason: String) : RoomConnection
94: data class Closed(val reason: String) : RoomConnection
98: data class RoomBurst(val emoji: String, val from: String)
105: data class RoomState(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/RoomModels.kt) · SHA-256 `e7051276b1321a6d14ac1af40c62d06febfb25a655bb4d0030427b9ee0823aeb`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.together

import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject

/** Wire models for yokan-hub rooms. Field names match `yokan-hub/src/rooms.rs`. */

val RoomJson: Json = Json {
    ignoreUnknownKeys = true
    encodeDefaults = true
    explicitNulls = false
}

@Serializable
data class RoomChapter(val url: String, val name: String? = null)

/** What a room is showing. The hub relays it; each client resolves it through its own source. */
@Serializable
data class RoomMedia(
    val itemType: String,
    val sourceId: Long,
    val link: String,
    val sourceName: String? = null,
    val lang: String? = null,
    val title: String? = null,
    val cover: String? = null,
    val chapter: RoomChapter? = null,
)

@Serializable
data class RoomUser(val id: String, val email: String)

@Serializable
data class RoomParticipant(val id: String, val email: String, val role: String, val detached: Boolean = false)

@Serializable
data class PlaylistItem(
    val id: Long,
    val media: RoomMedia,
    @SerialName("added_by") val addedBy: RoomUser,
    val note: String? = null,
    /** queued | suggested | playing | done */
    val status: String,
)

@Serializable
data class ChatMessage(
    val id: Long,
    val from: RoomUser,
    val text: String,
    @SerialName("reply_to") val replyTo: Long? = null,
    val at: Long,
    /** emoji → user ids */
    val reactions: Map<String, List<String>> = emptyMap(),
)

@Serializable
data class RoomSummary(
    val code: String,
    val host: RoomUser,
    val title: String? = null,
    val media: RoomMedia? = null,
    val policy: String,
    @SerialName("playlist_policy") val playlistPolicy: String,
    val participants: Int = 0,
    val pending: Int = 0,
    @SerialName("max_participants") val maxParticipants: Int = 0,
    @SerialName("playlist_len") val playlistLen: Int = 0,
    @SerialName("up_next") val upNext: String? = null,
    @SerialName("age_secs") val ageSecs: Long = 0,
    @SerialName("host_away") val hostAway: Boolean = false,
)

enum class RoomRole { Host, CoHost, Participant, Pending, None;
    val controls: Boolean get() = this == Host || this == CoHost

    companion object {
        fun parse(s: String?): RoomRole = when (s) {
            "host" -> Host
            "co_host" -> CoHost
            "participant" -> Participant
            "pending" -> Pending
            else -> None
        }
    }
}

sealed interface RoomConnection {
    data object Connecting : RoomConnection
    data object Open : RoomConnection
    data class Denied(val reason: String) : RoomConnection
    data class Closed(val reason: String) : RoomConnection
}

/** A live emoji burst; not part of [RoomState] because it is never stored. */
data class RoomBurst(val emoji: String, val from: String)

/**
 * Everything the UI needs to render a room. Built by [RoomReducer] from server messages.
 * `position` is the host's last `state` payload as received (`positionMs`/`playing`/`rate`,
 * `page`/`pages`, or `progress`, plus `server_ms`); the player and reader hooks interpret it.
 */
data class RoomState(
    val code: String,
    val connection: RoomConnection = RoomConnection.Connecting,
    val summary: RoomSummary? = null,
    val youId: String? = null,
    val role: RoomRole = RoomRole.None,
    val participants: List<RoomParticipant> = emptyList(),
    val pendingJoins: List<RoomUser> = emptyList(),
    val media: RoomMedia? = null,
    val position: JsonObject? = null,
    val playlist: List<PlaylistItem> = emptyList(),
    val playing: Long? = null,
    val chat: List<ChatMessage> = emptyList(),
    val policy: String = "approve",
    val playlistPolicy: String = "suggest",
    val hostAway: Boolean = false,
    /** Estimated `hub clock − local clock` in ms, from ping/pong; 0 until the first pong. */
    val clockOffsetMs: Long = 0,
    val lastError: String? = null,
) {
    val isHost: Boolean get() = role == RoomRole.Host
    val controls: Boolean get() = role.controls
    val canAddToPlaylist: Boolean get() = controls || playlistPolicy == "anyone"
    val canSuggest: Boolean get() = controls || playlistPolicy != "host_only"
    val upNext: PlaylistItem? get() = playlist.firstOrNull { it.status == "queued" }
    val suggestions: List<PlaylistItem> get() = playlist.filter { it.status == "suggested" }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/RoomReducer.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/RoomReducer.kt) · implementation · 136 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
17: object RoomReducer {
18: fun reduce(state: RoomState, msg: JsonObject): RoomState {
109: fun expectedPositionMs(state: RoomState, nowMs: Long): Long? {
125: private fun JsonObject.str(key: String): String? = this[key]?.jsonPrimitive?.contentOrNull
127: private fun JsonElement.participant(): RoomParticipant {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/RoomReducer.kt) · SHA-256 `65ac5cfbe13fd5f06cf4d332e904ba16c184e911a7b3c3d33c0ca33cd0e88ecd`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.together

import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.long
import kotlinx.serialization.json.longOrNull

/**
 * Pure fold of hub messages into [RoomState]. No I/O, so the whole protocol is unit-testable.
 * Unknown message types are ignored; `burst` and `pong` are handled by [RoomClient] itself.
 */
object RoomReducer {
    fun reduce(state: RoomState, msg: JsonObject): RoomState {
        val type = msg["type"]?.jsonPrimitive?.contentOrNull ?: return state
        return when (type) {
            "hello" -> {
                val you = msg["you"]?.jsonObject
                val participants = msg["participants"]?.jsonArray?.map { it.participant() }.orEmpty()
                val summary = msg["room"]?.let { RoomJson.decodeFromJsonElement(RoomSummary.serializer(), it) }
                state.copy(
                    connection = RoomConnection.Open,
                    summary = summary,
                    youId = you?.get("id")?.jsonPrimitive?.contentOrNull,
                    role = RoomRole.parse(you?.get("role")?.jsonPrimitive?.contentOrNull),
                    participants = participants,
                    media = summary?.media ?: state.media,
                    policy = summary?.policy ?: state.policy,
                    playlistPolicy = summary?.playlistPolicy ?: state.playlistPolicy,
                    hostAway = summary?.hostAway ?: state.hostAway,
                    lastError = null,
                )
            }
            "approved" -> state.copy(role = RoomRole.Participant)
            "denied" -> state.copy(connection = RoomConnection.Denied(msg.str("reason") ?: "denied"))
            "closed" -> state.copy(connection = RoomConnection.Closed(msg.str("reason") ?: "closed"))
            "error" -> state.copy(lastError = msg.str("msg"))

            "state" -> state.copy(position = JsonObject(msg.filterKeys { it != "type" }))
            "media" -> state.copy(
                media = msg["media"]?.let { RoomJson.decodeFromJsonElement(RoomMedia.serializer(), it) },
                position = null,
            )
            "playlist" -> state.copy(
                playlist = msg["items"]?.let { RoomJson.decodeFromJsonElement(PlaylistItemList, it) }.orEmpty(),
                playing = msg["playing"]?.jsonPrimitive?.longOrNull,
            )
            "chat_history" -> state.copy(chat = msg["messages"]?.let { RoomJson.decodeFromJsonElement(ChatMessageList, it) }.orEmpty())
            "chat" -> state.copy(chat = (state.chat + RoomJson.decodeFromJsonElement(ChatMessage.serializer(), msg)).takeLast(CHAT_KEEP))
            "reaction" -> {
                val id = msg["msg_id"]?.jsonPrimitive?.long ?: return state
                val emoji = msg.str("emoji") ?: return state
                val user = msg.str("user") ?: return state
                val on = msg["on"]?.jsonPrimitive?.booleanOrNull ?: return state
                state.copy(
                    chat = state.chat.map { m ->
                        if (m.id != id) m else {
                            val users = (m.reactions[emoji].orEmpty() - user) + (if (on) listOf(user) else emptyList())
                            m.copy(reactions = if (users.isEmpty()) m.reactions - emoji else m.reactions + (emoji to users))
                        }
                    },
                )
            }

            "participant_joined" -> {
                val user = msg["user"]?.jsonObject ?: return state
                val p = RoomParticipant(user.str("id").orEmpty(), user.str("email").orEmpty(), msg.str("role") ?: "participant")
                state.copy(
                    participants = state.participants.filter { it.id != p.id } + p,
                    pendingJoins = state.pendingJoins.filter { it.id != p.id },
                )
            }
            "participant_left" -> {
                val id = msg.str("user") ?: return state
                state.copy(participants = state.participants.filter { it.id != id })
            }
            "join_request" -> {
                val user = msg["user"]?.let { RoomJson.decodeFromJsonElement(RoomUser.serializer(), it) } ?: return state
                state.copy(pendingJoins = state.pendingJoins.filter { it.id != user.id } + user)
            }
            "role" -> {
                val id = msg.str("user") ?: return state
                val role = msg.str("role") ?: return state
                state.copy(
                    participants = state.participants.map { if (it.id == id) it.copy(role = role) else it },
                    role = if (id == state.youId) RoomRole.parse(role) else state.role,
                )
            }
            "policy" -> state.copy(
                policy = msg.str("policy") ?: state.policy,
                playlistPolicy = msg.str("playlist_policy") ?: state.playlistPolicy,
            )
            "presence" -> {
                val id = msg.str("user") ?: return state
                val detached = msg["detached"]?.jsonPrimitive?.booleanOrNull ?: return state
                state.copy(participants = state.participants.map { if (it.id == id) it.copy(detached = detached) else it })
            }
            "host_away" -> state.copy(hostAway = true)
            "host_back" -> state.copy(hostAway = false)
            else -> state
        }
    }

    /** Position the host is at *now*, extrapolating playback since the hub stamped it. */
    fun expectedPositionMs(state: RoomState, nowMs: Long): Long? {
        val pos = state.position ?: return null
        val base = pos["positionMs"]?.jsonPrimitive?.longOrNull ?: return null
        val playing = pos["playing"]?.jsonPrimitive?.booleanOrNull ?: false
        if (!playing) return base
        val stamped = pos["server_ms"]?.jsonPrimitive?.longOrNull ?: return base
        val rate = pos["rate"]?.jsonPrimitive?.contentOrNull?.toDoubleOrNull() ?: 1.0
        val elapsed = (nowMs + state.clockOffsetMs) - stamped
        return base + (elapsed * rate).toLong()
    }

    const val CHAT_KEEP = 200

    private val PlaylistItemList = kotlinx.serialization.builtins.ListSerializer(PlaylistItem.serializer())
    private val ChatMessageList = kotlinx.serialization.builtins.ListSerializer(ChatMessage.serializer())

    private fun JsonObject.str(key: String): String? = this[key]?.jsonPrimitive?.contentOrNull

    private fun JsonElement.participant(): RoomParticipant {
        val o = jsonObject
        return RoomParticipant(
            id = o.str("id").orEmpty(),
            email = o.str("email").orEmpty(),
            role = o.str("role") ?: "participant",
            detached = o["detached"]?.jsonPrimitive?.booleanOrNull ?: false,
        )
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/RoomSync.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/RoomSync.kt) · implementation · 165 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
22: internal fun roomMediaFor(manga: Manga, chapter: Chapter?): RoomMedia = RoomMedia(
34: internal fun roomShows(media: RoomMedia?, manga: Manga, chapter: Chapter?): Boolean {
42: internal fun announceMedia(client: RoomClient, room: RoomState?, manga: Manga, chapter: Chapter) {
50: internal suspend fun reportPlayback(
80: internal suspend fun followPlayback(
106: internal fun reportPage(
123: internal suspend fun followPage(
140: internal suspend fun reportProgress(client: RoomClient, progressPercent: Int, drives: () -> Boolean) {
146: internal class ProgressFollower {
150: suspend fun follow(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/RoomSync.kt) · SHA-256 `c7ae38cad736a6032793b3adfa79bd63c58142d5f456af478f3272620afb1a19`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.together

import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.media.player.MediaPlayerController
import eu.friedcutlet.yokan.util.nowMillis
import kotlin.math.abs
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.ensureActive
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.jsonPrimitive

/*
 * Position sync between a room and the local reader/player. Host side reports, follower side
 * applies. `drives`/`follows` are the caller's admission checks; they are re-read before every
 * room message or player effect so a disposed screen or a replaced room stops immediately.
 */

/** The room's identity for [manga] / [chapter]. */
internal fun roomMediaFor(manga: Manga, chapter: Chapter?): RoomMedia = RoomMedia(
    itemType = manga.itemType.name.lowercase(),
    sourceId = manga.sourceId ?: 0L,
    link = manga.link,
    sourceName = manga.source,
    lang = manga.lang,
    title = manga.name,
    cover = manga.imageUrl,
    chapter = chapter?.let { RoomChapter(url = it.url, name = it.name) },
)

/** Same title and chapter as the room is showing? */
internal fun roomShows(media: RoomMedia?, manga: Manga, chapter: Chapter?): Boolean {
    media ?: return false
    val sameTitle = media.link == manga.link &&
        (media.sourceId == (manga.sourceId ?: 0L) || media.sourceName.equals(manga.source, ignoreCase = true))
    return sameTitle && media.chapter?.url == chapter?.url
}

/** Host: announce what is open unless the room already shows it. */
internal fun announceMedia(client: RoomClient, room: RoomState?, manga: Manga, chapter: Chapter) {
    if (!roomShows(room?.media, manga, chapter)) client.setMedia(roomMediaFor(manga, chapter))
}

/**
 * Anime host: reports play/pause/speed and position every 5 s while playing, at once on a jump
 * or a paused seek. Runs until [drives] turns false.
 */
internal suspend fun reportPlayback(
    client: RoomClient,
    controller: MediaPlayerController,
    isPlaying: Boolean,
    speed: Float,
    drives: () -> Boolean,
) {
    var lastSentAt = 0L
    var lastSentPos = -1L
    while (drives()) {
        currentCoroutineContext().ensureActive()
        val pos = controller.currentPositionMs()
        val now = nowMillis()
        val expected = if (lastSentPos < 0) pos else lastSentPos + ((now - lastSentAt) * speed).toLong()
        val jumped = isPlaying && abs(pos - expected) > 1_500
        if (lastSentPos < 0 || jumped || (isPlaying && now - lastSentAt >= 5_000) || (!isPlaying && lastSentPos != pos)) {
            if (!drives()) break
            client.sendPlayback(pos, isPlaying, speed.toDouble())
            lastSentAt = now
            lastSentPos = pos
        }
        delay(1_000)
    }
}

/**
 * Anime follower: seeks when more than a second off the host's extrapolated position and mirrors
 * play/pause, reporting it through [onFollowPlaying]. Re-checks every 3 s while the host plays.
 * [position] is the snapshot the caller keyed on; [room] is the room as of now.
 */
internal suspend fun followPlayback(
    position: JsonObject?,
    room: RoomState?,
    manga: Manga,
    chapter: Chapter,
    controller: MediaPlayerController,
    follows: (RoomState?) -> Boolean,
    onFollowPlaying: (Boolean) -> Unit,
) {
    if (position == null || room == null || !follows(room) || !roomShows(room.media, manga, chapter)) return
    val hostPlaying = position["playing"]?.jsonPrimitive?.booleanOrNull ?: return
    while (follows(room)) {
        currentCoroutineContext().ensureActive()
        val expected = RoomReducer.expectedPositionMs(room, nowMillis()) ?: break
        if (abs(controller.currentPositionMs() - expected) > 1_000 && follows(room)) controller.seekTo(expected.coerceAtLeast(0))
        if (follows(room) && controller.isPlaying() != hostPlaying) {
            if (!follows(room)) break
            if (hostPlaying) controller.play() else controller.pause()
            if (follows(room)) onFollowPlaying(hostPlaying)
        }
        if (!hostPlaying) break
        delay(3_000)
    }
}

/** Manga host: announce the chapter and report the current page. */
internal fun reportPage(
    client: RoomClient,
    room: RoomState?,
    manga: Manga,
    chapter: Chapter,
    pageIndex: Int,
    pageCount: Int,
    drives: () -> Boolean,
) {
    announceMedia(client, room, manga, chapter)
    if (pageCount > 0 && drives()) client.sendPage(pageIndex + 1, pageCount)
}

/**
 * Manga follower: the room's [page] (the snapshot the caller keyed on) as a clamped index,
 * passed to [onJump] when it differs from [pageIndex].
 */
internal suspend fun followPage(
    page: Int?,
    room: RoomState?,
    manga: Manga,
    chapter: Chapter,
    pageIndex: Int,
    pageCount: Int,
    follows: (RoomState?) -> Boolean,
    onJump: (Int) -> Unit,
) {
    if (page == null || !follows(room) || pageCount == 0 || !roomShows(room?.media, manga, chapter)) return
    val index = (page - 1).coerceIn(0, pageCount - 1)
    currentCoroutineContext().ensureActive()
    if (index != pageIndex && follows(room)) onJump(index)
}

/** Novel host: report the scroll percentage after a 500 ms debounce. */
internal suspend fun reportProgress(client: RoomClient, progressPercent: Int, drives: () -> Boolean) {
    delay(500)
    if (drives()) client.sendProgress(progressPercent / 100.0)
}

/** Novel follower. Remembers the last applied ratio so jitter under 2 % is not re-applied. */
internal class ProgressFollower {
    private var lastApplied = -1.0

    /** [progress] is the snapshot the caller keyed on; [room] is the room as of now. */
    suspend fun follow(
        progress: Double?,
        room: RoomState?,
        manga: Manga,
        chapter: Chapter,
        follows: (RoomState?) -> Boolean,
        onFollow: suspend (Double) -> Unit,
    ) {
        if (progress == null || !progress.isFinite() || !follows(room) || !roomShows(room?.media, manga, chapter)) return
        if (abs(progress - lastApplied) < 0.02) return
        currentCoroutineContext().ensureActive()
        if (!follows(room)) return
        onFollow(progress.coerceIn(0.0, 1.0))
        lastApplied = progress
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherActions.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherActions.kt) · implementation · 34 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
13: internal object TogetherActions {
15: suspend fun startRoom(together: ProfileTogetherSession, http: HttpService, manga: eu.friedcutlet.yokan.domain.Manga, chapter: eu.friedcutlet.yokan.domain.Chapter?, onRoomOpened: () -> Unit): String {
26: fun addToRoom(manga: eu.friedcutlet.yokan.domain.Manga, chapter: eu.friedcutlet.yokan.domain.Chapter?, room: RoomState, client: RoomClient): String {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherActions.kt) · SHA-256 `9a0db368601da4b9cf107a47d70a5ca2400ced468e0f318fa99c844d29e8fc51`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.together

import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.together.ProfileTogetherSession
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import eu.friedcutlet.yokan.services.together.RoomClient
import eu.friedcutlet.yokan.services.together.RoomState
import eu.friedcutlet.yokan.services.together.roomMediaFor

/** Shared by the title menu: start a room, or add/suggest the title to the current one. */
internal object TogetherActions {
    /** Creates a room for [manga] and joins it, calling [onRoomOpened] on success; returns the outcome. */
    suspend fun startRoom(together: ProfileTogetherSession, http: HttpService, manga: eu.friedcutlet.yokan.domain.Manga, chapter: eu.friedcutlet.yokan.domain.Chapter?, onRoomOpened: () -> Unit): String {
        val result = together.createAndJoin(http, roomMediaFor(manga, chapter))
            ?: return "Log in to your hub under Settings → Sync first."
        val joined = result.getOrElse { return it.message ?: "Could not create the room." }
        currentCoroutineContext().ensureActive()
        if (!together.owns(joined.client)) throw CancellationException("Together room changed before opening it.")
        val created = joined.created
        onRoomOpened()
        return "Room ${created.code} is open. Share the code or ${created.joinUrl}."
    }

    fun addToRoom(manga: eu.friedcutlet.yokan.domain.Manga, chapter: eu.friedcutlet.yokan.domain.Chapter?, room: RoomState, client: RoomClient): String {
        val media = roomMediaFor(manga, chapter)
        return when {
            room.canAddToPlaylist -> { client.playlistAdd(media); "Added to the room playlist." }
            room.canSuggest -> { client.playlistSuggest(media); "Suggested to the host." }
            else -> "Only the host changes this room's playlist."
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherHooks.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherHooks.kt) · implementation · 214 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
53: internal fun rememberRoomState(together: ProfileTogetherSession): State<RoomState?> = together.state.collectAsStateWithLifecycle(initialValue = null)
60: private fun FollowRoomMedia(
79: internal fun rememberOpenRoomMedia(owner: ProfileSession, nav: Navigator): (RoomMedia) -> Unit {
87: internal fun rememberOpenRoomMedia(
98: fun admitted() = binding.active() && client?.state?.value?.media == media
112: internal fun rememberTogetherUiBinding(
135: internal fun TogetherPlaybackSync(
167: internal fun TogetherPageSync(together: ProfileTogetherSession, state: ReaderState, onEvent: (ReaderEvent) -> Unit, onOpenRoomMedia: (RoomMedia) -> Unit) {
187: internal fun TogetherProgressSync(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherHooks.kt) · SHA-256 `563ce6ee891c6a52316a61addce6e0a1d8abf1b72628d5b7cf4407c1194ef54c`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.together

import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LocalLifecycleOwner
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.app.profiles.ProfileSession
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.services.media.player.MediaPlayerController
import eu.friedcutlet.yokan.services.notifications.InAppNotifications
import eu.friedcutlet.yokan.services.notifications.InAppMessage
import eu.friedcutlet.yokan.services.together.ProfileTogetherSession
import eu.friedcutlet.yokan.services.together.ProgressFollower
import eu.friedcutlet.yokan.services.together.RoomClient
import eu.friedcutlet.yokan.services.together.RoomMedia
import eu.friedcutlet.yokan.services.together.RoomMediaTarget
import eu.friedcutlet.yokan.services.together.RoomState
import eu.friedcutlet.yokan.services.together.announceMedia
import eu.friedcutlet.yokan.services.together.followPage
import eu.friedcutlet.yokan.services.together.followPlayback
import eu.friedcutlet.yokan.services.together.reportPage
import eu.friedcutlet.yokan.services.together.reportPlayback
import eu.friedcutlet.yokan.services.together.reportProgress
import eu.friedcutlet.yokan.services.together.roomShows
import kotlinx.coroutines.Job
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.serialization.json.contentOrNull
import kotlinx.serialization.json.intOrNull
import kotlinx.serialization.json.jsonPrimitive
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import eu.friedcutlet.yokan.ui.screens.reader.ReaderEvent
import eu.friedcutlet.yokan.ui.screens.reader.ReaderState

/**
 * Reader/player integration for read-together rooms. Each hook is one line in its screen:
 * the host side reports position, the follower side applies it (see `services.together.RoomSync`).
 * Everything is a no-op when the app is not in a room.
 */

@Composable
internal fun rememberRoomState(together: ProfileTogetherSession): State<RoomState?> = together.state.collectAsStateWithLifecycle(initialValue = null)

/**
 * Follow the room onto another title or chapter. Runs on every device that is not driving:
 * when the host switches media, open it locally if the library has it, otherwise say why not.
 */
@Composable
private fun FollowRoomMedia(
    binding: TogetherUiBinding,
    manga: Manga,
    chapter: Chapter?,
    room: RoomState?,
    following: Boolean,
    drives: Boolean,
    onOpenRoomMedia: (RoomMedia) -> Unit,
) {
    val media = room?.media
    LaunchedEffect(binding, media, following, drives) {
        if (media == null || !binding.followsMedia(room) || roomShows(media, manga, chapter)) return@LaunchedEffect
        currentCoroutineContext().ensureActive()
        onOpenRoomMedia(media)
    }
}

/** A route retains its owner and loses navigation/notification admission when disposed. */
@Composable
internal fun rememberOpenRoomMedia(owner: ProfileSession, nav: Navigator): (RoomMedia) -> Unit {
    val together = remember(owner) { owner.together }
    val repository = remember(owner) { owner.repository }
    val settings = remember(owner) { owner.settings }
    return rememberOpenRoomMedia(together, owner.id, repository, settings, nav)
}

@Composable
internal fun rememberOpenRoomMedia(
    together: ProfileTogetherSession,
    profileId: ProfileId,
    repository: YokanRepository,
    settings: SettingsStore,
    nav: Navigator,
): (RoomMedia) -> Unit {
    val client = together.client.collectAsStateWithLifecycle().value
    val binding = rememberTogetherUiBinding(together, client)
    return remember(together, profileId, repository, settings, nav, binding) {
        { media ->
            fun admitted() = binding.active() && client?.state?.value?.media == media
            val target = if (admitted()) together.resolveMedia(media, repository, settings.db.value) else null
            if (target != null && admitted()) {
                when (target) {
                    is RoomMediaTarget.Open -> nav.navigate(Route.Reader(target.mangaId, target.chapterId))
                    is RoomMediaTarget.NotInLibrary -> InAppNotifications.post(InAppMessage("Together", "The room moved to \"${target.title}\". Add it from ${target.sourceName ?: "its source"} to follow along.", profileId = profileId))
                    is RoomMediaTarget.NoChapters -> InAppNotifications.post(InAppMessage("Together", "\"${target.title}\" has no chapters loaded yet. Open it once to fetch them.", profileId = profileId))
                }
            }
        }
    }
}

@Composable
internal fun rememberTogetherUiBinding(
    together: ProfileTogetherSession,
    client: RoomClient?,
    mediaKey: Any? = null,
): TogetherUiBinding {
    val scope = rememberCoroutineScope()
    val lifecycle = LocalLifecycleOwner.current.lifecycle
    val lifecycleState by lifecycle.currentStateFlow.collectAsStateWithLifecycle(minActiveState = Lifecycle.State.CREATED)
    val started = lifecycleState.isAtLeast(Lifecycle.State.STARTED)
    val binding = remember(together, client, mediaKey, lifecycle, started) {
        TogetherUiBinding(together, client, Job(scope.coroutineContext[Job])) {
            lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)
        }
    }
    DisposableEffect(binding) { onDispose { binding.close() } }
    return binding
}

/**
 * Anime. Host: reports play/pause/speed and position. Follower: converges on the host and
 * mirrors play/pause through [onFollowPlaying].
 */
@Composable
internal fun TogetherPlaybackSync(
    together: ProfileTogetherSession,
    manga: Manga,
    chapter: Chapter,
    controller: MediaPlayerController?,
    isPlaying: Boolean,
    speed: Float,
    onOpenRoomMedia: (RoomMedia) -> Unit,
    onFollowPlaying: (Boolean) -> Unit,
) {
    val room by rememberRoomState(together)
    val following by together.following.collectAsStateWithLifecycle()
    val client = together.client.collectAsStateWithLifecycle().value
    val driving by together.driving.collectAsStateWithLifecycle()
    val drives = roomDrives(room, driving)
    val binding = rememberTogetherUiBinding(together, client, manga.link to chapter.url)
    FollowRoomMedia(binding, manga, chapter, room, following, drives, onOpenRoomMedia)

    LaunchedEffect(binding, drives, chapter.id) {
        if (client != null && binding.drives()) announceMedia(client, room, manga, chapter)
    }
    LaunchedEffect(binding, drives, controller, isPlaying, speed, driving) {
        if (client != null && controller != null) reportPlayback(client, controller, isPlaying, speed, binding::drives)
    }
    val position = room?.position
    LaunchedEffect(binding, room?.connection, room?.role, room?.media, position, controller, drives, following) {
        if (controller != null) followPlayback(position, room, manga, chapter, controller, binding::follows, onFollowPlaying)
    }
}

/** Manga. Host: page turns → room. Follower: room page → `JumpToPage`. */
@Composable
internal fun TogetherPageSync(together: ProfileTogetherSession, state: ReaderState, onEvent: (ReaderEvent) -> Unit, onOpenRoomMedia: (RoomMedia) -> Unit) {
    val room by rememberRoomState(together)
    val following by together.following.collectAsStateWithLifecycle()
    val client = together.client.collectAsStateWithLifecycle().value
    val driving by together.driving.collectAsStateWithLifecycle()
    val drives = roomDrives(room, driving)
    val binding = rememberTogetherUiBinding(together, client, state.manga.link to state.chapter.url)
    FollowRoomMedia(binding, state.manga, state.chapter, room, following, drives, onOpenRoomMedia)

    LaunchedEffect(binding, drives, state.chapter.id, state.currentPageIndex, state.pageCount) {
        if (client != null && binding.drives()) reportPage(client, room, state.manga, state.chapter, state.currentPageIndex, state.pageCount, binding::drives)
    }
    val page = room?.position?.get("page")?.jsonPrimitive?.intOrNull
    LaunchedEffect(binding, room?.connection, room?.role, room?.media, page, drives, following, state.chapter.id, state.pageCount) {
        followPage(page, room, state.manga, state.chapter, state.currentPageIndex, state.pageCount, binding::follows) { onEvent(ReaderEvent.JumpToPage(it)) }
    }
}

/** Novel. Host: scroll percentage (debounced) → room. Follower: room progress → [onFollow] ratio. */
@Composable
internal fun TogetherProgressSync(
    together: ProfileTogetherSession,
    manga: Manga,
    chapter: Chapter,
    progressPercent: Int,
    onOpenRoomMedia: (RoomMedia) -> Unit,
    onFollow: suspend (Double) -> Unit,
) {
    val room by rememberRoomState(together)
    val following by together.following.collectAsStateWithLifecycle()
    val client = together.client.collectAsStateWithLifecycle().value
    val driving by together.driving.collectAsStateWithLifecycle()
    val drives = roomDrives(room, driving)
    val binding = rememberTogetherUiBinding(together, client, manga.link to chapter.url)
    FollowRoomMedia(binding, manga, chapter, room, following, drives, onOpenRoomMedia)

    LaunchedEffect(binding, drives, chapter.id) {
        if (client != null && binding.drives()) announceMedia(client, room, manga, chapter)
    }
    LaunchedEffect(binding, drives, progressPercent) {
        if (client != null && binding.drives()) reportProgress(client, progressPercent, binding::drives)
    }
    val progress = room?.position?.get("progress")?.jsonPrimitive?.contentOrNull?.toDoubleOrNull()
    val follower = remember(binding) { ProgressFollower() }
    LaunchedEffect(binding, room?.connection, room?.role, room?.media, progress, drives, following, chapter.id) {
        follower.follow(progress, room, manga, chapter, binding::follows, onFollow)
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherScreen.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherScreen.kt) · implementation · 464 lines.
- Manual task: Implement state-driven rendering and event callbacks, loading/empty/error states, stable lazy keys, accessibility and adaptive layout; bind ViewModels only at the route boundary.

Declaration checklist (source line numbers):
```text
67: internal fun TogetherRoute(title: String, nav: Navigator) {
94: internal fun TogetherScreen(
157: private fun InfoBanner(text: String, onDismiss: () -> Unit) {
167: private fun JoinRoomPane(hubConfigured: Boolean, onJoin: (String) -> Unit) {
188: private fun WaitingPane(room: RoomState) {
198: private fun ClosedPane(text: String, onLeave: () -> Unit) {
206: private fun RoomPane(
270: private fun ChatPane(room: RoomState, client: RoomClient) {
322: private fun PlaylistPane(room: RoomState, client: RoomClient) {
357: private fun PlaylistRow(item: PlaylistItem, room: RoomState, client: RoomClient, isSuggestion: Boolean) {
398: private fun positionOf(room: RoomState, id: Long): Int = room.playlist.indexOfFirst { it.id == id }.coerceAtLeast(0)
401: private fun PeoplePane(room: RoomState, client: RoomClient) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherScreen.kt) · SHA-256 `9dd5089341950f4ed3a1eb7b5293aecf75a121250145ff8d9a464c961b143063`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.together

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.Send
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.AssistChip
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.services.together.ChatMessage
import eu.friedcutlet.yokan.services.together.PlaylistItem
import eu.friedcutlet.yokan.services.together.RoomMedia
import eu.friedcutlet.yokan.services.together.RoomClient
import eu.friedcutlet.yokan.services.together.RoomConnection
import eu.friedcutlet.yokan.services.together.RoomRole
import eu.friedcutlet.yokan.services.together.RoomState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.friedcutlet.yokan.ui.navigation.Navigator
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.*

@Composable
internal fun TogetherRoute(title: String, nav: Navigator) {
    val owner = remember { YokanRuntime.activeSession }
    val together = remember(owner) { owner.together }
    val viewModel = viewModel { TogetherViewModel(together, together::hubSession) }
    val state by viewModel.state.collectAsStateWithLifecycle()
    val sync by owner.settings.sync.collectAsStateWithLifecycle()
    val hubConfigured = remember(sync, together) { together.hubSession() != null }
    TogetherScreen(
        title = title,
        state = state,
        hubConfigured = hubConfigured,
        onBack = nav::back,
        onJoin = viewModel::join,
        onLeave = viewModel::leave,
        onFollowing = viewModel::setFollowing,
        onDriving = viewModel::setDriving,
        onDismissMessage = viewModel::dismissMessage,
        onOpenRoomMedia = rememberOpenRoomMedia(owner, nav),
    )
}

/**
 * Read / watch together. Outside a room: join by code (or from a deep link). Inside: who is here,
 * chat with reactions, and the playlist. Rooms are started from a title's overflow menu.
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun TogetherScreen(
    title: String,
    state: TogetherState,
    hubConfigured: Boolean,
    onBack: () -> Unit,
    onJoin: (String) -> Unit,
    onLeave: () -> Unit,
    onFollowing: (Boolean) -> Unit,
    onDriving: (Boolean) -> Unit,
    onDismissMessage: () -> Unit,
    onOpenRoomMedia: (RoomMedia) -> Unit,
) {
    val room = state.room
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(room?.summary?.title?.let { stringResource(Res.string.together_title_with_room, title, it) } ?: title) },
                navigationIcon = {
                    IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(Res.string.action_back)) }
                },
                actions = {
                    if (room != null) {
                        TextButton(onClick = onLeave) { Text(stringResource(Res.string.together_leave)) }
                    }
                },
            )
        },
    ) { padding ->
        val client = state.client
        Column(Modifier.padding(padding).fillMaxSize()) {
            state.message?.let { InfoBanner(it, onDismissMessage) }
            when {
                room == null || client == null -> JoinRoomPane(hubConfigured = hubConfigured, onJoin = onJoin)
                room.connection is RoomConnection.Denied -> ClosedPane(
                    stringResource(
                        when (room.connection.reason) {
                            "locked" -> Res.string.together_denied_locked
                            "full" -> Res.string.together_denied_full
                            "banned" -> Res.string.together_denied_banned
                            "timeout" -> Res.string.together_denied_timeout
                            else -> Res.string.together_denied_declined
                        },
                    ),
                    onLeave = onLeave,
                )
                room.connection is RoomConnection.Closed -> ClosedPane(
                    stringResource(
                        when (room.connection.reason) {
                            "host_left" -> Res.string.together_closed_host_left
                            "maintenance" -> Res.string.together_closed_maintenance
                            else -> Res.string.together_closed
                        },
                    ),
                    onLeave = onLeave,
                )
                room.role == RoomRole.Pending -> WaitingPane(room)
                else -> RoomPane(room, client, state.following, state.driving, onFollowing, onDriving, onOpenRoomMedia)
            }
        }
    }
}

@Composable
private fun InfoBanner(text: String, onDismiss: () -> Unit) {
    Card(Modifier.fillMaxWidth().padding(16.dp)) {
        Row(Modifier.padding(horizontal = 16.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) {
            Text(text, Modifier.weight(1f), style = MaterialTheme.typography.bodyMedium)
            IconButton(onClick = onDismiss) { Icon(Icons.Filled.Close, contentDescription = stringResource(Res.string.together_dismiss)) }
        }
    }
}

@Composable
private fun JoinRoomPane(hubConfigured: Boolean, onJoin: (String) -> Unit) {
    var code by remember { mutableStateOf("") }
    Column(Modifier.padding(24.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
        Text(stringResource(Res.string.together_join_title), style = MaterialTheme.typography.headlineSmall)
        Text(stringResource(Res.string.together_join_intro), style = MaterialTheme.typography.bodyMedium)
        if (!hubConfigured) {
            Text(stringResource(Res.string.together_no_hub), color = MaterialTheme.colorScheme.error)
        }
        OutlinedTextField(
            value = code,
            onValueChange = { code = it.uppercase().filter { c -> c.isLetterOrDigit() }.take(6) },
            label = { Text(stringResource(Res.string.together_room_code)) },
            singleLine = true,
            keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Characters),
            modifier = Modifier.fillMaxWidth(),
        )
        Button(enabled = code.length == 6 && hubConfigured, onClick = { onJoin(code) }) { Text(stringResource(Res.string.together_join_room)) }
    }
}

@Composable
private fun WaitingPane(room: RoomState) {
    Column(Modifier.padding(24.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
        Text(stringResource(Res.string.together_waiting_title), style = MaterialTheme.typography.headlineSmall)
        val host = room.summary?.host?.email ?: stringResource(Res.string.together_waiting_host)
        val roomLabel = room.summary?.title?.let { stringResource(Res.string.together_title_with_room, room.code, it) } ?: room.code
        Text(stringResource(Res.string.together_waiting_body, host, roomLabel))
    }
}

@Composable
private fun ClosedPane(text: String, onLeave: () -> Unit) {
    Column(Modifier.padding(24.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
        Text(text, style = MaterialTheme.typography.titleMedium)
        OutlinedButton(onClick = onLeave) { Text(stringResource(Res.string.together_back_to_join)) }
    }
}

@Composable
private fun RoomPane(
    room: RoomState,
    client: RoomClient,
    following: Boolean,
    driving: Boolean,
    onFollowing: (Boolean) -> Unit,
    onDriving: (Boolean) -> Unit,
    onOpenRoomMedia: (RoomMedia) -> Unit,
) {
    var tab by remember { mutableIntStateOf(0) }

    Column(Modifier.fillMaxSize()) {
        // Header: what is playing, who drives, follow switch.
        Column(Modifier.padding(horizontal = 16.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
            Text(room.media?.title ?: stringResource(Res.string.together_nothing_playing), style = MaterialTheme.typography.titleMedium)
            Text(
                listOfNotNull(
                    room.media?.chapter?.name,
                    stringResource(Res.string.together_code, room.code),
                    stringResource(Res.string.together_here_count, room.participants.size),
                    if (room.hostAway) stringResource(Res.string.together_host_reconnecting) else null,
                ).joinToString(" · "),
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
            )
            Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                if (!room.isHost) {
                    Switch(checked = following, onCheckedChange = onFollowing)
                    Text(stringResource(if (following) Res.string.together_following_host else Res.string.together_browsing_alone), style = MaterialTheme.typography.bodyMedium)
                }
                if (room.role == RoomRole.CoHost) {
                    FilterChip(selected = driving, onClick = { onDriving(!driving) }, label = { Text(stringResource(if (driving) Res.string.together_driving else Res.string.together_take_control)) })
                }
                Spacer(Modifier.weight(1f))
                room.media?.let { media ->
                    if (!room.isHost) TextButton(onClick = { onOpenRoomMedia(media) }) { Text(stringResource(Res.string.action_open)) }
                }
            }
            // Quick reactions float over the player/reader on every device.
            Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
                RoomClient.QUICK_REACTIONS.forEach { e -> TextButton(onClick = { client.burst(e) }) { Text(e) } }
            }
        }
        androidx.compose.material3.SecondaryTabRow(selectedTabIndex = tab) {
            val chat = stringResource(Res.string.together_tab_chat)
            val playlist = stringResource(Res.string.together_tab_playlist)
            val people = stringResource(Res.string.together_tab_people)
            Tab(selected = tab == 0, onClick = { tab = 0 }, text = { Text(chat) })
            Tab(selected = tab == 1, onClick = { tab = 1 }, text = {
                Text(if (room.suggestions.isNotEmpty() && room.controls) stringResource(Res.string.together_tab_count, playlist, room.suggestions.size) else playlist)
            })
            Tab(selected = tab == 2, onClick = { tab = 2 }, text = {
                Text(if (room.pendingJoins.isNotEmpty() && room.controls) stringResource(Res.string.together_tab_count, people, room.pendingJoins.size) else people)
            })
        }
        when (tab) {
            0 -> ChatPane(room, client)
            1 -> PlaylistPane(room, client)
            else -> PeoplePane(room, client)
        }
    }
}

@Composable
private fun ChatPane(room: RoomState, client: RoomClient) {
    var text by remember { mutableStateOf("") }
    var replyTo by remember { mutableStateOf<ChatMessage?>(null) }
    val listState = rememberLazyListState()
    LaunchedEffect(room.chat.size) { if (room.chat.isNotEmpty()) listState.animateScrollToItem(room.chat.lastIndex) }
    Column(Modifier.fillMaxSize()) {
        LazyColumn(Modifier.weight(1f).fillMaxWidth(), state = listState, contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 12.dp, vertical = 8.dp)) {
            items(room.chat, key = { it.id }) { m ->
                val name = if (m.from.id == room.youId) stringResource(Res.string.together_chat_you) else m.from.email.substringBefore('@')
                val replied = m.replyTo?.let { id -> room.chat.firstOrNull { it.id == id } }
                Column(Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
                    Text(
                        replied?.let { stringResource(Res.string.together_chat_reply_to, name, it.text.take(30)) } ?: name,
                        style = MaterialTheme.typography.labelSmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                    )
                    Text(m.text, style = MaterialTheme.typography.bodyMedium)
                    Row(horizontalArrangement = Arrangement.spacedBy(4.dp), verticalAlignment = Alignment.CenterVertically) {
                        m.reactions.forEach { (emoji, users) ->
                            FilterChip(selected = room.youId in users, onClick = { client.react(m.id, emoji) }, label = { Text("$emoji ${users.size}") })
                        }
                        TextButton(onClick = { client.react(m.id, "❤️") }) { Text("❤️") }
                        TextButton(onClick = { replyTo = m }) { Text(stringResource(Res.string.together_reply)) }
                    }
                }
            }
        }
        replyTo?.let { r ->
            Row(Modifier.padding(horizontal = 12.dp), verticalAlignment = Alignment.CenterVertically) {
                Text(stringResource(Res.string.together_replying_to, r.from.email.substringBefore('@'), r.text.take(40)), Modifier.weight(1f), style = MaterialTheme.typography.labelSmall)
                IconButton(onClick = { replyTo = null }) { Icon(Icons.Filled.Close, contentDescription = stringResource(Res.string.together_cancel_reply)) }
            }
        }
        Row(Modifier.padding(horizontal = 12.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) {
            OutlinedTextField(
                value = text,
                onValueChange = { text = it.take(500) },
                placeholder = { Text(stringResource(Res.string.together_message_placeholder)) },
                modifier = Modifier.weight(1f),
                maxLines = 3,
            )
            Spacer(Modifier.width(8.dp))
            IconButton(enabled = text.isNotBlank(), onClick = {
                client.chat(text.trim(), replyTo?.id)
                text = ""
                replyTo = null
            }) { Icon(Icons.AutoMirrored.Filled.Send, contentDescription = stringResource(Res.string.send)) }
        }
    }
}

@Composable
private fun PlaylistPane(room: RoomState, client: RoomClient) {
    LazyColumn(Modifier.fillMaxSize(), contentPadding = androidx.compose.foundation.layout.PaddingValues(vertical = 8.dp)) {
        item {
            Column(Modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                Text(
                    stringResource(
                        when {
                            room.controls -> Res.string.together_playlist_hint_controls
                            room.canAddToPlaylist -> Res.string.together_playlist_hint_anyone
                            room.canSuggest -> Res.string.together_playlist_hint_suggest
                            else -> Res.string.together_playlist_hint_host_only
                        },
                    ),
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )
                if (room.controls && room.upNext != null) {
                    Button(onClick = { client.playlistNext() }) { Text(stringResource(Res.string.together_play_next, room.upNext?.media?.title.orEmpty())) }
                }
            }
        }
        if (room.suggestions.isNotEmpty()) {
            item { Text(stringResource(Res.string.together_suggestions), Modifier.padding(16.dp, 12.dp, 16.dp, 4.dp), style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary) }
            items(room.suggestions, key = { it.id }) { item ->
                PlaylistRow(item, room, client, isSuggestion = true)
            }
        }
        item { Text(stringResource(Res.string.together_queue), Modifier.padding(16.dp, 12.dp, 16.dp, 4.dp), style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary) }
        val queue = room.playlist.filter { it.status != "suggested" }
        if (queue.isEmpty()) item { Text(stringResource(Res.string.together_queue_empty), Modifier.padding(horizontal = 16.dp), style = MaterialTheme.typography.bodySmall) }
        items(queue, key = { it.id }) { item -> PlaylistRow(item, room, client, isSuggestion = false) }
    }
}

@Composable
private fun PlaylistRow(item: PlaylistItem, room: RoomState, client: RoomClient, isSuggestion: Boolean) {
    val queued = room.playlist.filter { it.status == "queued" }
    val index = queued.indexOfFirst { it.id == item.id }
    ListItem(
        headlineContent = { Text(item.media.title ?: item.media.link) },
        supportingContent = {
            Text(
                listOfNotNull(
                    item.media.chapter?.name,
                    item.media.sourceName,
                    if (isSuggestion) stringResource(Res.string.together_suggested_by, item.addedBy.email.substringBefore('@')) else null,
                    item.note?.let { stringResource(Res.string.together_note, it) },
                    when (item.status) {
                        "playing" -> stringResource(Res.string.together_status_playing)
                        "done" -> stringResource(Res.string.together_status_done)
                        else -> null
                    },
                ).joinToString(" · "),
            )
        },
        trailingContent = {
            Row {
                if (isSuggestion) {
                    if (room.controls) {
                        IconButton(onClick = { client.playlistAccept(item.id) }) { Icon(Icons.Filled.Check, contentDescription = stringResource(Res.string.together_accept)) }
                        IconButton(onClick = { client.playlistReject(item.id) }) { Icon(Icons.Filled.Close, contentDescription = stringResource(Res.string.together_reject)) }
                    } else if (item.addedBy.id == room.youId) {
                        IconButton(onClick = { client.playlistRemove(item.id) }) { Icon(Icons.Filled.Close, contentDescription = stringResource(Res.string.together_withdraw)) }
                    }
                } else if (room.controls && item.status == "queued") {
                    IconButton(enabled = index > 0, onClick = { client.playlistMove(item.id, positionOf(room, queued[index - 1].id)) }) { Icon(Icons.Filled.KeyboardArrowUp, contentDescription = stringResource(Res.string.together_move_up)) }
                    IconButton(enabled = index in 0 until queued.lastIndex, onClick = { client.playlistMove(item.id, positionOf(room, queued[index + 1].id)) }) { Icon(Icons.Filled.KeyboardArrowDown, contentDescription = stringResource(Res.string.together_move_down)) }
                    IconButton(onClick = { client.playlistPlay(item.id) }) { Icon(Icons.Filled.PlayArrow, contentDescription = stringResource(Res.string.together_play_now)) }
                    IconButton(onClick = { client.playlistRemove(item.id) }) { Icon(Icons.Filled.Close, contentDescription = stringResource(Res.string.action_remove)) }
                }
            }
        },
    )
}

/** Absolute index of an item in the hub's playlist vector (what `pl_move` expects). */
private fun positionOf(room: RoomState, id: Long): Int = room.playlist.indexOfFirst { it.id == id }.coerceAtLeast(0)

@Composable
private fun PeoplePane(room: RoomState, client: RoomClient) {
    LazyColumn(Modifier.fillMaxSize(), contentPadding = androidx.compose.foundation.layout.PaddingValues(vertical = 8.dp)) {
        if (room.controls) {
            item {
                Row(Modifier.padding(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                    listOf(
                        "open" to Res.string.together_policy_open,
                        "approve" to Res.string.together_policy_approve,
                        "locked" to Res.string.together_policy_locked,
                    ).forEach { (value, label) ->
                        FilterChip(selected = room.policy == value, enabled = room.isHost, onClick = { client.setPolicy(policy = value) }, label = { Text(stringResource(label)) })
                    }
                }
                Row(Modifier.padding(16.dp, 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                    listOf(
                        "host_only" to Res.string.together_playlist_host_only,
                        "suggest" to Res.string.together_playlist_suggest,
                        "anyone" to Res.string.together_playlist_anyone,
                    ).forEach { (value, label) ->
                        FilterChip(selected = room.playlistPolicy == value, enabled = room.isHost, onClick = { client.setPolicy(playlistPolicy = value) }, label = { Text(stringResource(label)) })
                    }
                }
            }
        }
        if (room.pendingJoins.isNotEmpty() && room.controls) {
            item { Text(stringResource(Res.string.together_waiting_to_join), Modifier.padding(16.dp, 12.dp, 16.dp, 4.dp), style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary) }
            items(room.pendingJoins, key = { it.id }) { u ->
                ListItem(
                    headlineContent = { Text(u.email) },
                    trailingContent = {
                        Row {
                            IconButton(onClick = { client.approve(u.id) }) { Icon(Icons.Filled.Check, contentDescription = stringResource(Res.string.together_approve)) }
                            IconButton(onClick = { client.deny(u.id) }) { Icon(Icons.Filled.Close, contentDescription = stringResource(Res.string.together_deny)) }
                        }
                    },
                )
            }
        }
        item { Text(stringResource(Res.string.together_in_room), Modifier.padding(16.dp, 12.dp, 16.dp, 4.dp), style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.primary) }
        items(room.participants, key = { it.id }) { p ->
            ListItem(
                headlineContent = { Text(if (p.id == room.youId) stringResource(Res.string.together_participant_you, p.email) else p.email) },
                supportingContent = {
                    Text(listOfNotNull(p.role.replace('_', ' '), if (p.detached) stringResource(Res.string.together_browsing_own) else null).joinToString(" · "))
                },
                trailingContent = {
                    if (room.controls && p.id != room.youId && p.role != "host") {
                        Row {
                            if (room.isHost) {
                                AssistChip(
                                    onClick = { if (p.role == "co_host") client.demote(p.id) else client.promote(p.id) },
                                    label = { Text(stringResource(if (p.role == "co_host") Res.string.together_demote else Res.string.together_co_host)) },
                                )
                                Spacer(Modifier.width(4.dp))
                            }
                            AssistChip(onClick = { client.kick(p.id) }, label = { Text(stringResource(Res.string.together_kick)) })
                        }
                    }
                },
            )
        }
        item { Spacer(Modifier.height(24.dp)) }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherSession.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherSession.kt) · implementation · 22 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
10: object TogetherSession {
16: fun offerCode(code: String) {
21: fun takePendingCode(): String? = _pendingCode.getAndUpdate { null }
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherSession.kt) · SHA-256 `01c15de2fd08e32ba70b20fb4b7e696d4ab1dfeea9a4e8f5c6da9b09ba587d45`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.together

import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.getAndUpdate
import kotlinx.coroutines.flow.update

/** Room code handed in by a deep link; the Together screen's view model joins it. */
object TogetherSession {
    private val _pendingCode = MutableStateFlow<String?>(null)

    /** Room code handed in by a deep link, consumed by the Together screen. */
    val pendingCode: StateFlow<String?> = _pendingCode.asStateFlow()

    fun offerCode(code: String) {
        _pendingCode.update { code }
    }

    /** Returns the deep-linked room code once, clearing it. */
    fun takePendingCode(): String? = _pendingCode.getAndUpdate { null }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherUiBinding.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherUiBinding.kt) · implementation · 37 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
10: internal fun roomDrives(room: RoomState?, driving: Boolean): Boolean =
15: internal class TogetherUiBinding(
21: fun active(): Boolean = job.isActive && isUiActive() && client != null && together.owns(client)
23: fun current(room: RoomState?): Boolean = active() && room != null && client?.state?.value == room
25: fun drives(): Boolean = active() && roomDrives(client?.state?.value, together.driving.value)
27: fun followsMedia(room: RoomState?): Boolean = active() && room != null &&
33: fun follows(room: RoomState?): Boolean = followsMedia(room) &&
36: fun close() { job.cancel() }
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherUiBinding.kt) · SHA-256 `6b185d41c24649060a0829c28cd287d78fb1a44cdd3a5b7aba32100d8f822c5d`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.together

import eu.friedcutlet.yokan.services.together.ProfileTogetherSession
import eu.friedcutlet.yokan.services.together.RoomClient
import eu.friedcutlet.yokan.services.together.RoomConnection
import eu.friedcutlet.yokan.services.together.RoomRole
import eu.friedcutlet.yokan.services.together.RoomState
import kotlinx.coroutines.Job

internal fun roomDrives(room: RoomState?, driving: Boolean): Boolean =
    room?.connection == RoomConnection.Open &&
        (room.role == RoomRole.Host || (room.role == RoomRole.CoHost && driving))

/** Captured room capability. Old clients, disposed screens and stale room snapshots fail closed. */
internal class TogetherUiBinding(
    private val together: ProfileTogetherSession,
    private val client: RoomClient?,
    private val job: Job,
    private val isUiActive: () -> Boolean = { true },
) {
    fun active(): Boolean = job.isActive && isUiActive() && client != null && together.owns(client)

    fun current(room: RoomState?): Boolean = active() && room != null && client?.state?.value == room

    fun drives(): Boolean = active() && roomDrives(client?.state?.value, together.driving.value)

    fun followsMedia(room: RoomState?): Boolean = active() && room != null &&
        client?.state?.value?.let { current ->
            current.connection == RoomConnection.Open && current.media == room.media &&
                together.following.value && !roomDrives(current, together.driving.value)
        } == true

    fun follows(room: RoomState?): Boolean = followsMedia(room) &&
        client?.state?.value?.position == room?.position

    fun close() { job.cancel() }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherViewModel.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherViewModel.kt) · implementation · 108 lines.
- Manual task: Define immutable UI state and commands, inject the captured owner/repository/services, expose StateFlow and use atomic updates; preserve request cancellation, late-result guards and awaited teardown.

Declaration checklist (source line numbers):
```text
30: internal data class TogetherState(
44: internal class TogetherViewModel(
69: fun join(code: String) {
81: fun leave() {
89: fun setFollowing(following: Boolean) {
96: fun setDriving(driving: Boolean) {
101: fun dismissMessage() {
105: private fun showMessage(message: String) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherViewModel.kt) · SHA-256 `a83b5aa42be32f5207ea8b06511939746994971a0b06b1184a5ada011289f1bf`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.ui.screens.together

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.together.HubSession
import eu.friedcutlet.yokan.services.together.ProfileTogetherSession
import eu.friedcutlet.yokan.services.together.RoomClient
import eu.friedcutlet.yokan.services.together.RoomState
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jetbrains.compose.resources.getString
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.together_join_failed
import yokan.composeapp.generated.resources.together_leave_failed
import yokan.composeapp.generated.resources.together_login_to_join

internal data class TogetherState(
    val room: RoomState? = null,
    /** The client [room] belongs to; room commands go to it. */
    val client: RoomClient? = null,
    val following: Boolean = true,
    val driving: Boolean = false,
    val message: String? = null,
)

/**
 * Join/leave and follow/drive for the Together screen. Calls run in [viewModelScope], so a join in
 * flight completes after the screen is covered. Room errors surface as [TogetherState.message].
 */
@OptIn(ExperimentalCoroutinesApi::class)
internal class TogetherViewModel(
    private val together: ProfileTogetherSession,
    private val hubSession: () -> HubSession?,
    private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {
    private val _state = MutableStateFlow(TogetherState())
    val state: StateFlow<TogetherState> = _state.asStateFlow()

    init {
        viewModelScope.launch {
            val rooms = together.client.flatMapLatest { client -> client?.state?.map { client to it } ?: flowOf(null) }
            combine(rooms, together.following, together.driving, ::Triple).collect { (current, following, driving) ->
                val room = current?.second
                _state.update {
                    val error = room?.lastError?.takeIf { error -> error != it.room?.lastError }
                    it.copy(room = room, client = current?.first, following = following, driving = driving, message = error ?: it.message)
                }
            }
        }
        // Deep link: join as soon as a code is handed in.
        viewModelScope.launch {
            TogetherSession.pendingCode.filterNotNull().collect { TogetherSession.takePendingCode()?.let(::join) }
        }
    }

    fun join(code: String) {
        viewModelScope.launch {
            val hub = hubSession()
            if (hub == null) {
                showMessage(getString(Res.string.together_login_to_join))
                return@launch
            }
            catchingNonCancellation { withContext(workDispatcher) { together.join(hub, code) } }
                .onFailure { error -> showMessage(error.message ?: getString(Res.string.together_join_failed)) }
        }
    }

    fun leave() {
        val client = together.client.value ?: return
        viewModelScope.launch {
            catchingNonCancellation { withContext(workDispatcher) { together.leave(client) } }
                .onFailure { error -> showMessage(error.message ?: getString(Res.string.together_leave_failed)) }
        }
    }

    fun setFollowing(following: Boolean) {
        val client = together.client.value ?: return
        if (!together.owns(client)) return
        together.setFollowing(following)
        client.presence(detached = !following)
    }

    fun setDriving(driving: Boolean) {
        val client = together.client.value ?: return
        if (together.owns(client)) together.setDriving(driving)
    }

    fun dismissMessage() {
        _state.update { it.copy(message = null) }
    }

    private fun showMessage(message: String) {
        _state.update { it.copy(message = message) }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/ProfileTogetherSessionTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/ProfileTogetherSessionTest.kt) · test / fixture · 154 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
34: class ProfileTogetherSessionTest {
149: private fun database() = InMemoryYokanDatabase(emptySnapshot()).also { it.upsertSyncPreference(Preference) }
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/ProfileTogetherSessionTest.kt) · SHA-256 `89b67660c354dd481f2613f67de2847dc88d412fa6875059e462707e17cd17a0`.

### Complete file

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)

package eu.friedcutlet.yokan.services.together

import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.SyncServerProvider
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.services.http.ProfileTestEngine
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue

class ProfileTogetherSessionTest {
    @Test fun connectionUsesCapturedCredentialsAndLeavePreservesOwner() = runTest {
        val parent = SupervisorJob()
        val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() }
        val together = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine }
        val client = assertNotNull(together.join(Hub, "abc"))
        val request = engine.requests.receive()
        assertEquals("Bearer owner-token", request.headers["Authorization"])
        assertEquals("owner-device", request.headers["X-Device"])
        assertTrue(request.url.toString().endsWith("/rooms/ABC/ws"))
        assertEquals("ABC", client.code)
        together.leave(); assertNull(together.client.value); assertEquals(1, engine.closeCalls)
        assertTrue(parent.isActive)
        client.connect(); testScheduler.runCurrent(); assertTrue(engine.requests.tryReceive().isFailure)
        together.closeAndJoin(); parent.cancelAndJoin()
    }

    @Test fun replacementJoinsOldSocketBeforeAllocatingOrPublishingAnother() = runTest {
        val parent = SupervisorJob(); val release = CompletableDeferred<Unit>()
        val first = ProfileTestEngine(StandardTestDispatcher(testScheduler)) {
            try { awaitCancellation() } finally { withContext(NonCancellable) { release.await() } }
        }
        val second = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() }
        var allocations = 0
        val together = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) {
            allocations++; if (allocations == 1) first else second
        }
        together.join(Hub, "OLD"); first.requests.receive()
        val replacing = launch { together.join(Hub, "NEW") }
        testScheduler.runCurrent()
        assertFalse(replacing.isCompleted); assertEquals(1, allocations); assertEquals(0, first.closeCalls)
        assertNull(together.client.value)
        release.complete(Unit); replacing.join()
        assertEquals(1, first.closeCalls); assertEquals("NEW", together.client.value?.code)
        together.closeAndJoin(); parent.cancelAndJoin(); assertEquals(1, second.closeCalls)
    }

    @Test fun retirementJoinsSocketFinalizerThenReleasesTransportAndState() = runTest {
        val parent = SupervisorJob(); val release = CompletableDeferred<Unit>(); var finalized = false
        val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) {
            try { awaitCancellation() } finally { withContext(NonCancellable) { release.await(); finalized = true } }
        }
        val together = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine }
        together.join(Hub, "ABC"); engine.requests.receive(); together.setDriving(true)
        val retiring = launch { parent.cancelAndJoin(); together.closeAndJoin() }
        testScheduler.runCurrent(); assertFalse(retiring.isCompleted); assertEquals(0, engine.closeCalls)
        assertNull(together.hubSession())
        release.complete(Unit); retiring.join()
        assertTrue(finalized); assertNull(together.client.value); assertFalse(together.driving.value)
        assertEquals(1, engine.closeCalls); together.closeAndJoin(); assertEquals(1, engine.closeCalls)
    }

    @Test fun staleAccountOrOtherSyncProviderCannotAllocateARoomTransport() = runTest {
        val parent = SupervisorJob(); val db = database(); var allocations = 0
        val together = ProfileTogetherSession(ProfileId.Default, db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) {
            allocations++; error("Stale credential transport")
        }
        db.upsertSyncPreference(Preference.copy(authToken = "replacement"))
        assertNull(together.join(Hub, "ABC"))
        db.upsertSyncPreference(Preference.copy(serverProvider = SyncServerProvider.Mangayomi))
        assertNull(together.hubSession()); assertNull(together.join(Hub, "ABC")); assertEquals(0, allocations)
        together.closeAndJoin(); parent.cancelAndJoin()
    }

    @Test fun expiredAndRetiredCallsCannotReadCredentialsOrDispatch() = runTest {
        val parent = SupervisorJob(); var allocations = 0
        val together = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + UnconfinedTestDispatcher(testScheduler))) {
            allocations++; error("Expired transport")
        }
        val caller = launch {
            currentCoroutineContext().cancel()
            assertFailsWith<CancellationException> { together.join(Hub, "ABC") }
        }
        caller.join(); assertEquals(0, allocations); assertTrue(parent.isActive)
        parent.cancelAndJoin(); together.closeAndJoin()
        assertNull(together.hubSession())
        assertFailsWith<CancellationException> { together.join(Hub, "ABC") }
        together.setDriving(true); together.setFollowing(false)
        assertFalse(together.driving.value); assertTrue(together.following.value)
    }

    @Test fun callerExpiryDuringReplacementJoinsCleanupAndDoesNotRetireOwner() = runTest {
        val parent = SupervisorJob(); val release = CompletableDeferred<Unit>(); var allocations = 0
        val first = ProfileTestEngine(StandardTestDispatcher(testScheduler)) {
            try { awaitCancellation() } finally { withContext(NonCancellable) { release.await() } }
        }
        val second = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() }
        val together = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) {
            allocations++; if (allocations == 1) first else second
        }
        together.join(Hub, "OLD"); first.requests.receive()
        val caller = launch { together.join(Hub, "ABANDONED") }
        testScheduler.runCurrent(); caller.cancel(); testScheduler.runCurrent()
        assertFalse(caller.isCompleted); assertTrue(parent.isActive); assertEquals(1, allocations)
        release.complete(Unit); caller.join(); assertNull(together.client.value)
        assertNotNull(together.join(Hub, "RETRY")); assertEquals(2, allocations)
        together.closeAndJoin(); parent.cancelAndJoin()
    }

    @Test fun independentOwnersRetainTheirRoomStateAndCleanupTargets() = runTest {
        val a = SupervisorJob(); val b = SupervisorJob()
        val engineA = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() }
        val engineB = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() }
        val idA = ProfileId("p_11111111111111111111111111111111")
        val idB = ProfileId("p_22222222222222222222222222222222")
        val first = ProfileTogetherSession(idA, database(), CoroutineScope(a + StandardTestDispatcher(testScheduler))) { assertEquals(idA, it); engineA }
        val second = ProfileTogetherSession(idB, database(), CoroutineScope(b + StandardTestDispatcher(testScheduler))) { assertEquals(idB, it); engineB }
        first.join(Hub, "AAA"); val currentB = second.join(Hub, "BBB")
        first.setFollowing(false); second.setDriving(true)
        a.cancelAndJoin(); first.closeAndJoin()
        assertSame(currentB, second.client.value); assertTrue(second.driving.value); assertTrue(second.following.value)
        assertEquals(1, engineA.closeCalls); assertEquals(0, engineB.closeCalls); assertTrue(b.isActive)
        second.closeAndJoin(); b.cancelAndJoin()
    }

    private fun database() = InMemoryYokanDatabase(emptySnapshot()).also { it.upsertSyncPreference(Preference) }
    private companion object {
        val Preference = DbSyncPreference(syncId = 1, server = "https://hub.test", authToken = "owner-token", deviceId = "owner-device")
        val Hub = HubSession("https://hub.test", "owner-token", "owner-device")
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/RoomApiTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/RoomApiTest.kt) · test / fixture · 64 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
13: class RoomApiTest {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/RoomApiTest.kt) · SHA-256 `49612177d3a77022e7b8ef1efaff7790d39afa237e9004a3b5caf2a412c01e9d`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.together

import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.HttpService
import eu.friedcutlet.yokan.services.http.RecordingHttpService
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue

class RoomApiTest {
    @Test fun allRestMethodsRejectRevokedAccountsBeforeDispatch() = runTest {
        var calls = 0
        val http = HttpService { calls++; error("Revoked REST dispatch") }
        val api = RoomApi(http) { false }
        assertFailsWith<CancellationException> { api.create(Hub, Media) }
        assertFailsWith<CancellationException> { api.info(Hub, "abcdef") }
        assertFailsWith<CancellationException> { api.close(Hub, "abcdef") }
        assertEquals(0, calls)
    }

    @Test fun allRestMethodsRejectResponsesAfterRevocationBeforeParsingOrReportingErrors() = runTest {
        for (method in listOf("POST", "GET", "DELETE")) {
            var current = true
            val http = HttpService { request ->
                assertEquals(method, request.method); current = false
                HttpResponse(401, "invalid response")
            }
            val api = RoomApi(http) { current }
            assertFailsWith<CancellationException> {
                when (method) {
                    "POST" -> api.create(Hub, Media)
                    "GET" -> api.info(Hub, "abcdef")
                    else -> api.close(Hub, "abcdef")
                }
            }
        }
    }

    @Test fun standaloneRestCompatibilityRetainsPolicyHeadersCodesAndErrors() = runTest {
        val http = RecordingHttpService { request ->
            when (request.method) {
                "POST" -> HttpResponse(201, "{\"code\":\"ABCDEF\",\"join_url\":\"join\"}")
                "GET" -> HttpResponse(404, "{}")
                else -> HttpResponse(204)
            }
        }
        val api = RoomApi(http)
        assertEquals("ABCDEF", api.create(Hub, Media, policy = "open", playlistPolicy = "all", maxParticipants = 8).getOrThrow().code)
        assertEquals("No room with code ABCDEF.", api.info(Hub, "abcdef").exceptionOrNull()?.message)
        assertTrue(api.close(Hub, "abcdef").isSuccess)
        assertEquals(listOf("POST", "GET", "DELETE"), http.requests.map { it.method })
        http.requests.forEach { assertEquals("Bearer token", it.headers["Authorization"]); assertEquals("device", it.headers["X-Device"]) }
        assertTrue(requireNotNull(http.requests.first().body).contains("\"max_participants\":8"))
        assertTrue(http.requests.last().url.endsWith("/rooms/ABCDEF"))
    }

    private companion object {
        val Hub = HubSession("https://hub.test", "token", "device")
        val Media = RoomMedia("manga", 1, "/title")
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/RoomReducerTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/RoomReducerTest.kt) · test / fixture · 122 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
13: class RoomReducerTest {
14: private fun RoomState.apply(json: String): RoomState = RoomReducer.reduce(this, RoomJson.parseToJsonElement(json).jsonObject)
23: fun helloSeedsRoleMediaAndPolicies() {
35: fun joinFlowMovesUsersFromPendingToParticipants() {
49: fun pendingJoinerBecomesParticipantOnApproved() {
60: fun deniedAndClosedAreTerminal() {
67: fun playlistSnapshotAndMediaSwitch() {
86: fun chatHistoryLiveMessagesAndReactionToggle() {
100: fun hostAwayAndPolicyChanges() {
114: fun expectedPositionExtrapolatesWhilePlaying() {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/RoomReducerTest.kt) · SHA-256 `d487746d3a435c7dd4d414206a1b7ca2e5063a01bf0525db423651f96257bca5`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.together

import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlinx.serialization.json.long
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertIs
import kotlin.test.assertNull
import kotlin.test.assertTrue

class RoomReducerTest {
    private fun RoomState.apply(json: String): RoomState = RoomReducer.reduce(this, RoomJson.parseToJsonElement(json).jsonObject)

    private val hello = """{"type":"hello","room":{"code":"ABC123","host":{"id":"h","email":"h@x"},"title":"One",
        "media":{"itemType":"anime","sourceId":42,"link":"/a/one","title":"One","chapter":{"url":"/a/one/1","name":"Ep 1"}},
        "policy":"approve","playlist_policy":"suggest","participants":1,"pending":0,"max_participants":20,"playlist_len":1},
        "you":{"id":"h","email":"h@x","role":"host"},
        "participants":[{"id":"h","email":"h@x","role":"host","detached":false}]}"""

    @Test
    fun helloSeedsRoleMediaAndPolicies() {
        val s = RoomState("ABC123").apply(hello)
        assertEquals(RoomConnection.Open, s.connection)
        assertEquals(RoomRole.Host, s.role)
        assertTrue(s.controls)
        assertEquals("One", s.media?.title)
        assertEquals("/a/one/1", s.media?.chapter?.url)
        assertEquals("approve", s.policy)
        assertEquals(1, s.participants.size)
    }

    @Test
    fun joinFlowMovesUsersFromPendingToParticipants() {
        var s = RoomState("ABC123").apply(hello)
        s = s.apply("""{"type":"join_request","user":{"id":"a","email":"a@x"}}""")
        assertEquals(listOf("a"), s.pendingJoins.map { it.id })
        s = s.apply("""{"type":"participant_joined","user":{"id":"a","email":"a@x"},"role":"participant"}""")
        assertTrue(s.pendingJoins.isEmpty())
        assertEquals(setOf("h", "a"), s.participants.map { it.id }.toSet())
        s = s.apply("""{"type":"role","user":"a","role":"co_host"}""")
        assertEquals("co_host", s.participants.single { it.id == "a" }.role)
        s = s.apply("""{"type":"participant_left","user":"a"}""")
        assertEquals(listOf("h"), s.participants.map { it.id })
    }

    @Test
    fun pendingJoinerBecomesParticipantOnApproved() {
        var s = RoomState("ABC123").apply(hello.replace("\"role\":\"host\"}", "\"role\":\"pending\"}"))
        assertEquals(RoomRole.Pending, s.role)
        s = s.apply("""{"type":"approved"}""")
        assertEquals(RoomRole.Participant, s.role)
        assertFalse(s.controls)
        assertTrue(s.canSuggest)
        assertFalse(s.canAddToPlaylist)
    }

    @Test
    fun deniedAndClosedAreTerminal() {
        assertIs<RoomConnection.Denied>(RoomState("X").apply("""{"type":"denied","reason":"locked"}""").connection)
        val closed = RoomState("X").apply("""{"type":"closed","reason":"host_left"}""").connection
        assertEquals("host_left", assertIs<RoomConnection.Closed>(closed).reason)
    }

    @Test
    fun playlistSnapshotAndMediaSwitch() {
        var s = RoomState("ABC123").apply(hello)
        s = s.apply(
            """{"type":"playlist","playing":1,"items":[
                 {"id":1,"media":{"itemType":"anime","sourceId":42,"link":"/a/one","title":"One"},"added_by":{"id":"h","email":"h@x"},"status":"playing"},
                 {"id":2,"media":{"itemType":"anime","sourceId":42,"link":"/a/two","title":"Two"},"added_by":{"id":"a","email":"a@x"},"note":"pls","status":"suggested"},
                 {"id":3,"media":{"itemType":"anime","sourceId":42,"link":"/a/three","title":"Three"},"added_by":{"id":"h","email":"h@x"},"status":"queued"}]}""",
        )
        assertEquals(1L, s.playing)
        assertEquals("Three", s.upNext?.media?.title)
        assertEquals(listOf(2L), s.suggestions.map { it.id })
        s = s.apply("""{"type":"state","positionMs":5000,"playing":true,"rate":1.0,"server_ms":1000}""")
        assertEquals(5000L, s.position!!["positionMs"]!!.jsonPrimitive.long)
        s = s.apply("""{"type":"media","media":{"itemType":"anime","sourceId":42,"link":"/a/three","title":"Three"},"server_ms":2000}""")
        assertEquals("Three", s.media?.title)
        assertNull(s.position, "a media switch resets the position until the host sends one")
    }

    @Test
    fun chatHistoryLiveMessagesAndReactionToggle() {
        var s = RoomState("ABC123").apply(hello)
        s = s.apply("""{"type":"chat_history","messages":[{"id":1,"from":{"id":"a","email":"a@x"},"text":"hi","at":10,"reactions":{"❤️":["h"]}}]}""")
        assertEquals(listOf("h"), s.chat.single().reactions["❤️"])
        s = s.apply("""{"type":"chat","id":2,"from":{"id":"h","email":"h@x"},"text":"yo 👋","reply_to":1,"at":11,"reactions":{}}""")
        assertEquals(2, s.chat.size)
        assertEquals(1L, s.chat[1].replyTo)
        s = s.apply("""{"type":"reaction","msg_id":2,"emoji":"🔥","user":"a","on":true}""")
        assertEquals(listOf("a"), s.chat[1].reactions["🔥"])
        s = s.apply("""{"type":"reaction","msg_id":2,"emoji":"🔥","user":"a","on":false}""")
        assertNull(s.chat[1].reactions["🔥"])
    }

    @Test
    fun hostAwayAndPolicyChanges() {
        var s = RoomState("ABC123").apply(hello)
        s = s.apply("""{"type":"host_away","until":123}""")
        assertTrue(s.hostAway)
        s = s.apply("""{"type":"host_back"}""")
        assertFalse(s.hostAway)
        s = s.apply("""{"type":"policy","policy":"locked","playlist_policy":"anyone"}""")
        assertEquals("locked", s.policy)
        assertTrue(s.canAddToPlaylist)
        s = s.apply("""{"type":"error","msg":"slow down"}""")
        assertEquals("slow down", s.lastError)
    }

    @Test
    fun expectedPositionExtrapolatesWhilePlaying() {
        val s = RoomState("X", clockOffsetMs = 100).apply("""{"type":"state","positionMs":10000,"playing":true,"rate":2.0,"server_ms":50000}""")
        // local now 51000 → hub now 51100 → 1100 ms since the stamp at 2× = 2200
        assertEquals(12200L, RoomReducer.expectedPositionMs(s, 51000))
        val paused = RoomState("X").apply("""{"type":"state","positionMs":10000,"playing":false,"server_ms":50000}""")
        assertEquals(10000L, RoomReducer.expectedPositionMs(paused, 99999))
        assertNull(RoomReducer.expectedPositionMs(RoomState("X"), 0))
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/RoomSyncTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/RoomSyncTest.kt) · test / fixture · 77 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
16: class RoomSyncTest {
18: fun pageFollowerClampsToTheLocalChapterAndSkipsOtherMediaOrDetachedFollowers() = runTest {
30: fun progressFollowerIgnoresJitterAndNonFiniteValues() = runTest {
42: fun pausedHostSeeksTheFollowerOnceWithoutTogglingPlayback() = runTest {
55: private fun room(vararg position: Pair<String, JsonPrimitive>) =
58: private class RecordingPlayer : MediaPlayerController {
61: override fun load(url: String, headers: Map<String, String>, initialPositionMs: Long) = Unit
62: override fun play() { playing = true }
63: override fun pause() { playing = false }
64: override fun seekTo(positionMs: Long) { seeks += positionMs }
65: override fun setPlaybackSpeed(speed: Float) = Unit
66: override fun release() = Unit
67: override fun currentPositionMs() = seeks.lastOrNull() ?: 0L
68: override fun durationMs() = 0L
69: override fun isPlaying() = playing
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/RoomSyncTest.kt) · SHA-256 `32ca0894c8f44b26a41a777d259f23e71f84756d2f0356ffe13c65987e937687`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.together

import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.Status
import eu.friedcutlet.yokan.services.media.player.MediaPlayerController
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.JsonPrimitive

class RoomSyncTest {
    @Test
    fun pageFollowerClampsToTheLocalChapterAndSkipsOtherMediaOrDetachedFollowers() = runTest {
        val jumps = mutableListOf<Int>()

        followPage(99, room("page" to JsonPrimitive(99)), Title, FirstChapter, pageIndex = 0, pageCount = 3, follows = { true }) { jumps += it }
        followPage(1, room("page" to JsonPrimitive(1)), Title, FirstChapter, pageIndex = 0, pageCount = 3, follows = { true }) { jumps += it }
        followPage(2, room("page" to JsonPrimitive(2)), Title, FirstChapter.copy(url = "/other"), pageIndex = 0, pageCount = 3, follows = { true }) { jumps += it }
        followPage(2, room("page" to JsonPrimitive(2)), Title, FirstChapter, pageIndex = 0, pageCount = 3, follows = { false }) { jumps += it }

        assertEquals(listOf(2), jumps)
    }

    @Test
    fun progressFollowerIgnoresJitterAndNonFiniteValues() = runTest {
        val follower = ProgressFollower()
        val applied = mutableListOf<Double>()

        for (progress in listOf("0.5", "0.51", "NaN", "1.5")) {
            follower.follow(progress.toDouble(), room("progress" to JsonPrimitive(progress)), Title, FirstChapter, follows = { true }) { applied += it }
        }

        assertEquals(listOf(0.5, 1.0), applied)
    }

    @Test
    fun pausedHostSeeksTheFollowerOnceWithoutTogglingPlayback() = runTest {
        val player = RecordingPlayer()
        val playing = mutableListOf<Boolean>()
        val paused = room("positionMs" to JsonPrimitive(5_000), "playing" to JsonPrimitive(false), "rate" to JsonPrimitive(1))

        followPlayback(paused.position, paused, Title, FirstChapter, player, follows = { true }) { playing += it }
        followPlayback(paused.position, paused, Title, FirstChapter, player, follows = { false }) { playing += it }

        assertEquals(listOf(5_000L), player.seeks)
        assertFalse(player.playing)
        assertTrue(playing.isEmpty())
    }

    private fun room(vararg position: Pair<String, JsonPrimitive>) =
        RoomState(code = "ABC", media = roomMediaFor(Title, FirstChapter), position = JsonObject(position.toMap()))

    private class RecordingPlayer : MediaPlayerController {
        val seeks = mutableListOf<Long>()
        var playing = false
        override fun load(url: String, headers: Map<String, String>, initialPositionMs: Long) = Unit
        override fun play() { playing = true }
        override fun pause() { playing = false }
        override fun seekTo(positionMs: Long) { seeks += positionMs }
        override fun setPlaybackSpeed(speed: Float) = Unit
        override fun release() = Unit
        override fun currentPositionMs() = seeks.lastOrNull() ?: 0L
        override fun durationMs() = 0L
        override fun isPlaying() = playing
    }

    private companion object {
        val Title = Manga(1, "Title", link = "/title", description = "", status = Status.Ongoing, itemType = ItemType.Manga,
            source = "source", lang = "en", dateAddedMillis = 0, lastUpdateMillis = 0, sourceId = 42)
        val FirstChapter = Chapter(1, 1, "Chapter", "/chapter/1")
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/TogetherAccountLifecycleTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/TogetherAccountLifecycleTest.kt) · test / fixture · 258 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
46: class TogetherAccountLifecycleTest {
164: override fun close() { attempts++; check(!fail) { "Native cleanup failed" }; first.close() }
214: private fun TestScope.fixture(): Fixture {
222: private class Fixture(val parent: Job, val engine: ProfileTestEngine, val database: InMemoryYokanDatabase,
224: suspend fun join(): RoomClient = assertNotNull(together.join(Hub, "ABC")).also { engine.requests.receive() }
225: suspend fun finish() { together.closeAndJoin(); parent.cancelAndJoin() }
229: private class ControlledSocket(context: CoroutineContext) : DefaultWebSocketSession {
246: override fun start(negotiatedExtensions: List<WebSocketExtension<*>>) = Unit
247: override suspend fun send(frame: Frame) { if (frame is Frame.Text) sent += frame.readText(); outgoing.send(frame) }
248: override suspend fun flush() = Unit
250: override fun terminate() { coroutineContext.cancel() }
253: private fun database() = InMemoryYokanDatabase(emptySnapshot()).also { it.upsertSyncPreference(Preference) }
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/TogetherAccountLifecycleTest.kt) · SHA-256 `988777a8df2c5e5ffc0364537c1aed915095c505b1dfacb4e2081ed74a2c0d43`.

### Complete file

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class, io.ktor.utils.io.InternalAPI::class)

package eu.friedcutlet.yokan.services.together

import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.SyncServerProvider
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.services.http.ProfileTestEngine
import io.ktor.client.engine.HttpClientEngine
import io.ktor.client.engine.callContext
import io.ktor.client.request.HttpResponseData
import io.ktor.http.Headers
import io.ktor.http.HttpProtocolVersion
import io.ktor.http.HttpStatusCode
import io.ktor.util.date.GMTDate
import io.ktor.websocket.CloseReason
import io.ktor.websocket.DefaultWebSocketSession
import io.ktor.websocket.Frame
import io.ktor.websocket.WebSocketExtension
import io.ktor.websocket.readText
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlin.coroutines.CoroutineContext
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue

class TogetherAccountLifecycleTest {
    @Test fun tokenChangeRevokesRoomAndJoinsFinalizersBeforeReplacementAllocation() = runTest {
        val parent = SupervisorJob(); val dispatcher = StandardTestDispatcher(testScheduler)
        val database = database(); val release = CompletableDeferred<Unit>()
        val first = ProfileTestEngine(dispatcher) {
            try { awaitCancellation() } finally { withContext(NonCancellable) { release.await() } }
        }
        val second = ProfileTestEngine(dispatcher) { awaitCancellation() }; var allocations = 0
        val scope = CoroutineScope(parent + dispatcher); val sibling = scope.launch { awaitCancellation() }
        val together = ProfileTogetherSession(ProfileId.Default, database, scope) {
            allocations++; if (allocations == 1) first else second
        }
        val old = assertNotNull(together.join(Hub, "OLD")); first.requests.receive()
        together.setDriving(true); together.setFollowing(false)
        database.upsertSyncPreference(Preference.copy(authToken = "new-token"))
        testScheduler.runCurrent()
        assertNull(together.client.value); assertFalse(together.driving.value); assertTrue(together.following.value)
        assertFalse(old.isAvailable); assertEquals(0, first.closeCalls)
        val joining = launch { together.join(assertNotNull(together.hubSession()), "NEW") }
        testScheduler.runCurrent()
        assertFalse(joining.isCompleted); assertEquals(1, allocations)
        assertTrue(parent.isActive); assertTrue(sibling.isActive)
        release.complete(Unit); joining.join()
        assertEquals(1, first.closeCalls); assertEquals("NEW", together.client.value?.code)
        assertEquals("Bearer new-token", second.requests.receive().headers["Authorization"])
        together.closeAndJoin(); parent.cancelAndJoin()
    }

    @Test fun logoutProviderServerDeviceAndSelectionChangesEachRevokeTheRoom() = runTest {
        for (changed in listOf(
            Preference.copy(authToken = null),
            Preference.copy(serverProvider = SyncServerProvider.Mangayomi),
            Preference.copy(server = "https://other-hub.test"),
            Preference.copy(deviceId = "other-device"),
        )) {
            val fixture = fixture()
            val client = fixture.join()
            fixture.database.upsertSyncPreference(changed)
            testScheduler.runCurrent()
            assertNull(fixture.together.client.value); assertFalse(client.isAvailable)
            assertEquals(1, fixture.engine.closeCalls); assertTrue(fixture.parent.isActive)
            fixture.finish()
        }
        val fixture = fixture(); val client = fixture.join()
        fixture.database.replaceAll(fixture.database.snapshot().copy(syncPreferences = listOf(Preference.copy(syncId = 2))))
        testScheduler.runCurrent()
        assertNull(fixture.together.client.value); assertFalse(client.isAvailable)
        fixture.finish()
    }

    @Test fun irrelevantSettingsAndNormalizedServerChangesKeepTheRoom() = runTest {
        val fixture = fixture(); val client = fixture.join()
        fixture.together.setDriving(true); fixture.together.setFollowing(false)
        fixture.database.updateSettings(fixture.database.settings().copy(userAgent = "new-agent"))
        fixture.database.upsertSyncPreference(Preference.copy(server = "https://hub.test/", email = "label@changed",
            syncOn = true, lastSyncManga = 999L, hubHead = 42L))
        testScheduler.runCurrent()
        assertSame(client, fixture.together.client.value); assertTrue(client.isAvailable)
        assertTrue(fixture.together.driving.value); assertFalse(fixture.together.following.value)
        assertEquals(0, fixture.engine.closeCalls)
        fixture.finish()
    }

    @Test fun retainedClientCannotReconnectEvenWhenCredentialsAreRestored() = runTest {
        val fixture = fixture(); val old = fixture.join()
        fixture.database.upsertSyncPreference(Preference.copy(authToken = null))
        // A retained command checks the captured account without waiting for the watcher.
        old.chat("late"); assertFalse(old.isAvailable)
        fixture.database.upsertSyncPreference(Preference)
        old.connect(); testScheduler.runCurrent()
        assertTrue(fixture.engine.requests.tryReceive().isFailure); assertFalse(old.isAvailable)
        fixture.together.leave(); assertEquals(1, fixture.engine.closeCalls)
        fixture.finish()
    }

    @Test fun accountChangeBeforeQueuedHandshakePreventsTransportDispatch() = runTest {
        val fixture = fixture()
        val client = assertNotNull(fixture.together.join(Hub, "ABC"))
        fixture.database.upsertSyncPreference(Preference.copy(authToken = "replacement"))
        testScheduler.runCurrent()
        assertTrue(fixture.engine.requests.tryReceive().isFailure)
        assertFalse(client.isAvailable); assertNull(fixture.together.client.value)
        assertEquals(1, fixture.engine.closeCalls)
        fixture.finish()
    }

    @Test fun queuedCommandsAndIncomingMessagesCannotUseAChangedAccount() = runTest {
        val parent = SupervisorJob(); val dispatcher = StandardTestDispatcher(testScheduler); val database = database()
        val socketReady = CompletableDeferred<ControlledSocket>()
        val engine = ProfileTestEngine(dispatcher) {
            val context = callContext(); val socket = ControlledSocket(context)
            socketReady.complete(socket)
            HttpResponseData(HttpStatusCode.SwitchingProtocols, GMTDate(), Headers.Empty,
                HttpProtocolVersion.HTTP_1_1, socket, context)
        }
        val together = ProfileTogetherSession(ProfileId.Default, database, CoroutineScope(parent + dispatcher)) { engine }
        val client = assertNotNull(together.join(Hub, "ABC")); val socket = socketReady.await()
        socket.incoming.send(Frame.Text("""{"type":"hello","you":{"id":"me","role":"host"}}"""))
        testScheduler.runCurrent(); assertEquals(RoomConnection.Open, client.state.value.connection)
        client.chat("accepted"); testScheduler.runCurrent()
        assertTrue(socket.sent.any { it.contains("accepted") })
        client.chat("queued-late")
        socket.incoming.send(Frame.Text("""{"type":"error","msg":"late-message"}"""))
        database.upsertSyncPreference(Preference.copy(authToken = null))
        client.chat("late"); client.sendPage(5, 10)
        testScheduler.runCurrent()
        assertFalse(socket.sent.any { it.contains("queued-late") || it.contains("\"text\":\"late\"") || it.contains("\"page\":5") })
        assertNull(client.state.value.lastError); assertNull(together.client.value)
        assertFalse(client.isAvailable); assertEquals(1, engine.closeCalls); assertTrue(parent.isActive)
        together.closeAndJoin(); parent.cancelAndJoin()
    }

    @Test fun failedRevocationCleanupIsRetriedBeforeAnotherRoomIsAllocated() = runTest {
        val parent = SupervisorJob(); val dispatcher = StandardTestDispatcher(testScheduler); val database = database()
        val first = ProfileTestEngine(dispatcher) { awaitCancellation() }
        val second = ProfileTestEngine(dispatcher) { awaitCancellation() }
        var fail = true; var attempts = 0; var allocations = 0
        val failing = object : HttpClientEngine by first {
            override fun close() { attempts++; check(!fail) { "Native cleanup failed" }; first.close() }
        }
        val together = ProfileTogetherSession(ProfileId.Default, database, CoroutineScope(parent + dispatcher)) {
            allocations++; if (allocations == 1) failing else second
        }
        together.join(Hub, "OLD"); first.requests.receive()
        database.upsertSyncPreference(Preference.copy(authToken = "replacement"))
        testScheduler.runCurrent()
        assertNull(together.client.value); assertEquals(1, attempts); assertEquals(1, allocations)
        assertTrue(parent.isActive)
        fail = false
        assertNotNull(together.join(assertNotNull(together.hubSession()), "NEW"))
        assertEquals(2, attempts); assertEquals(2, allocations); assertEquals(1, first.closeCalls)
        together.closeAndJoin(); parent.cancelAndJoin()
    }

    @Test fun queuedAccountWatcherCannotRevokeAReplacementForTheLatestAccount() = runTest {
        val parent = SupervisorJob(); val dispatcher = StandardTestDispatcher(testScheduler); val database = database()
        val release = CompletableDeferred<Unit>()
        val first = ProfileTestEngine(dispatcher) {
            try { awaitCancellation() } finally { withContext(NonCancellable) { release.await() } }
        }
        val second = ProfileTestEngine(dispatcher) { awaitCancellation() }; var allocations = 0
        val together = ProfileTogetherSession(ProfileId.Default, database, CoroutineScope(parent + dispatcher)) {
            allocations++; if (allocations == 1) first else second
        }
        together.join(Hub, "OLD"); first.requests.receive()
        database.upsertSyncPreference(Preference.copy(authToken = "intermediate"))
        testScheduler.runCurrent()
        database.upsertSyncPreference(Preference.copy(authToken = "latest"))
        val replacing = launch { together.join(assertNotNull(together.hubSession()), "LATEST") }
        testScheduler.runCurrent(); assertEquals(1, allocations)
        release.complete(Unit); replacing.join(); testScheduler.runCurrent()
        val current = assertNotNull(together.client.value)
        assertEquals("LATEST", current.code); assertTrue(current.isAvailable)
        assertEquals("Bearer latest", second.requests.receive().headers["Authorization"])
        assertEquals(0, second.closeCalls); assertTrue(parent.isActive)
        together.closeAndJoin(); parent.cancelAndJoin()
    }

    @Test fun changingOneAccountDoesNotRevokeAnotherOwner() = runTest {
        val left = fixture(); val right = fixture()
        val a = left.join(); val b = right.join()
        left.database.upsertSyncPreference(Preference.copy(authToken = null))
        testScheduler.runCurrent()
        assertFalse(a.isAvailable); assertNull(left.together.client.value)
        assertSame(b, right.together.client.value); assertTrue(b.isAvailable); assertEquals(0, right.engine.closeCalls)
        left.finish(); right.finish()
    }

    private fun TestScope.fixture(): Fixture {
        val parent = SupervisorJob(); val dispatcher = StandardTestDispatcher(testScheduler)
        val engine = ProfileTestEngine(dispatcher) { awaitCancellation() }
        val database = database()
        return Fixture(parent, engine, database,
            ProfileTogetherSession(ProfileId.Default, database, CoroutineScope(parent + dispatcher)) { engine })
    }

    private class Fixture(val parent: Job, val engine: ProfileTestEngine, val database: InMemoryYokanDatabase,
        val together: ProfileTogetherSession) {
        suspend fun join(): RoomClient = assertNotNull(together.join(Hub, "ABC")).also { engine.requests.receive() }
        suspend fun finish() { together.closeAndJoin(); parent.cancelAndJoin() }
    }

    /** A real Ktor upgrade with controlled frame channels instead of a remote socket. */
    private class ControlledSocket(context: CoroutineContext) : DefaultWebSocketSession {
        override val coroutineContext = context + Job(context[Job])
        override var masking = false
        override var maxFrameSize = Long.MAX_VALUE
        override var pingIntervalMillis = -1L
        override var timeoutMillis = 15_000L
        override val incoming = Channel<Frame>(Channel.UNLIMITED)
        override val outgoing = Channel<Frame>(Channel.UNLIMITED)
        override val extensions: List<WebSocketExtension<*>> = emptyList()
        override val closeReason = CompletableDeferred<CloseReason?>()
        val sent = mutableListOf<String>()
        init {
            CoroutineScope(coroutineContext).launch {
                try { awaitCancellation() }
                finally { incoming.cancel(); outgoing.cancel(); closeReason.complete(null) }
            }
        }
        override fun start(negotiatedExtensions: List<WebSocketExtension<*>>) = Unit
        override suspend fun send(frame: Frame) { if (frame is Frame.Text) sent += frame.readText(); outgoing.send(frame) }
        override suspend fun flush() = Unit
        @Deprecated("Overrides deprecated Ktor API")
        override fun terminate() { coroutineContext.cancel() }
    }

    private fun database() = InMemoryYokanDatabase(emptySnapshot()).also { it.upsertSyncPreference(Preference) }
    private companion object {
        val Preference = DbSyncPreference(syncId = 1, server = "https://hub.test", authToken = "owner-token", deviceId = "owner-device")
        val Hub = HubSession("https://hub.test", "owner-token", "owner-device")
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/TogetherCreationLifecycleTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/TogetherCreationLifecycleTest.kt) · test / fixture · 241 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
43: class TogetherCreationLifecycleTest {
231: private fun database() = InMemoryYokanDatabase(emptySnapshot().copy(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/TogetherCreationLifecycleTest.kt) · SHA-256 `83d26640384b1e6cb3f786c7d7c674305604361f5fe5899e72daa53101facdfc`.

### Complete file

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)

package eu.friedcutlet.yokan.services.together

import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.SyncServerProvider
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.services.http.HttpRequest
import eu.friedcutlet.yokan.services.http.HttpResponse
import eu.friedcutlet.yokan.services.http.RecordingHttpService
import eu.friedcutlet.yokan.services.http.ProfileHttpService
import eu.friedcutlet.yokan.services.http.ProfileTestEngine
import eu.friedcutlet.yokan.ui.screens.together.TogetherActions
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancel
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue

class TogetherCreationLifecycleTest {
    @Test fun creationUsesCapturedCredentialsAndReturnsTheJoinedClient() = runTest {
        val parent = SupervisorJob()
        val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))
        val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() }
        val together = ProfileTogetherSession(ProfileId.Default, database(), scope) { engine }
        val http = RecordingHttpService { Created }
        val joined = assertNotNull(together.createAndJoin(http, Media)).getOrThrow()
        val rest = http.requests.single()
        assertEquals("https://hub.test/api/v1/rooms", rest.url)
        assertEquals("POST", rest.method)
        assertEquals("Bearer owner-token", rest.headers["Authorization"])
        assertEquals("owner-device", rest.headers["X-Device"])
        val body = RoomJson.parseToJsonElement(requireNotNull(rest.body)).jsonObject
        assertEquals("approve", body["policy"]?.jsonPrimitive?.content)
        assertEquals("suggest", body["playlist_policy"]?.jsonPrimitive?.content)
        assertEquals(Media, RoomJson.decodeFromJsonElement(RoomMedia.serializer(), requireNotNull(body["media"])))
        val socket = engine.requests.receive()
        assertEquals("Bearer owner-token", socket.headers["Authorization"])
        assertEquals("owner-device", socket.headers["X-Device"])
        assertEquals("ABCDEF", joined.client.code)
        assertSame(joined.client, together.client.value)
        assertTrue(together.owns(joined.client))
        together.leave()
        assertFalse(together.owns(joined.client))
        together.closeAndJoin(); parent.cancelAndJoin()
    }

    @Test fun changedAccountDuringCreationCannotAllocateAJoinedRoom() = runTest {
        val mutations: List<(DbSyncPreference) -> DbSyncPreference> = listOf(
            { it.copy(authToken = null, syncOn = false) },
            { it.copy(authToken = "new-token") },
            { it.copy(server = "https://new-hub.test") },
            { it.copy(deviceId = "new-device") },
            { it.copy(serverProvider = SyncServerProvider.Mangayomi) },
            { it.copy(syncId = 2) }, // Even identical server/token/device cannot retarget another preference.
        )
        for (mutate in mutations) {
            val parent = SupervisorJob(); val db = database(); var allocations = 0
            val together = ProfileTogetherSession(ProfileId.Default, db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) {
                allocations++; error("Stale REST result allocated a socket")
            }
            val replacement = mutate(Preference)
            val http = RecordingHttpService {
                db.replaceAll(db.snapshot().copy(syncPreferences = listOf(replacement)))
                Created
            }
            assertFailsWith<CancellationException> { together.createAndJoin(http, Media) }
            assertEquals(0, allocations); assertNull(together.client.value)
            assertEquals(replacement, db.syncPreferences().single())
            together.closeAndJoin(); parent.cancelAndJoin()
        }
    }

    @Test fun controllerRetirementJoinsRestFinalizersThroughTheProfileHttpWrapper() = runTest {
        val parent = SupervisorJob(); val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()
        val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))
        val together = ProfileTogetherSession(ProfileId.Default, database(), scope) { error("Retired socket") }
        var finalized = false
        val delegate = RecordingHttpService { request ->
            if (request.method == "POST") {
                entered.complete(Unit)
                try { awaitCancellation() } finally { withContext(NonCancellable) { release.await(); finalized = true } }
            }
            HttpResponse(200, "sibling")
        }
        val http = ProfileHttpService(ProfileId.Default, delegate, scope)
        val caller = launch { together.createAndJoin(http, Media) }
        entered.await()
        val closing = launch { together.closeAndJoin() }
        testScheduler.runCurrent()
        assertFalse(closing.isCompleted); assertFalse(caller.isCompleted); assertFalse(finalized)
        assertNull(together.hubSession()); assertTrue(parent.isActive)
        release.complete(Unit); closing.join(); caller.join()
        assertTrue(finalized); assertNull(together.client.value)
        assertEquals("sibling", http.request(HttpRequest("https://hub.test/sibling")).body)
        assertFailsWith<CancellationException> { together.createAndJoin(http, Media) }
        parent.cancelAndJoin()
    }

    @Test fun callerExpiryJoinsCreationWithoutRetiringItsControllerOrSiblingOwner() = runTest {
        val a = SupervisorJob(); val b = SupervisorJob()
        val release = CompletableDeferred<Unit>(); val entered = CompletableDeferred<Unit>()
        val first = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(a + StandardTestDispatcher(testScheduler))) { error("Expired socket") }
        val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() }
        val second = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(b + StandardTestDispatcher(testScheduler))) { engine }
        val caller = launch {
            first.createAndJoin(RecordingHttpService {
                entered.complete(Unit)
                try { awaitCancellation() } finally { withContext(NonCancellable) { release.await() } }
            }, Media)
        }
        entered.await(); caller.cancel(); testScheduler.runCurrent()
        assertFalse(caller.isCompleted); assertTrue(a.isActive)
        assertNotNull(second.createAndJoin(RecordingHttpService { Created }, Media)).getOrThrow()
        assertNotNull(second.client.value)
        release.complete(Unit); caller.join()
        assertNull(first.client.value); assertNotNull(first.hubSession()); assertTrue(b.isActive)
        first.closeAndJoin(); second.closeAndJoin(); a.cancelAndJoin(); b.cancelAndJoin()
    }

    @Test fun queuedAndAlreadyExpiredCreationCannotDispatch() = runTest {
        val parent = SupervisorJob(); val http = RecordingHttpService { Created }
        val together = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { error("Queued socket") }
        val queued = launch { together.createAndJoin(http, Media) }
        together.closeAndJoin(); queued.join()
        assertTrue(http.requests.isEmpty()); assertTrue(parent.isActive)
        val immediate = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + UnconfinedTestDispatcher(testScheduler))) { error("Expired socket") }
        val expired = launch {
            currentCoroutineContext().cancel()
            assertFailsWith<CancellationException> { immediate.createAndJoin(http, Media) }
        }
        expired.join(); assertTrue(http.requests.isEmpty()); assertTrue(parent.isActive)
        immediate.closeAndJoin(); parent.cancelAndJoin()
    }

    @Test fun creationFailurePreservesAnExistingRoomAndCanBeRetried() = runTest {
        val parent = SupervisorJob()
        val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() }
        val together = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine }
        val current = assertNotNull(together.join(Hub, "OLD")); engine.requests.receive()
        for (response in listOf(HttpResponse(401, "{\"error\":\"Unauthorized\"}"), HttpResponse(200, "{}"), HttpResponse(200, "invalid"))) {
            assertTrue(assertNotNull(together.createAndJoin(RecordingHttpService { response }, Media)).isFailure)
            assertSame(current, together.client.value); assertTrue(together.owns(current)); assertEquals(0, engine.closeCalls)
        }
        together.closeAndJoin(); parent.cancelAndJoin()
    }

    @Test fun preferenceChangeDuringOldRoomCleanupCannotJoinTheCreatedRoom() = runTest {
        val parent = SupervisorJob(); val db = database(); val release = CompletableDeferred<Unit>(); var allocations = 0
        val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) {
            try { awaitCancellation() } finally { withContext(NonCancellable) { release.await() } }
        }
        val together = ProfileTogetherSession(ProfileId.Default, db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { allocations++; engine }
        together.join(Hub, "OLD"); engine.requests.receive()
        val caller = launch { together.createAndJoin(RecordingHttpService { Created }, Media) }
        testScheduler.runCurrent(); assertFalse(caller.isCompleted); assertNull(together.client.value)
        db.replaceAll(db.snapshot().copy(syncPreferences = listOf(Preference.copy(syncId = 2))))
        release.complete(Unit); caller.join()
        assertEquals(1, allocations); assertEquals(1, engine.closeCalls); assertNull(together.client.value)
        together.closeAndJoin(); parent.cancelAndJoin()
    }

    @Test fun titleActionSuppressesLateNavigationAndDeliversItsOwnSuccessfulRoom() = runTest {
        val parent = SupervisorJob(); val db = database(); var opened = 0
        val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() }
        val together = ProfileTogetherSession(ProfileId.Default, db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine }
        val title = assertNotNull(DefaultYokanRepository(db).manga(1))
        val changed = RecordingHttpService { db.upsertSyncPreference(Preference.copy(authToken = "new-token")); Created }
        assertFailsWith<CancellationException> { TogetherActions.startRoom(together, changed, title, null) { opened++ } }
        assertEquals(0, opened); assertNull(together.client.value)
        db.upsertSyncPreference(Preference)
        val message = TogetherActions.startRoom(together, RecordingHttpService { Created }, title, null) { opened++ }
        assertEquals(1, opened); assertTrue(message.contains("ABCDEF")); assertEquals("ABCDEF", together.client.value?.code)
        together.closeAndJoin(); parent.cancelAndJoin()
    }

    @Test fun lateNonCancellableResponseCannotJoinAfterOwnerRetirement() = runTest {
        val parent = SupervisorJob(); val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>(); var allocations = 0
        val together = ProfileTogetherSession(ProfileId.Default, database(), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) {
            allocations++; error("Late owner socket")
        }
        val http = RecordingHttpService {
            entered.complete(Unit)
            withContext(NonCancellable) { release.await() }
            Created
        }
        val caller = launch { together.createAndJoin(http, Media) }
        entered.await(); parent.cancel(); testScheduler.runCurrent()
        assertFalse(caller.isCompleted); assertEquals(0, allocations)
        release.complete(Unit); parent.join(); caller.join()
        assertEquals(0, allocations); assertNull(together.client.value)
        together.closeAndJoin()
    }

    @Test fun unrelatedBookkeepingDuringCreationPreservesTheAccount() = runTest {
        val parent = SupervisorJob(); val db = database()
        val engine = ProfileTestEngine(StandardTestDispatcher(testScheduler)) { awaitCancellation() }
        val together = ProfileTogetherSession(ProfileId.Default, db, CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { engine }
        val http = RecordingHttpService {
            db.upsertSyncPreference(Preference.copy(hubHead = 10, syncSettings = true, email = "label"))
            Created
        }
        val joined = assertNotNull(together.createAndJoin(http, Media)).getOrThrow()
        assertTrue(together.owns(joined.client)); assertEquals(10L, db.syncPreferences().single().hubHead)
        together.closeAndJoin(); parent.cancelAndJoin()
    }

    private fun database() = InMemoryYokanDatabase(emptySnapshot().copy(
        syncPreferences = listOf(Preference), mangas = listOf(DbManga(id = 1, name = "Title", link = "/title")),
    ))

    private companion object {
        val Preference = DbSyncPreference(syncId = 1, server = "https://hub.test/", authToken = "owner-token", deviceId = "owner-device")
        val Hub = HubSession("https://hub.test", "owner-token", "owner-device")
        val Media = RoomMedia("manga", 1, "/title", title = "Title")
        val Created = HttpResponse(201, "{\"code\":\"ABCDEF\",\"join_url\":\"https://hub.test/rooms/ABCDEF\"}")
    }
}
```
[complete-source-end]: #

## `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/together/RoomClientAdmissionConcurrencyTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/together/RoomClientAdmissionConcurrencyTest.kt) · test / fixture · 53 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
19: class RoomClientAdmissionConcurrencyTest {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/together/RoomClientAdmissionConcurrencyTest.kt) · SHA-256 `78547a8bbde0fb31bd39ceb998b37cd75c92dda8b05ae4be50f020c3da32c36b`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.together

import eu.friedcutlet.yokan.services.http.ProfileTestEngine
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.runTest
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class RoomClientAdmissionConcurrencyTest {
    @Test fun concurrentCloseDoesNotWaitForABlockedCredentialRead() = runTest {
        val parent = SupervisorJob(); val dispatcher = StandardTestDispatcher(testScheduler)
        val entered = CountDownLatch(1); val release = CountDownLatch(1); val closed = CountDownLatch(1)
        val failures = ConcurrentLinkedQueue<Throwable>()
        val engine = ProfileTestEngine(dispatcher) { awaitCancellation() }
        val client = RoomClient(engine, HubSession("https://hub.test", "token", "device"), "ABC",
            CoroutineScope(parent + dispatcher)) {
            entered.countDown()
            release.await()
            true
        }
        val connecting = thread(name = "room-admission-test", isDaemon = true) {
            try { client.connect() } catch (error: Throwable) { failures.add(error) }
        }
        var closing: Thread? = null
        try {
            assertTrue(entered.await(5, TimeUnit.SECONDS), "Credential read did not start")
            closing = thread(name = "room-close-test", isDaemon = true) {
                try { client.close() } catch (error: Throwable) { failures.add(error) }
                finally { closed.countDown() }
            }
            // If admission holds the room lock, release would wait for this blocked database read.
            assertTrue(closed.await(5, TimeUnit.SECONDS), "Close is blocked by the credential read")
            assertEquals(1, engine.closeCalls)
        } finally {
            release.countDown()
            connecting.join(5_000); closing?.join(5_000)
            client.closeAndJoin(); parent.cancelAndJoin()
        }
        assertFalse(connecting.isAlive); assertFalse(closing.isAlive)
        assertTrue(failures.isEmpty(), failures.toString())
        assertTrue(engine.requests.tryReceive().isFailure)
    }
}
```
[complete-source-end]: #

## `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherHooksLifecycleTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherHooksLifecycleTest.kt) · test / fixture · 378 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
52: class TogetherHooksLifecycleTest {
252: private enum class Mode { Binding, Page, Progress, Playback, Navigation }
254: private class Fixture(val test: TestScope) {
310: suspend fun join(role: String = "participant") {
314: fun media() = send("""{"type":"media","media":${RoomJson.encodeToString(roomMediaFor(Manga, chapter.value))}}""")
315: fun send(json: String) { assertTrue(socket.incoming.trySend(Frame.Text(json)).isSuccess); pump() }
316: fun mount(next: Mode) { ui { mode.value = next; show.value = true }; pump() }
317: fun hide() { ui { show.value = false }; pump() }
318: fun changeChapter(next: Chapter) { ui { chapter.value = next }; pump() }
321: fun pump() = ui { repeat(3) {
326: fun advance(ms: Long) = ui { test.testScheduler.advanceTimeBy(ms); pump() }
327: suspend fun finish() { ui { scene.close() }; together.closeAndJoin(); parent.cancelAndJoin() }
330: private class RecordingPlayer : MediaPlayerController {
335: override fun load(url: String, headers: Map<String, String>, initialPositionMs: Long) = Unit
336: override fun play() { playing = true }
337: override fun pause() { playing = false }
338: override fun seekTo(positionMs: Long) { seeks += positionMs }
339: override fun setPlaybackSpeed(speed: Float) = Unit
340: override fun release() = Unit
341: override fun currentPositionMs(): Long { reads++; return 0 }
342: override fun durationMs() = 0L
343: override fun isPlaying(): Boolean { reads++; beforePlayingRead(); return playing }
346: private class ControlledSocket(context: CoroutineContext) : DefaultWebSocketSession {
359: override fun start(negotiatedExtensions: List<WebSocketExtension<*>>) = Unit
361: override suspend fun send(frame: Frame) { if (frame is Frame.Text) sent += frame.readText(); outgoing.send(frame) }
362: override suspend fun flush() = Unit
364: override fun terminate() { coroutineContext.cancel() }
373: fun <T> ui(block: () -> T): T {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherHooksLifecycleTest.kt) · SHA-256 `defffe7da36665adf6a8ed5aeb3bc29bde4cd66f1e556a2be17209e4fdb282f1`.

### Complete file

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class, androidx.compose.ui.ExperimentalComposeUiApi::class, io.ktor.utils.io.InternalAPI::class)

package eu.friedcutlet.yokan.ui.screens.together

import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.SideEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.ImageComposeScene
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.lifecycle.compose.LocalLifecycleOwner
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.database.DbPageUrl
import eu.friedcutlet.yokan.database.DbReaderMode
import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.ItemType
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.Status
import eu.friedcutlet.yokan.services.http.ProfileTestEngine
import eu.friedcutlet.yokan.services.media.player.MediaPlayerController
import eu.friedcutlet.yokan.services.together.*
import eu.friedcutlet.yokan.ui.screens.reader.ReaderEvent
import eu.friedcutlet.yokan.ui.screens.reader.ReaderLoadState
import eu.friedcutlet.yokan.ui.screens.reader.ReaderState
import io.ktor.client.engine.callContext
import io.ktor.client.request.HttpResponseData
import io.ktor.http.Headers
import io.ktor.http.HttpProtocolVersion
import io.ktor.http.HttpStatusCode
import io.ktor.util.date.GMTDate
import io.ktor.websocket.*
import java.util.concurrent.FutureTask
import javax.swing.SwingUtilities
import kotlin.coroutines.CoroutineContext
import kotlin.test.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.test.*
import kotlinx.serialization.encodeToString

class TogetherHooksLifecycleTest {
    @Test fun disposedBindingCannotApplyOrControlARoomAndRemountGetsANewCapability() = runTest {
        val f = Fixture(this)
        try {
            f.join(); f.mount(Mode.Binding)
            val old = f.binding
            assertTrue(old.follows(f.client.state.value))
            f.hide(); assertFalse(old.active()); assertTrue(f.parent.isActive)
            f.mount(Mode.Binding)
            assertNotSame(old, f.binding); assertTrue(f.binding.active())
            assertFalse(old.active())
        } finally { f.finish() }
    }

    @Test fun changedCredentialsRejectRetainedBindingsBeforeTheWatcherRuns() = runTest {
        val f = Fixture(this)
        try {
            f.join(); f.mount(Mode.Binding)
            val old = f.binding; val room = f.client.state.value
            f.database.upsertSyncPreference(Preference.copy(authToken = "replacement"))
            assertFalse(old.follows(room)); assertFalse(old.active())
            f.pump(); assertNull(f.together.client.value)
        } finally { f.finish() }
    }

    @Test fun sameCodeReplacementInvalidatesOldBindingAndLeaveTargetsOnlyCapturedClient() = runTest {
        val f = Fixture(this)
        try {
            f.join(); f.mount(Mode.Binding)
            val old = f.binding; val oldClient = f.client
            f.join(); f.pump()
            assertFalse(old.active()); assertTrue(f.binding.active())
            f.together.leave(oldClient)
            assertSame(f.client, f.together.client.value)
            assertTrue(f.binding.active())
            f.together.leave(f.client); f.pump(); assertNull(f.together.client.value)
        } finally { f.finish() }
    }

    @Test fun pageFollowingClampsAndStopsWhenDetachedDisposedOrAccountChanges() = runTest {
        val f = Fixture(this)
        try {
            f.join(); f.send("""{"type":"state","page":99,"pages":3}"""); f.mount(Mode.Page)
            assertEquals<List<ReaderEvent>>(listOf(ReaderEvent.JumpToPage(2)), f.pages)
            f.together.setFollowing(false); f.send("""{"type":"state","page":2}""")
            assertEquals(1, f.pages.size)
            f.together.setFollowing(true); f.pump(); assertEquals<ReaderEvent>(ReaderEvent.JumpToPage(1), f.pages.last())
            f.hide(); f.send("""{"type":"state","page":1}"""); assertEquals(2, f.pages.size)
            f.database.upsertSyncPreference(Preference.copy(authToken = null)); f.pump()
            assertEquals(2, f.pages.size)
        } finally { f.finish() }
    }

    @Test fun stalePositionIsRejectedButUnrelatedRoomMessagesDoNotInvalidateFollowing() = runTest {
        val f = Fixture(this)
        try {
            f.join(); f.mount(Mode.Binding)
            f.send("""{"type":"state","progress":0.25}"""); val old = f.client.state.value
            assertTrue(f.binding.follows(old))
            f.send("""{"type":"error","msg":"unrelated"}""")
            assertTrue(f.binding.follows(old)); assertFalse(f.binding.current(old))
            f.send("""{"type":"state","progress":0.75}""")
            assertFalse(f.binding.follows(old))
            f.together.setFollowing(false); assertFalse(f.binding.follows(f.client.state.value))
        } finally { f.finish() }
    }

    @Test fun novelUpdatesResetOnChapterAndRoomReplacementAndRejectNonFiniteProgress() = runTest {
        val f = Fixture(this)
        try {
            f.join(); f.send("""{"type":"state","progress":0.5}"""); f.mount(Mode.Progress)
            assertEquals(listOf(0.5), f.progress)
            f.send("""{"type":"state","progress":0.51}"""); assertEquals(1, f.progress.size)
            f.send("""{"type":"state","progress":"NaN"}"""); assertEquals(1, f.progress.size)
            f.changeChapter(Chapter.copy(id = 2, url = "/chapter/2"))
            f.media(); f.send("""{"type":"state","progress":0.5}""")
            assertEquals(listOf(0.5, 0.5), f.progress)
            f.join(); f.send("""{"type":"state","progress":0.5}""")
            assertEquals(listOf(0.5, 0.5, 0.5), f.progress)
        } finally { f.finish() }
    }

    @Test fun novelFollowerScrollRemainsAChildOfTheDisposedEffect() = runTest {
        val f = Fixture(this)
        try {
            f.join(); f.send("""{"type":"state","progress":0.5}""")
            f.holdProgress = true; f.mount(Mode.Progress)
            assertEquals(listOf(0.5), f.progress); assertFalse(f.progressFinalized)
            f.hide(); assertTrue(f.progressFinalized); assertTrue(f.parent.isActive)
        } finally { f.finish() }
    }

    @Test fun playbackConvergesThenStopsReadingTheControllerAfterDisposal() = runTest {
        val f = Fixture(this)
        try {
            f.join(); f.send("""{"type":"state","positionMs":5000,"playing":true,"rate":1,"server_ms":0}""")
            f.mount(Mode.Playback)
            assertTrue(f.player.seeks.isNotEmpty()); assertTrue(f.player.playing)
            assertEquals(listOf(true), f.playing)
            f.hide(); val reads = f.player.reads
            f.advance(4000); assertEquals(reads, f.player.reads)
            assertTrue(f.parent.isActive)
        } finally { f.finish() }
    }

    @Test fun followMediaUsesCapturedControllerAndDoesNotOpenAfterDetaching() = runTest {
        val f = Fixture(this)
        try {
            f.join(); f.mount(Mode.Page)
            val other = roomMediaFor(Manga.copy(link = "/other"), Chapter)
            f.send("""{"type":"media","media":${RoomJson.encodeToString(other)}}""")
            assertEquals(listOf(other), f.opened)
            f.together.setFollowing(false)
            f.send("""{"type":"media","media":${RoomJson.encodeToString(other.copy(link = "/third"))}}""")
            assertEquals(1, f.opened.size)
            f.hide(); f.advance(500); assertEquals(1, f.opened.size)
        } finally { f.finish() }
    }

    @Test fun drivingTracksCapturedCoHostControlsAndRejectsClosedRooms() = runTest {
        val f = Fixture(this)
        try {
            f.join("co_host"); f.mount(Mode.Binding)
            assertFalse(f.binding.drives()); assertTrue(f.binding.follows(f.client.state.value))
            f.together.setDriving(true); assertTrue(f.binding.drives()); assertFalse(f.binding.follows(f.client.state.value))
            f.send("""{"type":"closed","reason":"host_left"}""")
            assertFalse(f.binding.drives()); assertFalse(f.binding.follows(f.client.state.value))
        } finally { f.finish() }
    }

    @Test fun navigationCapturesLibraryAndExpiresOnDisposalAndSameMediaReplacement() = runTest {
        val f = Fixture(this)
        try {
            f.database.upsertManga(DbManga(id = 1, name = "Local", link = "/title", sourceId = 42))
            f.database.upsertChapter(DbChapter(id = 1, mangaId = 1, name = "Chapter", url = "/chapter/1"))
            f.join(); f.mount(Mode.Navigation)
            val firstAction = f.open; val media = assertNotNull(f.client.state.value.media)
            ui { firstAction(media) }; assertEquals(Route.Reader(1, 1), f.nav.backStack.value.last().route)
            ui { f.nav.back() }; f.join(); f.pump()
            ui { firstAction(media) }; assertTrue(f.nav.backStack.value.isEmpty())
            val replacementAction = f.open
            ui { replacementAction(media) }; assertEquals(Route.Reader(1, 1), f.nav.backStack.value.last().route)
            ui { f.nav.back() }; f.hide()
            ui { replacementAction(media) }; assertTrue(f.nav.backStack.value.isEmpty())
        } finally { f.finish() }
    }

    @Test fun navigationRejectsSupersededMediaAndImmediateAccountRevocation() = runTest {
        val f = Fixture(this)
        try {
            f.database.upsertManga(DbManga(id = 1, name = "Local", link = "/title", sourceId = 42))
            f.database.upsertChapter(DbChapter(id = 1, mangaId = 1, name = "Chapter", url = "/chapter/1"))
            f.join(); f.mount(Mode.Navigation)
            val action = f.open; val media = assertNotNull(f.client.state.value.media)
            f.send("""{"type":"media","media":${RoomJson.encodeToString(media.copy(link = "/other"))}}""")
            ui { action(media) }; assertTrue(f.nav.backStack.value.isEmpty())
            f.media(); f.database.upsertSyncPreference(Preference.copy(authToken = null))
            ui { f.open(media) }; assertTrue(f.nav.backStack.value.isEmpty())
        } finally { f.finish() }
    }

    @Test fun stoppedLifecycleBlocksRetainedNavigationAndResumeCreatesFreshAdmission() = runTest {
        val f = Fixture(this)
        try {
            f.database.upsertManga(DbManga(id = 1, name = "Local", link = "/title", sourceId = 42))
            f.database.upsertChapter(DbChapter(id = 1, mangaId = 1, name = "Chapter", url = "/chapter/1"))
            f.join(); f.mount(Mode.Navigation)
            val old = f.open; val media = assertNotNull(f.client.state.value.media)
            ui { f.lifecycleRegistry.currentState = Lifecycle.State.CREATED }
            ui { old(media) }; assertTrue(f.nav.backStack.value.isEmpty())
            f.pump(); assertFalse(f.binding.active())
            ui { f.lifecycleRegistry.currentState = Lifecycle.State.RESUMED }; f.pump()
            ui { old(media) }; assertTrue(f.nav.backStack.value.isEmpty())
            ui { f.open(media) }; assertEquals(Route.Reader(1, 1), f.nav.backStack.value.last().route)
        } finally { f.finish() }
    }

    @Test fun disposedHostCannotSendDebouncedNovelProgress() = runTest {
        val f = Fixture(this)
        try {
            f.join("host"); f.mount(Mode.Progress)
            f.hide(); f.advance(1000)
            assertFalse(f.socket.sent.any { it.contains("\"progress\"") })
            f.mount(Mode.Progress); f.advance(600)
            assertTrue(f.socket.sent.any { it.contains("\"progress\"") })
        } finally { f.finish() }
    }

    @Test fun accountRevokedByPlayerReadCannotIssuePlayOrFollowerState() = runTest {
        val f = Fixture(this)
        try {
            f.join(); f.send("""{"type":"state","positionMs":0,"playing":true,"rate":1,"server_ms":0}""")
            f.player.beforePlayingRead = { f.database.upsertSyncPreference(Preference.copy(authToken = null)) }
            f.mount(Mode.Playback)
            assertTrue(f.player.reads > 0)
            assertNull(f.database.snapshot().syncPreferences.single().authToken)
            assertFalse(f.player.playing); assertTrue(f.playing.isEmpty())
        } finally { f.finish() }
    }

    private enum class Mode { Binding, Page, Progress, Playback, Navigation }

    private class Fixture(val test: TestScope) {
        val parent = SupervisorJob()
        val dispatcher = StandardTestDispatcher(test.testScheduler)
        val database = InMemoryYokanDatabase(emptySnapshot()).also { it.upsertSyncPreference(Preference) }
        val repository = DefaultYokanRepository(database)
        val settings = SettingsStore(repository, CoroutineScope(parent + dispatcher)) {}
        val nav = Navigator(settings, CoroutineScope(parent + dispatcher))
        lateinit var open: (RoomMedia) -> Unit
        val sockets = Channel<ControlledSocket>(Channel.UNLIMITED)
        val together = ProfileTogetherSession(ProfileId.Default, database, CoroutineScope(parent + dispatcher)) {
            ProfileTestEngine(dispatcher) {
                val context = callContext(); val socket = ControlledSocket(context); sockets.send(socket)
                HttpResponseData(HttpStatusCode.SwitchingProtocols, GMTDate(), Headers.Empty, HttpProtocolVersion.HTTP_1_1, socket, context)
            }
        }
        lateinit var socket: ControlledSocket
        lateinit var client: RoomClient
        lateinit var binding: TogetherUiBinding
        val show = mutableStateOf(false)
        val mode = mutableStateOf(Mode.Binding)
        val chapter = mutableStateOf(Chapter)
        val pages = mutableListOf<ReaderEvent>()
        val progress = mutableListOf<Double>()
        val playing = mutableListOf<Boolean>()
        val opened = mutableListOf<RoomMedia>()
        val player = RecordingPlayer()
        var holdProgress = false
        var progressFinalized = false
        val lifecycleOwner = object : LifecycleOwner { override val lifecycle = LifecycleRegistry.createUnsafe(this) }
        val lifecycleRegistry = lifecycleOwner.lifecycle as LifecycleRegistry
        val scene = ui {
            lifecycleRegistry.currentState = Lifecycle.State.RESUMED
            ImageComposeScene(100, 100, coroutineContext = UnconfinedTestDispatcher(test.testScheduler)) {
                CompositionLocalProvider(LocalLifecycleOwner provides lifecycleOwner) {
                    if (show.value) {
                        val active = together.client.collectAsStateWithLifecycle().value
                        val current = rememberTogetherUiBinding(together, active, chapter.value.url)
                        SideEffect { binding = current }
                        when (mode.value) {
                            Mode.Binding -> Unit
                            Mode.Navigation -> {
                                val action = rememberOpenRoomMedia(together, ProfileId.Default, repository, settings, nav)
                                SideEffect { open = action }
                            }
                            Mode.Page -> TogetherPageSync(together, ReaderState(Manga, chapter.value, mode = DbReaderMode.Vertical,
                                load = ReaderLoadState.PagesReady(List(3) { DbPageUrl(url = "/page/$it") })), pages::add, opened::add)
                            Mode.Progress -> TogetherProgressSync(together, Manga, chapter.value, 0, opened::add) {
                                progress += it
                                if (holdProgress) try { awaitCancellation() } finally { progressFinalized = true }
                            }
                            Mode.Playback -> TogetherPlaybackSync(together, Manga, chapter.value, player, false, 1f, opened::add) { playing += it }
                        }
                    }
                }
            }
        }
        suspend fun join(role: String = "participant") {
            client = assertNotNull(together.join(Hub, "ABC")); socket = sockets.receive()
            send("""{"type":"hello","you":{"id":"me","role":"$role"}}"""); media()
        }
        fun media() = send("""{"type":"media","media":${RoomJson.encodeToString(roomMediaFor(Manga, chapter.value))}}""")
        fun send(json: String) { assertTrue(socket.incoming.trySend(Frame.Text(json)).isSuccess); pump() }
        fun mount(next: Mode) { ui { mode.value = next; show.value = true }; pump() }
        fun hide() { ui { show.value = false }; pump() }
        fun changeChapter(next: Chapter) { ui { chapter.value = next }; pump() }
        // Room Flow collection starts after composition; its initial snapshot needs a subsequent
        // frame before the keyed follower effect can run. Deliver frames without draining delays.
        fun pump() = ui { repeat(3) {
            test.testScheduler.runCurrent()
            scene.render(test.testScheduler.currentTime * 1_000_000).close()
            test.testScheduler.runCurrent()
        } }
        fun advance(ms: Long) = ui { test.testScheduler.advanceTimeBy(ms); pump() }
        suspend fun finish() { ui { scene.close() }; together.closeAndJoin(); parent.cancelAndJoin() }
    }

    private class RecordingPlayer : MediaPlayerController {
        val seeks = mutableListOf<Long>()
        var playing = false
        var reads = 0
        var beforePlayingRead: () -> Unit = {}
        override fun load(url: String, headers: Map<String, String>, initialPositionMs: Long) = Unit
        override fun play() { playing = true }
        override fun pause() { playing = false }
        override fun seekTo(positionMs: Long) { seeks += positionMs }
        override fun setPlaybackSpeed(speed: Float) = Unit
        override fun release() = Unit
        override fun currentPositionMs(): Long { reads++; return 0 }
        override fun durationMs() = 0L
        override fun isPlaying(): Boolean { reads++; beforePlayingRead(); return playing }
    }

    private class ControlledSocket(context: CoroutineContext) : DefaultWebSocketSession {
        override val coroutineContext = context + Job(context[Job])
        override var masking = false
        override var maxFrameSize = Long.MAX_VALUE
        override var pingIntervalMillis = -1L
        override var timeoutMillis = 15_000L
        override val incoming = Channel<Frame>(Channel.UNLIMITED)
        override val outgoing = Channel<Frame>(Channel.UNLIMITED)
        override val extensions: List<WebSocketExtension<*>> = emptyList()
        override val closeReason = CompletableDeferred<CloseReason?>()
        init { CoroutineScope(coroutineContext).launch {
            try { awaitCancellation() } finally { incoming.cancel(); outgoing.cancel(); closeReason.complete(null) }
        } }
        override fun start(negotiatedExtensions: List<WebSocketExtension<*>>) = Unit
        val sent = mutableListOf<String>()
        override suspend fun send(frame: Frame) { if (frame is Frame.Text) sent += frame.readText(); outgoing.send(frame) }
        override suspend fun flush() = Unit
        @Deprecated("Overrides deprecated Ktor API")
        override fun terminate() { coroutineContext.cancel() }
    }

    private companion object {
        val Preference = DbSyncPreference(syncId = 1, server = "https://hub.test", authToken = "owner-token", deviceId = "owner-device")
        val Hub = HubSession("https://hub.test", "owner-token", "owner-device")
        val Manga = Manga(1, "Title", link = "/title", description = "", status = Status.Ongoing, itemType = ItemType.Manga,
            source = "source", lang = "en", dateAddedMillis = 0, lastUpdateMillis = 0, sourceId = 42)
        val Chapter = Chapter(1, 1, "Chapter", "/chapter/1")
        fun <T> ui(block: () -> T): T {
            if (SwingUtilities.isEventDispatchThread()) return block()
            val task = FutureTask(block); SwingUtilities.invokeAndWait(task); return task.get()
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherViewModelTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherViewModelTest.kt) · test / fixture · 89 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
25: class TogetherViewModelTest {
29: fun tearDown() = host.close()
32: fun joinConnectsTheRoomAndLeaveClearsIt() = runTest {
53: fun joinWithoutHubAsksToLogInAndDismissClearsTheMessage() = runTest {
69: fun joinFailureBecomesAMessage() = runTest {
80: private fun together(scope: CoroutineScope, engine: (ProfileId) -> ProfileTestEngine) =
83: private fun database() = InMemoryYokanDatabase(emptySnapshot()).also { it.upsertSyncPreference(Preference) }
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherViewModelTest.kt) · SHA-256 `df17eb173eff69f7cdace5905f3dbb241cbf8bdfd7427e65c19b421ab8895c4a`.

### Complete file

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)

package eu.friedcutlet.yokan.ui.screens.together

import eu.friedcutlet.yokan.database.DbSyncPreference
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.emptySnapshot
import eu.friedcutlet.yokan.domain.ProfileId
import eu.friedcutlet.yokan.services.http.ProfileTestEngine
import eu.friedcutlet.yokan.services.together.HubSession
import eu.friedcutlet.yokan.services.together.ProfileTogetherSession
import eu.friedcutlet.yokan.ui.ViewModelTestHost
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.jetbrains.compose.resources.getString
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.together_login_to_join

class TogetherViewModelTest {
    private val host = ViewModelTestHost()

    @AfterTest
    fun tearDown() = host.close()

    @Test
    fun joinConnectsTheRoomAndLeaveClearsIt() = runTest {
        val engine = ProfileTestEngine(host.dispatcher) { awaitCancellation() }
        val together = together(backgroundScope) { engine }
        val vm = host.create { TogetherViewModel(together, { Hub }, host.dispatcher) }

        vm.join("abc")
        runCurrent()

        assertEquals("ABC", vm.state.value.client?.code)
        assertEquals("ABC", vm.state.value.room?.code)
        assertNull(vm.state.value.message)

        vm.leave()
        runCurrent()

        assertNull(together.client.value)
        assertNull(vm.state.value.room)
        assertEquals(1, engine.closeCalls)
    }

    @Test
    fun joinWithoutHubAsksToLogInAndDismissClearsTheMessage() = runTest {
        val together = together(backgroundScope) { error("No hub, no socket") }
        val vm = host.create { TogetherViewModel(together, { null }, host.dispatcher) }

        vm.join("ABC")
        runCurrent()

        assertEquals(getString(Res.string.together_login_to_join), vm.state.value.message)
        assertNull(together.client.value)

        vm.dismissMessage()

        assertNull(vm.state.value.message)
    }

    @Test
    fun joinFailureBecomesAMessage() = runTest {
        val together = together(backgroundScope) { error("Hub unreachable") }
        val vm = host.create { TogetherViewModel(together, { Hub }, host.dispatcher) }

        vm.join("ABC")
        runCurrent()

        assertEquals("Hub unreachable", vm.state.value.message)
        assertNull(vm.state.value.room)
    }

    private fun together(scope: CoroutineScope, engine: (ProfileId) -> ProfileTestEngine) =
        ProfileTogetherSession(ProfileId.Default, database(), scope, engine)

    private fun database() = InMemoryYokanDatabase(emptySnapshot()).also { it.upsertSyncPreference(Preference) }

    private companion object {
        val Preference = DbSyncPreference(syncId = 1, server = "https://hub.test", authToken = "owner-token", deviceId = "owner-device")
        val Hub = HubSession("https://hub.test", "owner-token", "owner-device")
    }
}
```
[complete-source-end]: #

