Prerequisites: authenticated Hub account, owned network calls and reader/player adapters. File workbook.
How to write this chapter
Implement the Together client as protocol state, owned transport, position policy and UI/media bindings. Server-side rooms and a client's current connection are separate lifetimes.
The 20 assigned entries are integrated below at their implementation steps. Every text listing is complete, including imports, helpers and tests. Create the displayed paths in your new project; dependencies imported from other chapters are linked beside the file. Binary assets have direct downloads.
Read each step’s explanation, write its contracts and implementation, then trace the test assertions. The final application graph has dependencies across chapters: the ordering is a construction plan, and a step is not a promise that the whole app compiles before its referenced contracts exist.
Implementation sequence:
- Step 1: Define room values and a pure JSON event reducer.
- Step 2: Own create/join/leave transport and serialize admission.
- Step 3: Calculate expected position and prevent control feedback loops.
- Step 4: Bind room state, actions, chat and reader/player hooks.
- Verification: recreate the full test/fixture listings and run the relevant target tasks. [chapter-content-end]: #
Step 1: define protocol state
Implement RoomModels for room summary, connection, participant/role, media, position, playlist/policy, pending joins, chat and reactions. Implement RoomReducer as a pure fold over JSON events. Preserve hello/approval/denial/closed/error, media/state/playlist, chat/history/reaction and participant/role/policy transitions. Unknown types are ignored where the reference does; malformed required data must not crash unrelated UI state.
Keep protocol schema and JSON field spellings unchanged. Chat retention is bounded. Switching media clears obsolete position. Initial hello establishes identity/role and room state; a pending participant is not automatically authorized to control playback.
Follow the code
The reducer folds server messages into immutable connection/participant/media/chat/playlist state. Hello establishes identity and initial room state; pending admission does not grant control. Media replacement clears obsolete position, and bounded chat/history avoids unbounded retention. Preserve exact protocol fields and unknown-message behavior so one unsupported event does not corrupt unrelated state.
Write these files in this order:
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/RoomModels.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/RoomReducer.kt
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/RoomModels.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines RoomChapter, RoomMedia, RoomUser, RoomParticipant, PlaylistItem, ChatMessage, RoomSummary, RoomRole, parse, RoomConnection and 6 further declarations.
The source describes its contract as:
Wire models for yokan-hub rooms. Field names match
yokan-hub/src/rooms.rs.
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" }
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/RoomReducer.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The reducer is pure protocol interpretation. Keep state-reset and permission transitions visible in tests rather than implementing them as ad hoc UI side effects.
The implementation below defines RoomReducer, reduce, expectedPositionMs, JsonObject.str, JsonElement.participant.
The source describes its contract as:
Pure fold of hub messages into [RoomState]. No I/O, so the whole protocol is unit-testable. Unknown message types are ignored;
burstandpongare handled by [RoomClient] itself.
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,
)
}
}
Check your understanding
Replay hello → pending/approval → media/state → closed sequences. Check permissions, position reset and retained bounded chat at each transition. [chapter-content-end]: #
Step 2: implement client and admission
Build RoomClient HTTP operations and WebSocket connection, authentication, join/create/leave/close, burst handling, heartbeat/pong, reconnect and error state. Reproduce admission serialization so overlapping requests cannot publish the wrong joined room. Capture exact account/server/room identity; account changes cancel the old connection and prevent late creation/join results from becoming current.
Wrap it in ProfileTogetherSession. Session retirement closes network work and joins finalizers. Keep a server-side room's existence distinct from the current client's connection lifecycle. Server limits/host-away behavior in the planning document are protocol expectations; this checkout contains the client, not the Hub implementation.
Follow the code
HTTP admission and WebSocket establishment both carry captured account/server/room identity. Overlapping joins must not publish whichever response happens to finish last. Cancellation closes old connections and joins their jobs; reconnect belongs to the same admitted identity. ProfileTogetherSession wraps these operations so retirement cannot leave an old network callback targeting a new profile.
Write these files in this order:
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/RoomClient.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/ProfileTogetherSession.kt
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/RoomClient.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
Room creation/joining and socket connection are asynchronous admission steps. Preserve their identity checks and serialized publication so late results cannot connect the wrong room/account.
The implementation below defines HubSession, RoomApi, Created, create, info, close, ensureCurrent, errorOf, RoomClient, revoke and 31 further declarations.
The source describes its contract as:
Credentials for one hub; the same ones the sync service stores in
sync_preference.
Cross-chapter imports used by this file: HttpRequest, hubWebSocketBase, nowMillis, PlatformLock. Keep those contracts available as you connect this step.
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("👍", "❤️", "😂", "😮", "😢", "🔥", "👏", "💀")
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/ProfileTogetherSession.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines RoomMediaTarget, Open, NotInLibrary, NoChapters, ProfileTogetherSession, setFollowing, setDriving, RoomAccount, account, currentAccount and 12 further declarations.
The source describes its contract as:
Where following a room's media leads in this profile's library.
Cross-chapter imports used by this file: YokanRepository, DbSettings, ProfileId, YokanDatabase, DbSyncPreference, SyncServerProvider. Keep those contracts available as you connect this step.
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()
}
}
}
}
Check your understanding
Start joins for two rooms, complete them out of order, then change accounts. Only the admitted current room/account may become connected. [chapter-content-end]: #
Step 3: implement position synchronization
Build RoomSync and expected-position calculation with an injectable clock. For anime, account for playing/paused, playback rate and elapsed time; apply the source's correction policy without endless seek feedback. For manga/novels, map the shared position into the appropriate reader units and chapter identity. Do not treat every media's position as milliseconds.
Distinguish locally originated control from incoming state to avoid rebroadcast loops. Honor host/co-host/participant permissions and room/playlist policy. A new media selection cancels pending resolution of the prior one.
Follow the code
Expected anime position depends on whether playback is running, elapsed time and playback rate; paused state does not advance. Manga/novel positions use their own units and chapter identities. Incoming state and locally originated actions are distinguished so applying a remote seek does not rebroadcast it indefinitely. Respect role/playlist policy before issuing control, and cancel resolution for a superseded media selection.
Write these files in this order:
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/RoomSync.kt
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/together/RoomSync.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
Time-based expected position must use a controlled clock and the current media type. Incoming control suppression prevents remote corrections from feeding back as a second local command.
The implementation below defines roomMediaFor, roomShows, announceMedia, reportPlayback, followPlayback, reportPage, followPage, reportProgress, ProgressFollower, follow.
The source describes its contract as:
The room's identity for [manga] / [chapter].
Cross-chapter imports used by this file: Chapter, Manga, MediaPlayerController, nowMillis. Keep those contracts available as you connect this step.
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
}
}
Check your understanding
With an injected clock, compare playing/paused/rate cases. Apply one remote update and verify it does not produce an endless local/remote seek loop. [chapter-content-end]: #
Step 4: connect UI and media hooks
Implement TogetherViewModel, actions, session binding, hooks and screen. Add create/join/list/leave, room status, participants/requests/roles, playback/read controls, playlist operations and chat/reactions according to capability. Use reader/player bindings so an incoming event targets only the currently owned media session.
Follow the code
The ViewModel exposes room/session state and allowed commands, while bindings/hooks connect it to the currently owned reader or player. Render pending/denied/disconnected states distinctly from an empty room. Role/request/playlist/chat actions call the client under the same identity checks. Media hooks should not retain a prior chapter/controller after navigation, even while the room connection remains established.
Write these files in this order:
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherViewModel.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherSession.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherActions.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherUiBinding.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherHooks.ktcomposeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherScreen.kt
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherViewModel.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines TogetherState, TogetherViewModel, join, leave, setFollowing, setDriving, dismissMessage, showMessage.
The source describes its contract as:
The client [room] belongs to; room commands go to it.
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) }
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherSession.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines TogetherSession, offerCode, takePendingCode.
The source describes its contract as:
Room code handed in by a deep link; the Together screen's view model joins it.
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 }
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherActions.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines TogetherActions, startRoom, addToRoom.
The source describes its contract as:
Shared by the title menu: start a room, or add/suggest the title to the current one.
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."
}
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherUiBinding.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines roomDrives, TogetherUiBinding, active, current, drives, followsMedia, follows, close.
The source describes its contract as:
Captured room capability. Old clients, disposed screens and stale room snapshots fail closed.
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() }
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherHooks.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines rememberRoomState, FollowRoomMedia, rememberOpenRoomMedia, admitted, rememberTogetherUiBinding, TogetherPlaybackSync, TogetherPageSync, TogetherProgressSync.
The source describes its contract as:
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.
Cross-chapter imports used by this file: Chapter, Manga, ProfileSession, ProfileId, SettingsStore, YokanRepository. Keep those contracts available as you connect this step.
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)
}
}
Write composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherScreen.kt
Create this path in your reconstruction project. Source set: commonMain. Exact file download.
The implementation below defines TogetherRoute, TogetherScreen, InfoBanner, JoinRoomPane, WaitingPane, ClosedPane, RoomPane, ChatPane, PlaylistPane, PlaylistRow and 2 further declarations.
The source describes its contract as:
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.
Cross-chapter imports used by this file: YokanRuntime, Navigator. Keep those contracts available as you connect this step.
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)) }
}
}
Check your understanding
Change the current media owner while a room event is queued. Confirm it is applied only to the matching session, with controls hidden/disabled according to actual role policy. [chapter-content-end]: #
Recreate the tests and verify the chapter
Recreate reducer, API/admission, timing and Together account/profile/UI lifecycle fixtures. Use a controlled clock and deferred transport to test races deterministically. Finally connect two real clients to a compatible Hub; this repository supplies the client and cannot establish server availability from reducer tests.
These are source tests to reproduce and run in your reconstruction. Their inclusion here is not a claim that application/native/device tests were executed while writing the guide.
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/ProfileTogetherSessionTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines ProfileTogetherSessionTest, database.
Read the setup, action and assertions in these cases before implementing their production paths:
connectionUsesCapturedCredentialsAndLeavePreservesOwnerreplacementJoinsOldSocketBeforeAllocatingOrPublishingAnotherretirementJoinsSocketFinalizerThenReleasesTransportAndStatestaleAccountOrOtherSyncProviderCannotAllocateARoomTransportexpiredAndRetiredCallsCannotReadCredentialsOrDispatchcallerExpiryDuringReplacementJoinsCleanupAndDoesNotRetireOwnerindependentOwnersRetainTheirRoomStateAndCleanupTargets
Cross-chapter imports used by this file: ProfileId, DbSyncPreference, InMemoryYokanDatabase, SyncServerProvider, emptySnapshot, ProfileTestEngine. Keep those contracts available as you connect this step.
@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")
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/RoomApiTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines RoomApiTest.
Read the setup, action and assertions in these cases before implementing their production paths:
allRestMethodsRejectRevokedAccountsBeforeDispatchallRestMethodsRejectResponsesAfterRevocationBeforeParsingOrReportingErrorsstandaloneRestCompatibilityRetainsPolicyHeadersCodesAndErrors
Cross-chapter imports used by this file: HttpResponse, RecordingHttpService. Keep those contracts available as you connect this step.
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")
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/RoomReducerTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines RoomReducerTest, RoomState.apply, helloSeedsRoleMediaAndPolicies, joinFlowMovesUsersFromPendingToParticipants, pendingJoinerBecomesParticipantOnApproved, deniedAndClosedAreTerminal, playlistSnapshotAndMediaSwitch, chatHistoryLiveMessagesAndReactionToggle, hostAwayAndPolicyChanges, expectedPositionExtrapolatesWhilePlaying.
Read the setup, action and assertions in these cases before implementing their production paths:
helloSeedsRoleMediaAndPoliciesjoinFlowMovesUsersFromPendingToParticipantspendingJoinerBecomesParticipantOnApproveddeniedAndClosedAreTerminalplaylistSnapshotAndMediaSwitchchatHistoryLiveMessagesAndReactionTogglehostAwayAndPolicyChangesexpectedPositionExtrapolatesWhilePlaying
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))
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/RoomSyncTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines RoomSyncTest, pageFollowerClampsToTheLocalChapterAndSkipsOtherMediaOrDetachedFollowers, progressFollowerIgnoresJitterAndNonFiniteValues, pausedHostSeeksTheFollowerOnceWithoutTogglingPlayback, room, RecordingPlayer, load, play, pause, seekTo and 5 further declarations.
Read the setup, action and assertions in these cases before implementing their production paths:
pageFollowerClampsToTheLocalChapterAndSkipsOtherMediaOrDetachedFollowersprogressFollowerIgnoresJitterAndNonFiniteValuespausedHostSeeksTheFollowerOnceWithoutTogglingPlayback
Cross-chapter imports used by this file: Chapter, ItemType, Manga, Status, MediaPlayerController. Keep those contracts available as you connect this step.
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")
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/TogetherAccountLifecycleTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines TogetherAccountLifecycleTest, close, TestScope.fixture, Fixture, join, finish, ControlledSocket, start, send, flush and 2 further declarations.
The source describes its contract as:
A real Ktor upgrade with controlled frame channels instead of a remote socket.
Read the setup, action and assertions in these cases before implementing their production paths:
tokenChangeRevokesRoomAndJoinsFinalizersBeforeReplacementAllocationlogoutProviderServerDeviceAndSelectionChangesEachRevokeTheRoomirrelevantSettingsAndNormalizedServerChangesKeepTheRoomretainedClientCannotReconnectEvenWhenCredentialsAreRestoredaccountChangeBeforeQueuedHandshakePreventsTransportDispatchqueuedCommandsAndIncomingMessagesCannotUseAChangedAccountfailedRevocationCleanupIsRetriedBeforeAnotherRoomIsAllocatedqueuedAccountWatcherCannotRevokeAReplacementForTheLatestAccountchangingOneAccountDoesNotRevokeAnotherOwner
Cross-chapter imports used by this file: ProfileId, DbSyncPreference, InMemoryYokanDatabase, SyncServerProvider, emptySnapshot, ProfileTestEngine. Keep those contracts available as you connect this step.
@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")
}
}
Write composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/together/TogetherCreationLifecycleTest.kt
Create this path in your reconstruction project. Source set: commonTest. Exact file download.
The implementation below defines TogetherCreationLifecycleTest, database.
Read the setup, action and assertions in these cases before implementing their production paths:
creationUsesCapturedCredentialsAndReturnsTheJoinedClientchangedAccountDuringCreationCannotAllocateAJoinedRoomcontrollerRetirementJoinsRestFinalizersThroughTheProfileHttpWrappercallerExpiryJoinsCreationWithoutRetiringItsControllerOrSiblingOwnerqueuedAndAlreadyExpiredCreationCannotDispatchcreationFailurePreservesAnExistingRoomAndCanBeRetriedpreferenceChangeDuringOldRoomCleanupCannotJoinTheCreatedRoomtitleActionSuppressesLateNavigationAndDeliversItsOwnSuccessfulRoomlateNonCancellableResponseCannotJoinAfterOwnerRetirementunrelatedBookkeepingDuringCreationPreservesTheAccount
Cross-chapter imports used by this file: ProfileId, DefaultYokanRepository, DbManga, DbSyncPreference, InMemoryYokanDatabase, SyncServerProvider. Keep those contracts available as you connect this step.
@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\"}")
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/together/RoomClientAdmissionConcurrencyTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines RoomClientAdmissionConcurrencyTest.
Read the setup, action and assertions in these cases before implementing their production paths:
concurrentCloseDoesNotWaitForABlockedCredentialRead
Cross-chapter imports used by this file: ProfileTestEngine. Keep those contracts available as you connect this step.
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)
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherHooksLifecycleTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines TogetherHooksLifecycleTest, Mode, Fixture, join, media, send, mount, hide, changeChapter, pump and 17 further declarations.
Read the setup, action and assertions in these cases before implementing their production paths:
disposedBindingCannotApplyOrControlARoomAndRemountGetsANewCapabilitychangedCredentialsRejectRetainedBindingsBeforeTheWatcherRunssameCodeReplacementInvalidatesOldBindingAndLeaveTargetsOnlyCapturedClientpageFollowingClampsAndStopsWhenDetachedDisposedOrAccountChangesstalePositionIsRejectedButUnrelatedRoomMessagesDoNotInvalidateFollowingnovelUpdatesResetOnChapterAndRoomReplacementAndRejectNonFiniteProgressnovelFollowerScrollRemainsAChildOfTheDisposedEffectplaybackConvergesThenStopsReadingTheControllerAfterDisposalfollowMediaUsesCapturedControllerAndDoesNotOpenAfterDetachingdrivingTracksCapturedCoHostControlsAndRejectsClosedRoomsnavigationCapturesLibraryAndExpiresOnDisposalAndSameMediaReplacementnavigationRejectsSupersededMediaAndImmediateAccountRevocationstoppedLifecycleBlocksRetainedNavigationAndResumeCreatesFreshAdmissiondisposedHostCannotSendDebouncedNovelProgressaccountRevokedByPlayerReadCannotIssuePlayOrFollowerState
Cross-chapter imports used by this file: DefaultYokanRepository, SettingsStore, DbManga, DbChapter, Navigator, Route. Keep those contracts available as you connect this step.
@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()
}
}
}
Write composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/together/TogetherViewModelTest.kt
Create this path in your reconstruction project. Source set: desktopTest. Exact file download.
The implementation below defines TogetherViewModelTest, tearDown, joinConnectsTheRoomAndLeaveClearsIt, joinWithoutHubAsksToLogInAndDismissClearsTheMessage, joinFailureBecomesAMessage, together, database.
Read the setup, action and assertions in these cases before implementing their production paths:
joinConnectsTheRoomAndLeaveClearsItjoinWithoutHubAsksToLogInAndDismissClearsTheMessagejoinFailureBecomesAMessage
Cross-chapter imports used by this file: DbSyncPreference, InMemoryYokanDatabase, emptySnapshot, ProfileId, ProfileTestEngine, ViewModelTestHost. Keep those contracts available as you connect this step.
@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")
}
}
Completion record
- [ ] Every implementation/configuration and required asset shown above is present at its displayed path.
- [ ] Cross-chapter imports resolve against the intended contracts and platform source sets.
- [ ] The tests for this chapter pass in the rebuilt app; record the command, platform and result.
- [ ] Native, device, browser and live-service checks have evidence or an explicit “not run” entry. [chapter-content-end]: #
Gate: replay fixture message sequences into the reducer, test denied/pending/closed/reconnect states, overlapping joins and account switches. Run Room API/reducer/sync and Together account/creation/profile/UI lifecycle tests. Then test two real clients against a compatible Hub; matching reducer tests alone does not establish server availability or timing behavior.