From c83375079c7f46939ec10990802b1013b1ad3842 Mon Sep 17 00:00:00 2001 From: aharonamir Date: Sun, 29 Nov 2026 22:33:25 +0200 Subject: [PATCH 01/58] Add the sync op log schema, model, stores and service Sync v0 needs a per-member append-only log before any client can exchange turns. V10 adds sync_heads and sync_ops with the board's forced-RLS household policy, a partial unique turn index and a pull index; appends lock the head row so one household's seqs have no gap, a replayed op id is a duplicate and a turn lands once per thread. The service validates the batch shape and caps before the store writes anything, and pull serves a client-owned cursor with a 1..200 page. The in-memory store keeps route tests database-free. Part of #32 --- .../com/hopa/backend/store/PgSyncStore.kt | 224 ++++++++++++++++++ .../hopa/backend/sync/InMemorySyncStore.kt | 126 ++++++++++ .../kotlin/com/hopa/backend/sync/NewSyncOp.kt | 15 ++ .../kotlin/com/hopa/backend/sync/SyncAck.kt | 7 + .../kotlin/com/hopa/backend/sync/SyncOp.kt | 21 ++ .../kotlin/com/hopa/backend/sync/SyncPage.kt | 7 + .../com/hopa/backend/sync/SyncResult.kt | 10 + .../com/hopa/backend/sync/SyncService.kt | 85 +++++++ .../kotlin/com/hopa/backend/sync/SyncStore.kt | 40 ++++ .../main/resources/db/migration/V10__sync.sql | 77 ++++++ .../com/hopa/backend/store/V10SchemaTest.kt | 116 +++++++++ .../com/hopa/backend/sync/PgSyncStoreTest.kt | 33 +++ .../com/hopa/backend/sync/SyncServiceTest.kt | 139 +++++++++++ .../hopa/backend/sync/SyncStoreContract.kt | 178 ++++++++++++++ 14 files changed, 1078 insertions(+) create mode 100644 services/backend/src/main/kotlin/com/hopa/backend/store/PgSyncStore.kt create mode 100644 services/backend/src/main/kotlin/com/hopa/backend/sync/InMemorySyncStore.kt create mode 100644 services/backend/src/main/kotlin/com/hopa/backend/sync/NewSyncOp.kt create mode 100644 services/backend/src/main/kotlin/com/hopa/backend/sync/SyncAck.kt create mode 100644 services/backend/src/main/kotlin/com/hopa/backend/sync/SyncOp.kt create mode 100644 services/backend/src/main/kotlin/com/hopa/backend/sync/SyncPage.kt create mode 100644 services/backend/src/main/kotlin/com/hopa/backend/sync/SyncResult.kt create mode 100644 services/backend/src/main/kotlin/com/hopa/backend/sync/SyncService.kt create mode 100644 services/backend/src/main/kotlin/com/hopa/backend/sync/SyncStore.kt create mode 100644 services/backend/src/main/resources/db/migration/V10__sync.sql create mode 100644 services/backend/src/test/kotlin/com/hopa/backend/store/V10SchemaTest.kt create mode 100644 services/backend/src/test/kotlin/com/hopa/backend/sync/PgSyncStoreTest.kt create mode 100644 services/backend/src/test/kotlin/com/hopa/backend/sync/SyncServiceTest.kt create mode 100644 services/backend/src/test/kotlin/com/hopa/backend/sync/SyncStoreContract.kt diff --git a/services/backend/src/main/kotlin/com/hopa/backend/store/PgSyncStore.kt b/services/backend/src/main/kotlin/com/hopa/backend/store/PgSyncStore.kt new file mode 100644 index 000000000..2e99b07a1 --- /dev/null +++ b/services/backend/src/main/kotlin/com/hopa/backend/store/PgSyncStore.kt @@ -0,0 +1,224 @@ +package com.hopa.backend.store + +import com.hopa.backend.sync.NewSyncOp +import com.hopa.backend.sync.SyncAck +import com.hopa.backend.sync.SyncConflict +import com.hopa.backend.sync.SyncOp +import com.hopa.backend.sync.SyncService +import com.hopa.backend.sync.SyncStore +import com.hopa.backend.sync.bodyHash +import com.hopa.backend.sync.hex +import java.sql.Connection +import java.sql.SQLException +import java.sql.Timestamp +import java.time.Instant + +/** + * The sync op log in Postgres (V10). Every statement runs in a household + * transaction, so the policies decide what this repository can see. + * + * An append first locks `sync_heads`, inserting the row at 0 when it is missing. + * The lock serializes appends of one household, so the op-id check that follows + * sees every op committed before it and seqs are handed out one at a time. A + * duplicated op id writes nothing and burns no seq; another body under the same + * op id, or a turn already in its thread, is a [SyncConflict]. + */ +class PgSyncStore( + private val db: Database, + private val clock: () -> Long = System::currentTimeMillis, +) : SyncStore { + override fun append(householdId: String, memberId: String, deviceId: String, op: NewSyncOp): SyncAck = + appendBatch(householdId, memberId, deviceId, listOf(op)).single() + + override fun appendBatch( + householdId: String, + memberId: String, + deviceId: String, + ops: List, + ): List { + checkBatch(ops) + if (ops.isEmpty()) return emptyList() + return try { + db.tenant(householdId) { connection -> + appendAll(connection, householdId, memberId, deviceId, ops) + } + } catch (problem: SQLException) { + if (problem.sqlState == UNIQUE_VIOLATION) { + throw SyncConflict("the turn is already stored in its thread") + } + throw problem + } + } + + override fun opsAfter(householdId: String, memberId: String, after: Long, limit: Int): List = + db.tenant(householdId) { connection -> + connection.prepareStatement( + """ + select seq, op_id, kind, thread_id, turn_id, from_device, member_id, body, client_at, created_at + from sync_ops + where household_id = ?::uuid and member_id = ?::uuid and seq > ? + order by seq + limit ? + """.trimIndent(), + ).use { + it.setString(1, householdId) + it.setString(2, memberId) + it.setLong(3, after) + it.setInt(4, limit) + it.executeQuery().use { rows -> + buildList { + while (rows.next()) { + add( + SyncOp( + seq = rows.getLong(1), + opId = rows.getString(2), + kind = rows.getString(3), + threadId = rows.getString(4), + turnId = rows.getString(5), + fromDevice = rows.getString(6), + memberId = rows.getString(7), + body = rows.getBytes(8), + clientAt = rows.getLong(9), + createdAt = rows.getTimestamp(10).time, + ), + ) + } + } + } + } + } + + override fun head(householdId: String): Long = db.tenant(householdId) { connection -> + connection.prepareStatement( + "select last_seq from sync_heads where household_id = ?::uuid", + ).use { + it.setString(1, householdId) + it.executeQuery().use { rows -> if (rows.next()) rows.getLong(1) else 0L } + } + } + + private fun appendAll( + connection: Connection, + householdId: String, + memberId: String, + deviceId: String, + ops: List, + ): List { + var head = lockedHead(connection, householdId) + val createdAt = timestamp(clock()) + val acks = ops.map { op -> + val existing = findByOpId(connection, householdId, op.opId) + if (existing != null) { + if (existing.bodyHashHex != hex(bodyHash(op.body))) { + throw SyncConflict("the op id is already stored with another body") + } + SyncAck(op.opId, existing.seq, duplicate = true) + } else { + head += 1 + insert(connection, householdId, head, memberId, deviceId, op, createdAt) + SyncAck(op.opId, head, duplicate = false) + } + } + if (acks.any { !it.duplicate }) { + connection.prepareStatement( + "update sync_heads set last_seq = ? where household_id = ?::uuid", + ).use { + it.setLong(1, head) + it.setString(2, householdId) + it.executeUpdate() + } + } + return acks + } + + /** + * The household's last seq, with its row locked until commit. A missing row + * is inserted at 0; `do nothing` on a concurrent first append makes the + * second one wait for the winner, so both then see the same row. + */ + private fun lockedHead(connection: Connection, householdId: String): Long { + headForUpdate(connection, householdId)?.let { return it } + connection.prepareStatement( + "insert into sync_heads(household_id, last_seq) values (?::uuid, 0) on conflict (household_id) do nothing", + ).use { + it.setString(1, householdId) + it.executeUpdate() + } + return headForUpdate(connection, householdId) ?: 0L + } + + private fun headForUpdate(connection: Connection, householdId: String): Long? = + connection.prepareStatement( + "select last_seq from sync_heads where household_id = ?::uuid for update", + ).use { + it.setString(1, householdId) + it.executeQuery().use { rows -> if (rows.next()) rows.getLong(1) else null } + } + + private class Existing(val seq: Long, val bodyHashHex: String) + + private fun findByOpId(connection: Connection, householdId: String, opId: String): Existing? = + connection.prepareStatement( + "select seq, encode(body_hash, 'hex') from sync_ops where household_id = ?::uuid and op_id = ?", + ).use { + it.setString(1, householdId) + it.setString(2, opId) + it.executeQuery().use { rows -> + if (rows.next()) Existing(rows.getLong(1), rows.getString(2)) else null + } + } + + private fun insert( + connection: Connection, + householdId: String, + seq: Long, + memberId: String, + deviceId: String, + op: NewSyncOp, + createdAt: Timestamp, + ) { + connection.prepareStatement( + """ + insert into sync_ops(household_id, seq, op_id, kind, thread_id, turn_id, from_device, member_id, + body, body_hash, size, client_at, created_at) + values (?::uuid, ?, ?, ?, ?, ?, ?::uuid, ?::uuid, ?, ?, ?, ?, ?) + """.trimIndent(), + ).use { + it.setString(1, householdId) + it.setLong(2, seq) + it.setString(3, op.opId) + it.setString(4, op.kind) + it.setString(5, op.threadId) + it.setString(6, op.turnId) + it.setString(7, deviceId) + it.setString(8, memberId) + it.setBytes(9, op.body) + it.setBytes(10, bodyHash(op.body)) + it.setInt(11, op.body.size) + it.setLong(12, op.clientAt) + it.setTimestamp(13, createdAt) + it.executeUpdate() + } + } + + private fun checkBatch(ops: List) { + require(ops.size <= SyncService.MAX_OPS_PER_PUSH) { + "a push carries at most ${SyncService.MAX_OPS_PER_PUSH} ops" + } + for (op in ops) { + require(op.body.size >= SyncService.MIN_OP_BYTES) { + "ciphertext is shorter than IV and tag" + } + require(op.body.size <= SyncService.MAX_OP_BYTES) { + "ciphertext is larger than ${SyncService.MAX_OP_BYTES} bytes" + } + } + } + + private fun timestamp(millis: Long): Timestamp = Timestamp.from(Instant.ofEpochMilli(millis)) + + private companion object { + /** `unique_violation`: the op log's op-id or turn index refused the row. */ + const val UNIQUE_VIOLATION = "23505" + } +} diff --git a/services/backend/src/main/kotlin/com/hopa/backend/sync/InMemorySyncStore.kt b/services/backend/src/main/kotlin/com/hopa/backend/sync/InMemorySyncStore.kt new file mode 100644 index 000000000..fff7b1eec --- /dev/null +++ b/services/backend/src/main/kotlin/com/hopa/backend/sync/InMemorySyncStore.kt @@ -0,0 +1,126 @@ +package com.hopa.backend.sync + +/** + * The op log for protocol tests. One lock per store keeps the seq, the op-id + * index and the turn index consistent, as the head row and the unique indexes do + * in Postgres. A batch is resolved in full before anything is written, so a + * conflict halfway leaves no trace, as a rolled-back transaction does not. + */ +class InMemorySyncStore( + private val clock: () -> Long = System::currentTimeMillis, +) : SyncStore { + private class Stored(val op: SyncOp, val bodyHashHex: String) + + private class Pending(val op: NewSyncOp, val seq: Long, val bodyHashHex: String, val turnKey: String?) + + private val lock = Any() + private val heads = mutableMapOf() + private val log = mutableMapOf>() + private val byOpId = mutableMapOf() + private val turns = mutableSetOf() + + override fun append(householdId: String, memberId: String, deviceId: String, op: NewSyncOp): SyncAck = + appendBatch(householdId, memberId, deviceId, listOf(op)).single() + + override fun appendBatch( + householdId: String, + memberId: String, + deviceId: String, + ops: List, + ): List { + checkBatch(ops) + if (ops.isEmpty()) return emptyList() + return synchronized(lock) { appendLocked(householdId, memberId, deviceId, ops) } + } + + override fun opsAfter(householdId: String, memberId: String, after: Long, limit: Int): List = + synchronized(lock) { + log[householdId].orEmpty() + .asSequence() + .map { it.op } + .filter { it.memberId == memberId && it.seq > after } + .take(limit) + .toList() + } + + override fun head(householdId: String): Long = synchronized(lock) { heads[householdId] ?: 0L } + + private fun appendLocked( + householdId: String, + memberId: String, + deviceId: String, + ops: List, + ): List { + var head = heads[householdId] ?: 0L + val pending = mutableListOf() + val pendingByOpId = mutableMapOf() + val pendingTurns = mutableSetOf() + val acks = ops.map { op -> + val key = "$householdId/${op.opId}" + val hash = hex(bodyHash(op.body)) + val stored = byOpId[key] + val waiting = pendingByOpId[key] + when { + stored != null -> duplicate(stored.op.seq, stored.bodyHashHex, hash, op.opId) + waiting != null -> duplicate(waiting.seq, waiting.bodyHashHex, hash, op.opId) + else -> { + val turnKey = turnKey(householdId, op) + if (turnKey != null && (turnKey in turns || !pendingTurns.add(turnKey))) { + throw SyncConflict("the turn is already stored in its thread") + } + head += 1 + val next = Pending(op, head, hash, turnKey) + pending += next + pendingByOpId[key] = next + SyncAck(op.opId, head, duplicate = false) + } + } + } + // Nothing was written above: a conflict has left the log untouched. + val createdAt = clock() + for (next in pending) { + val stored = Stored( + SyncOp( + seq = next.seq, + opId = next.op.opId, + kind = next.op.kind, + threadId = next.op.threadId, + turnId = next.op.turnId, + fromDevice = deviceId, + memberId = memberId, + body = next.op.body.copyOf(), + clientAt = next.op.clientAt, + createdAt = createdAt, + ), + next.bodyHashHex, + ) + log.getOrPut(householdId) { mutableListOf() } += stored + byOpId["$householdId/${next.op.opId}"] = stored + next.turnKey?.let { turns += it } + } + if (pending.isNotEmpty()) heads[householdId] = head + return acks + } + + private fun duplicate(seq: Long, storedHash: String, sentHash: String, opId: String): SyncAck { + if (storedHash != sentHash) throw SyncConflict("the op id is already stored with another body") + return SyncAck(opId, seq, duplicate = true) + } + + private fun turnKey(householdId: String, op: NewSyncOp): String? = + if (op.kind == SyncService.KIND_TURN_APPEND) "$householdId/${op.threadId}/${op.turnId}" else null + + private fun checkBatch(ops: List) { + require(ops.size <= SyncService.MAX_OPS_PER_PUSH) { + "a push carries at most ${SyncService.MAX_OPS_PER_PUSH} ops" + } + for (op in ops) { + require(op.body.size >= SyncService.MIN_OP_BYTES) { + "ciphertext is shorter than IV and tag" + } + require(op.body.size <= SyncService.MAX_OP_BYTES) { + "ciphertext is larger than ${SyncService.MAX_OP_BYTES} bytes" + } + } + } +} diff --git a/services/backend/src/main/kotlin/com/hopa/backend/sync/NewSyncOp.kt b/services/backend/src/main/kotlin/com/hopa/backend/sync/NewSyncOp.kt new file mode 100644 index 000000000..c5d2f9ac1 --- /dev/null +++ b/services/backend/src/main/kotlin/com/hopa/backend/sync/NewSyncOp.kt @@ -0,0 +1,15 @@ +package com.hopa.backend.sync + +/** + * What a device pushes: an op id it chose, one of the two op kinds, the thread + * (and, for a turn, the turn) it writes, the sealed body and the author's clock + * reading. The actor and the seq are the server's to fill in. + */ +class NewSyncOp( + val opId: String, + val kind: String, + val threadId: String, + val turnId: String?, + val body: ByteArray, + val clientAt: Long, +) diff --git a/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncAck.kt b/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncAck.kt new file mode 100644 index 000000000..c2ebc8ca1 --- /dev/null +++ b/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncAck.kt @@ -0,0 +1,7 @@ +package com.hopa.backend.sync + +/** + * What one pushed op got: the seq it is stored at, and whether the server had + * already stored it (a replay is acked with its first seq and writes nothing). + */ +data class SyncAck(val opId: String, val seq: Long, val duplicate: Boolean) diff --git a/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncOp.kt b/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncOp.kt new file mode 100644 index 000000000..0be63ce14 --- /dev/null +++ b/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncOp.kt @@ -0,0 +1,21 @@ +package com.hopa.backend.sync + +/** + * One stored op: the server-assigned [seq], the client ids it names, the + * attested actor and the ciphertext the server never read. + * + * [createdAt] is the server's time (millis), the only clock the merge trusts; + * [clientAt] is the author's, kept for display and advisory ordering. + */ +class SyncOp( + val seq: Long, + val opId: String, + val kind: String, + val threadId: String, + val turnId: String?, + val fromDevice: String, + val memberId: String, + val body: ByteArray, + val clientAt: Long, + val createdAt: Long, +) diff --git a/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncPage.kt b/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncPage.kt new file mode 100644 index 000000000..e34d490eb --- /dev/null +++ b/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncPage.kt @@ -0,0 +1,7 @@ +package com.hopa.backend.sync + +/** + * One pull: the ops after the client's cursor, whether more follow the last one, + * and the household head so the client knows how far it has read. + */ +data class SyncPage(val ops: List, val hasMore: Boolean, val head: Long) diff --git a/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncResult.kt b/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncResult.kt new file mode 100644 index 000000000..fcb7d5e96 --- /dev/null +++ b/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncResult.kt @@ -0,0 +1,10 @@ +package com.hopa.backend.sync + +import com.hopa.backend.protocol.GatewayError + +/** A sync call's answer: a value, or a stable error code the client acts on. */ +sealed interface SyncResult { + data class Ok(val value: T) : SyncResult + + data class Failed(val error: GatewayError) : SyncResult +} diff --git a/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncService.kt b/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncService.kt new file mode 100644 index 000000000..04c1fbc5b --- /dev/null +++ b/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncService.kt @@ -0,0 +1,85 @@ +package com.hopa.backend.sync + +import com.hopa.backend.auth.DeviceIdentity +import com.hopa.backend.protocol.GatewayError + +/** + * Sync v0's rules on top of [SyncStore]. + * + * A push is one batch of at most [MAX_OPS_PER_PUSH] ops from one device; the + * whole batch is refused before any write if one op is malformed. A pull pages + * the caller's member log after a client-owned cursor and clamps the page to + * [MAX_PAGE]. The household and member always come from [DeviceIdentity], never + * from the request. + */ +class SyncService(private val store: SyncStore) { + fun push(identity: DeviceIdentity, ops: List): SyncResult> { + if (ops.isEmpty()) return schema("a push carries at least one op") + if (ops.size > MAX_OPS_PER_PUSH) return schema("a push carries at most $MAX_OPS_PER_PUSH ops") + for (op in ops) { + problem(op)?.let { return schema(it) } + } + return try { + SyncResult.Ok(store.appendBatch(identity.householdId, identity.memberId, identity.deviceId, ops)) + } catch (_: SyncConflict) { + SyncResult.Failed( + GatewayError("E_CONFLICT", "op id already stored with another body, or the turn is already stored"), + ) + } + } + + fun pull(identity: DeviceIdentity, after: Long, limit: Int? = null): SyncResult { + if (after < 0) return schema("after must not be negative") + val pageSize = when (limit) { + null, 0 -> MAX_PAGE + else -> limit.coerceIn(1, MAX_PAGE) + } + val fetched = store.opsAfter(identity.householdId, identity.memberId, after, pageSize + 1) + return SyncResult.Ok( + SyncPage( + ops = fetched.take(pageSize), + hasMore = fetched.size > pageSize, + head = store.head(identity.householdId), + ), + ) + } + + /** The household's latest seq, for the push acknowledgement. */ + fun head(identity: DeviceIdentity): Long = store.head(identity.householdId) + + private fun problem(op: NewSyncOp): String? = when { + op.kind !in KINDS -> "unknown op kind" + op.threadId.isBlank() -> "threadId must not be blank" + op.kind == KIND_TURN_APPEND && op.turnId.isNullOrBlank() -> "a turn needs a turnId" + op.kind == KIND_THREAD_UPSERT && op.turnId != null -> "a thread upsert carries no turnId" + op.body.size < MIN_OP_BYTES -> "ciphertext is shorter than IV and tag" + op.body.size > MAX_OP_BYTES -> "ciphertext is larger than $MAX_OP_BYTES bytes" + op.clientAt < 0 -> "clientAt must not be negative" + else -> null + } + + private fun schema(message: String) = SyncResult.Failed(GatewayError("E_SCHEMA", message)) + + companion object { + const val KIND_THREAD_UPSERT = "thread.upsert" + + const val KIND_TURN_APPEND = "turn.append" + + val KINDS = setOf(KIND_THREAD_UPSERT, KIND_TURN_APPEND) + + /** Ops one push may carry. */ + const val MAX_OPS_PER_PUSH = 100 + + /** IV (12) and GCM tag (16): the shortest well-formed ciphertext. */ + const val MIN_OP_BYTES = 28 + + /** Raw ciphertext cap of one op. */ + const val MAX_OP_BYTES = 64 * 1024 + + /** Cap of the whole push request body. */ + const val MAX_BODY_BYTES = 256 * 1024 + + /** Ops one pull may return. */ + const val MAX_PAGE = 200 + } +} diff --git a/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncStore.kt b/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncStore.kt new file mode 100644 index 000000000..1c94ea5f2 --- /dev/null +++ b/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncStore.kt @@ -0,0 +1,40 @@ +package com.hopa.backend.sync + +import java.security.MessageDigest + +/** + * The household's op log. Every call is scoped to one household and one member: + * a member's devices share a log, and a member of the same household reads none + * of another member's ops. The seq counter is the household's, so the log a + * member reads has gaps where other members wrote. + */ +interface SyncStore { + /** Appends at the household's next seq. Same opId returns the stored seq as duplicate. */ + fun append(householdId: String, memberId: String, deviceId: String, op: NewSyncOp): SyncAck + + /** Ops of [memberId] with seq > after, ascending, at most limit. */ + fun opsAfter(householdId: String, memberId: String, after: Long, limit: Int): List + + /** Latest seq written in the household (0 when none). */ + fun head(householdId: String): Long + + /** + * Appends [ops] for one device in order. Returns the acks in the same order. + * Enforces the per-push cap and body limits before any write; a rejected batch + * writes nothing. + */ + fun appendBatch(householdId: String, memberId: String, deviceId: String, ops: List): List +} + +/** + * The op id is already stored with another body, or the turn is already in its + * thread. Thrown by a [SyncStore] so a rejected batch rolls back whole; the + * service turns it into `E_CONFLICT`. + */ +class SyncConflict(message: String) : RuntimeException(message) + +/** SHA-256 of an op body: what a replay compares, and what `body_hash` stores. */ +internal fun bodyHash(body: ByteArray): ByteArray = MessageDigest.getInstance("SHA-256").digest(body) + +/** Lower-case hex, in the form Postgres `encode(body_hash, 'hex')` returns. */ +internal fun hex(bytes: ByteArray): String = bytes.joinToString("") { "%02x".format(it) } diff --git a/services/backend/src/main/resources/db/migration/V10__sync.sql b/services/backend/src/main/resources/db/migration/V10__sync.sql new file mode 100644 index 000000000..8c8d1eb46 --- /dev/null +++ b/services/backend/src/main/resources/db/migration/V10__sync.sql @@ -0,0 +1,77 @@ +-- Schema v10: sync v0, the per-member op log that lets a phone and a PC +-- exchange conversation turns (#32 Phase 2). +-- +-- The server stores op bodies as ciphertext only and never reads them. The +-- plaintext columns are metadata: the op kind, the client ids it names, the +-- server-attested actor, a body hash and size, the client's clock reading and +-- the server's own time. `op_id`, `thread_id` and `turn_id` are text because +-- they are client ids (`c-…`, `m-…`), not UUIDs. +-- +-- sync_heads holds the last seq per household; an append locks that row, hands +-- out the next seq and updates it in one tenant transaction, so the seqs of one +-- household have no gap and no duplicate. One counter is shared by every member, +-- so a member reading only its own ops sees the gaps the other members' ops +-- leave; that is a recorded metadata leak, as on the family board. +-- +-- The cursor is client-owned (passed as `after=`), so there is no cursor table. +-- A turn is stored once per thread: the partial unique index is the guard, and +-- a violation is answered as `E_CONFLICT`, never as a 500. +-- +-- from_device and member_id are server-attested. They reference their rows +-- without a cascade: devices are tombstoned, not deleted, and an append-only log +-- must not lose entries when a device goes away. + +create table sync_heads ( + household_id uuid primary key references households (id) on delete cascade, + last_seq bigint not null check (last_seq >= 0) +); + +create table sync_ops ( + household_id uuid not null references households (id) on delete cascade, + seq bigint not null check (seq > 0), + op_id text not null, + kind text not null check (kind in ('thread.upsert', 'turn.append')), + thread_id text not null, + turn_id text null, + from_device uuid not null references devices (id), + member_id uuid not null references members (id), + body bytea not null, + body_hash bytea not null check (octet_length(body_hash) = 32), + size int not null check (size >= 0), + client_at bigint not null, + created_at timestamptz not null default now(), + primary key (household_id, seq), + unique (household_id, op_id) +); + +create unique index sync_ops_turn_idx + on sync_ops (household_id, thread_id, turn_id) + where kind = 'turn.append' and turn_id is not null; + +create index sync_ops_pull_idx + on sync_ops (household_id, member_id, seq); + +alter table sync_heads enable row level security; +alter table sync_heads force row level security; +create policy sync_heads_own on sync_heads + using (household_id = nullif(current_setting('hopa.household_id', true), '')::uuid) + with check (household_id = nullif(current_setting('hopa.household_id', true), '')::uuid); + +alter table sync_ops enable row level security; +alter table sync_ops force row level security; +create policy sync_ops_own on sync_ops + using (household_id = nullif(current_setting('hopa.household_id', true), '')::uuid) + with check (household_id = nullif(current_setting('hopa.household_id', true), '')::uuid); + +-- The app role only reads and appends the log, and updates the head row. The +-- log has no delete and no update: it is append-only. On a deployment whose +-- runtime role owns the tables (render.yaml) the migration role is that same +-- role and already holds every privilege; the grant covers a separate role. +do $$ +begin + if exists (select from pg_roles where rolname = 'hopa_app') then + grant select, insert on sync_ops to hopa_app; + grant select, insert, update on sync_heads to hopa_app; + end if; +end +$$; diff --git a/services/backend/src/test/kotlin/com/hopa/backend/store/V10SchemaTest.kt b/services/backend/src/test/kotlin/com/hopa/backend/store/V10SchemaTest.kt new file mode 100644 index 000000000..81166ca20 --- /dev/null +++ b/services/backend/src/test/kotlin/com/hopa/backend/store/V10SchemaTest.kt @@ -0,0 +1,116 @@ +package com.hopa.backend.store + +import com.hopa.backend.harness.PostgresHarness +import java.sql.Connection +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test + +/** + * Schema v10: the sync op log. Every table is household scoped with RLS enabled + * and forced, the ids are text because they are client ids (`c-…`, `m-…`), and a + * turn is stored once per thread by a partial unique index. + */ +class V10SchemaTest { + private val tables = listOf("sync_heads", "sync_ops") + + @Test + fun `v10 creates the sync tables and re-applies cleanly`() { + val owner = PostgresHarness.ownerDatabase() + + assertEquals(0, owner.migrate()) + assertEquals(0, owner.migrate()) + + val present = PostgresHarness.adminDatabase().dataSource.connection.use { connection -> + connection.strings( + "select table_name from information_schema.tables " + + "where table_schema = 'public' and table_name in ('sync_heads', 'sync_ops') " + + "order by table_name", + ) + } + + assertEquals(tables, present) + } + + @Test + fun `every sync table has row level security enabled and forced`() { + val flags = PostgresHarness.adminDatabase().dataSource.connection.use { connection -> + connection.strings( + "select relname || ':' || relrowsecurity || ':' || relforcerowsecurity " + + "from pg_class where relname in ('sync_heads', 'sync_ops') order by relname", + ) + } + val policies = PostgresHarness.adminDatabase().dataSource.connection.use { connection -> + connection.strings( + "select tablename || ':' || policyname from pg_policies " + + "where tablename in ('sync_heads', 'sync_ops') order by tablename", + ) + } + + assertEquals(tables.map { "$it:true:true" }, flags) + assertEquals(listOf("sync_heads:sync_heads_own", "sync_ops:sync_ops_own"), policies) + } + + @Test + fun `the op log keeps ids as text and bodies as bytea`() { + val columns = PostgresHarness.adminDatabase().dataSource.connection.use { connection -> + connection.strings( + "select column_name || ':' || data_type || ':' || is_nullable " + + "from information_schema.columns where table_schema = 'public' and table_name = 'sync_ops' " + + "order by ordinal_position", + ) + } + val heads = PostgresHarness.adminDatabase().dataSource.connection.use { connection -> + connection.strings( + "select column_name || ':' || data_type || ':' || is_nullable " + + "from information_schema.columns where table_schema = 'public' and table_name = 'sync_heads' " + + "order by ordinal_position", + ) + } + + assertEquals( + listOf( + "household_id:uuid:NO", + "seq:bigint:NO", + "op_id:text:NO", + "kind:text:NO", + "thread_id:text:NO", + "turn_id:text:YES", + "from_device:uuid:NO", + "member_id:uuid:NO", + "body:bytea:NO", + "body_hash:bytea:NO", + "size:integer:NO", + "client_at:bigint:NO", + "created_at:timestamp with time zone:NO", + ), + columns, + ) + assertEquals(listOf("household_id:uuid:NO", "last_seq:bigint:NO"), heads) + } + + @Test + fun `the pull index and the partial turn index are present`() { + val indexes = PostgresHarness.adminDatabase().dataSource.connection.use { connection -> + connection.strings( + "select indexname || ' ' || indexdef from pg_indexes " + + "where tablename = 'sync_ops' order by indexname", + ) + } + + val turn = indexes.single { it.startsWith("sync_ops_turn_idx ") } + val pull = indexes.single { it.startsWith("sync_ops_pull_idx ") } + assertTrue(turn.contains("UNIQUE"), turn) + assertTrue(turn.contains("(household_id, thread_id, turn_id)"), turn) + assertTrue(turn.contains("WHERE ((kind = 'turn.append'::text) AND (turn_id IS NOT NULL))"), turn) + assertTrue(pull.contains("(household_id, member_id, seq)"), pull) + assertTrue(indexes.any { it.contains("(household_id, op_id)") && it.contains("UNIQUE") }) + } + + private fun Connection.strings(sql: String): List = + createStatement().use { statement -> + statement.executeQuery(sql).use { rows -> + buildList { while (rows.next()) add(rows.getString(1)) } + } + } +} diff --git a/services/backend/src/test/kotlin/com/hopa/backend/sync/PgSyncStoreTest.kt b/services/backend/src/test/kotlin/com/hopa/backend/sync/PgSyncStoreTest.kt new file mode 100644 index 000000000..fd2706fba --- /dev/null +++ b/services/backend/src/test/kotlin/com/hopa/backend/sync/PgSyncStoreTest.kt @@ -0,0 +1,33 @@ +package com.hopa.backend.sync + +import com.hopa.backend.auth.DeviceIdentity +import com.hopa.backend.harness.PostgresHarness +import com.hopa.backend.harness.newDevice +import com.hopa.backend.harness.newHousehold +import com.hopa.backend.harness.seedHousehold +import com.hopa.backend.harness.seedMember +import com.hopa.backend.store.PgSyncStore +import java.util.UUID + +class PgSyncStoreTest : SyncStoreContract() { + private val db = PostgresHarness.appDatabase() + + override val store: SyncStore = PgSyncStore(db) + + /** A second store over the same database: what a reconnect or a restart sees. */ + override fun reopened(): SyncStore = PgSyncStore(db) + + override fun household(devices: Int): List { + val household = newHousehold() + return (1..devices).map { index -> + val device = newDevice() + val member = UUID.randomUUID().toString() + if (index == 1) { + seedHousehold(db, household, device, member) + } else { + seedMember(db, household, member, device) + } + DeviceIdentity(device, household, member) + } + } +} diff --git a/services/backend/src/test/kotlin/com/hopa/backend/sync/SyncServiceTest.kt b/services/backend/src/test/kotlin/com/hopa/backend/sync/SyncServiceTest.kt new file mode 100644 index 000000000..080c7128d --- /dev/null +++ b/services/backend/src/test/kotlin/com/hopa/backend/sync/SyncServiceTest.kt @@ -0,0 +1,139 @@ +package com.hopa.backend.sync + +import com.hopa.backend.auth.DeviceIdentity +import java.util.UUID +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test + +/** + * The push and pull rules on top of [SyncStore]: the batch cap, the two op + * shapes, the ciphertext bounds and the page clamp. The in-memory store keeps + * the test database-free. + */ +class SyncServiceTest { + private val service = SyncService(InMemorySyncStore(clock = { NOW })) + private val home = DeviceIdentity("d-ana", "h-1", "m-ana") + private val other = DeviceIdentity("d-ben", "h-1", "m-ben") + + private fun op( + opId: String = UUID.randomUUID().toString(), + kind: String = SyncService.KIND_TURN_APPEND, + threadId: String = "c-1", + turnId: String? = "m-" + UUID.randomUUID(), + body: ByteArray = ByteArray(40) { 3 }, + clientAt: Long = NOW, + ) = NewSyncOp(opId, kind, threadId, turnId, body, clientAt) + + private fun ok(result: SyncResult): T = (result as SyncResult.Ok).value + + private fun code(result: SyncResult<*>): String = (result as SyncResult.Failed).error.code + + @Test + fun `an empty batch is refused and writes nothing`() { + assertEquals("E_SCHEMA", code(service.push(home, emptyList()))) + assertEquals(0L, service.head(home)) + } + + @Test + fun `a push of more than one hundred ops is refused`() { + val hundred = (1..100).map { op(turnId = "m-$it") } + + assertEquals("E_SCHEMA", code(service.push(home, hundred + op(turnId = "m-101")))) + assertEquals(0L, service.head(home), "the refused batch wrote nothing") + assertEquals(100, ok(service.push(home, hundred)).size) + } + + @Test + fun `an unknown kind is refused`() { + assertEquals("E_SCHEMA", code(service.push(home, listOf(op(kind = "thread.delete"))))) + } + + @Test + fun `a turn append needs a turn id and an upsert must not have one`() { + val refused = listOf( + service.push(home, listOf(op(turnId = null))), + service.push(home, listOf(op(turnId = " "))), + service.push(home, listOf(op(kind = SyncService.KIND_THREAD_UPSERT, turnId = "m-1"))), + ) + + assertEquals(List(refused.size) { "E_SCHEMA" }, refused.map(::code)) + assertEquals(0L, service.head(home)) + } + + @Test + fun `a blank thread id is refused`() { + assertEquals("E_SCHEMA", code(service.push(home, listOf(op(threadId = " "))))) + } + + @Test + fun `ciphertext outside the sealed bounds is refused and the bounds are accepted`() { + val refused = listOf( + service.push(home, listOf(op(body = ByteArray(SyncService.MIN_OP_BYTES - 1)))), + service.push(home, listOf(op(body = ByteArray(SyncService.MAX_OP_BYTES + 1)))), + ) + + assertEquals(List(refused.size) { "E_SCHEMA" }, refused.map(::code)) + val smallest = ok(service.push(home, listOf(op(body = ByteArray(SyncService.MIN_OP_BYTES))))) + val largest = ok(service.push(home, listOf(op(body = ByteArray(SyncService.MAX_OP_BYTES))))) + assertEquals(listOf(1L, 2L), smallest.map { it.seq } + largest.map { it.seq }) + } + + @Test + fun `a negative client time is refused`() { + assertEquals("E_SCHEMA", code(service.push(home, listOf(op(clientAt = -1))))) + } + + @Test + fun `a replay is a duplicate ack and another body with the same op id is a conflict`() { + val sent = op() + val first = ok(service.push(home, listOf(sent))).single() + val replay = ok(service.push(home, listOf(sent))).single() + val conflict = service.push(home, listOf(op(opId = sent.opId, body = ByteArray(41) { 4 }))) + + assertEquals(SyncAck(sent.opId, 1, duplicate = false), first) + assertEquals(SyncAck(sent.opId, 1, duplicate = true), replay) + assertEquals("E_CONFLICT", code(conflict)) + assertEquals(1L, service.head(home)) + } + + @Test + fun `pull clamps the page size to one to two hundred`() { + repeat(3) { + ok(service.push(home, (1..100).map { n -> op(turnId = "m-${it * 100 + n}") })) + } + ok(service.push(home, listOf(op(turnId = "m-301")))) + + val clamped = ok(service.pull(home, 0, limit = 1_000)) + assertEquals(200, clamped.ops.size) + assertTrue(clamped.hasMore) + assertEquals(301L, clamped.head) + assertEquals(200, ok(service.pull(home, 0, limit = 0)).ops.size) + assertEquals(1, ok(service.pull(home, 0, limit = -5)).ops.size) + assertEquals(3, ok(service.pull(home, 0, limit = 3)).ops.size) + assertTrue(ok(service.pull(home, 0, limit = 3)).hasMore) + assertEquals(1, ok(service.pull(home, 300)).ops.size) + } + + @Test + fun `pull refuses a negative after`() { + assertEquals("E_SCHEMA", code(service.pull(home, -1))) + } + + @Test + fun `pull reads only the caller's member log`() { + ok(service.push(home, listOf(op(turnId = "m-1"), op(turnId = "m-2")))) + + val mine = ok(service.pull(home, 0)) + val theirs = ok(service.pull(other, 0)) + + assertEquals(listOf(1L, 2L), mine.ops.map { it.seq }) + assertEquals(2L, mine.head) + assertTrue(theirs.ops.isEmpty()) + assertEquals(2L, theirs.head, "the household head is shared even when the log is not") + } + + private companion object { + const val NOW = 1_733_000_000_000L + } +} diff --git a/services/backend/src/test/kotlin/com/hopa/backend/sync/SyncStoreContract.kt b/services/backend/src/test/kotlin/com/hopa/backend/sync/SyncStoreContract.kt new file mode 100644 index 000000000..17667d52f --- /dev/null +++ b/services/backend/src/test/kotlin/com/hopa/backend/sync/SyncStoreContract.kt @@ -0,0 +1,178 @@ +package com.hopa.backend.sync + +import com.hopa.backend.auth.DeviceIdentity +import java.util.UUID +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows + +/** + * What every [SyncStore] must do, run against Postgres. A subclass supplies the + * store and seeds households with real devices. + */ +abstract class SyncStoreContract { + protected abstract val store: SyncStore + + /** A store over the same data, as after a reconnect or a server restart. */ + protected abstract fun reopened(): SyncStore + + /** A new household with [devices] devices, each of its own member. */ + protected abstract fun household(devices: Int): List + + private fun op( + kind: String = SyncService.KIND_TURN_APPEND, + threadId: String = "c-1", + turnId: String? = "m-" + UUID.randomUUID(), + opId: String = UUID.randomUUID().toString(), + body: ByteArray = ByteArray(40) { 5 }, + clientAt: Long = 1_733_000_000_000L, + ) = NewSyncOp(opId, kind, threadId, turnId, body, clientAt) + + private fun append(device: DeviceIdentity, op: NewSyncOp = op()): SyncAck = + store.append(device.householdId, device.memberId, device.deviceId, op) + + @Test + fun `appends get consecutive seqs and the head follows them`() { + val device = household(1).single() + + val first = append(device) + val second = append(device) + val third = append(device) + + assertEquals(listOf(1L, 2L, 3L), listOf(first.seq, second.seq, third.seq)) + assertEquals(3L, store.head(device.householdId)) + } + + @Test + fun `each household counts its own seqs and a fresh one is at zero`() { + val home = household(1).single() + val other = household(1).single() + assertEquals(0L, store.head(home.householdId)) + + append(home) + append(home) + val elsewhere = append(other) + val again = append(home) + + assertEquals(1L, elsewhere.seq) + assertEquals(3L, again.seq) + assertEquals(3L, store.head(home.householdId)) + assertEquals(1L, store.head(other.householdId)) + } + + @Test + fun `the same op id with the same body is a duplicate and burns no seq`() { + val device = household(1).single() + val sent = op() + append(device, sent) + + val again = reopened().append(device.householdId, device.memberId, device.deviceId, sent) + + assertEquals(SyncAck(sent.opId, 1, duplicate = true), again) + assertEquals(1L, store.head(device.householdId)) + assertEquals(1, store.opsAfter(device.householdId, device.memberId, 0, 500).size) + assertEquals(2L, append(device).seq) + } + + @Test + fun `the same op id with another body is a conflict and burns no seq`() { + val device = household(1).single() + val sent = op() + append(device, sent) + + assertThrows { + append(device, op(opId = sent.opId, body = ByteArray(41) { 6 })) + } + assertEquals(1L, store.head(device.householdId)) + assertEquals(2L, append(device).seq) + } + + @Test + fun `a turn is stored once per thread whatever its op id`() { + val device = household(1).single() + append(device, op(threadId = "c-1", turnId = "m-1")) + + assertThrows { + append(device, op(threadId = "c-1", turnId = "m-1")) + } + assertEquals(1L, store.head(device.householdId)) + // An upsert of the same thread supersedes; only turns are unique. + val upsert = op(kind = SyncService.KIND_THREAD_UPSERT, threadId = "c-1", turnId = null) + assertEquals(2L, append(device, upsert).seq) + assertEquals(3L, append(device, op(threadId = "c-2", turnId = "m-1")).seq) + assertEquals(4L, append(device, op(threadId = "c-1", turnId = "m-2")).seq) + } + + @Test + fun `ops after a seq are this member's in order and up to the limit`() { + val (ana, ben) = household(2) + repeat(3) { append(ana) } + append(ben) + + val mine = store.opsAfter(ana.householdId, ana.memberId, 0, 500) + val theirs = store.opsAfter(ben.householdId, ben.memberId, 0, 500) + val page = store.opsAfter(ana.householdId, ana.memberId, 1, 1) + + assertEquals(listOf(1L, 2L, 3L), mine.map { it.seq }) + assertEquals(listOf(4L), theirs.map { it.seq }) + assertEquals(listOf(2L), page.map { it.seq }) + assertEquals(4L, store.head(ana.householdId)) + } + + @Test + fun `an op keeps the attested actor and the body verbatim`() { + val device = household(1).single() + val body = ByteArray(64) { it.toByte() } + val sent = op(opId = "op-1", threadId = "c-9", turnId = "m-9", body = body, clientAt = 1_700_000_000_123L) + append(device, sent) + + val read = store.opsAfter(device.householdId, device.memberId, 0, 10).single() + + assertEquals(1L, read.seq) + assertEquals("op-1", read.opId) + assertEquals(SyncService.KIND_TURN_APPEND, read.kind) + assertEquals("c-9", read.threadId) + assertEquals("m-9", read.turnId) + assertEquals(device.deviceId, read.fromDevice) + assertEquals(device.memberId, read.memberId) + assertEquals(sent.clientAt, read.clientAt) + assertTrue(body.contentEquals(read.body)) + } + + @Test + fun `a batch is acked in order and a replay is all duplicates`() { + val device = household(1).single() + val sent = listOf(op(turnId = "m-1"), op(turnId = "m-2")) + + val acks = store.appendBatch(device.householdId, device.memberId, device.deviceId, sent) + val replay = store.appendBatch(device.householdId, device.memberId, device.deviceId, sent) + + assertEquals(listOf(1L, 2L), acks.map { it.seq }) + assertTrue(acks.none { it.duplicate }) + assertEquals(listOf(1L, 2L), replay.map { it.seq }) + assertTrue(replay.all { it.duplicate }) + assertEquals(2L, store.head(device.householdId)) + } + + @Test + fun `a batch over the cap or outside the body bounds writes nothing`() { + val device = household(1).single() + val tooMany = (1..SyncService.MAX_OPS_PER_PUSH + 1).map { op(turnId = "m-$it") } + + assertThrows { + store.appendBatch(device.householdId, device.memberId, device.deviceId, tooMany) + } + assertThrows { + store.appendBatch( + device.householdId, + device.memberId, + device.deviceId, + listOf(op(body = ByteArray(SyncService.MIN_OP_BYTES - 1))), + ) + } + assertEquals(0L, store.head(device.householdId)) + val accepted = store.appendBatch(device.householdId, device.memberId, device.deviceId, listOf(op(), op())) + assertEquals(2L, accepted.last().seq) + } +} From 5dd78142055488bd55386255004081ec02316216 Mon Sep 17 00:00:00 2001 From: aharonamir Date: Sun, 29 Nov 2026 22:33:34 +0200 Subject: [PATCH 02/58] Serve the sync push and pull routes POST /v1/sync/ops acks a sealed batch with its seqs and the household head; GET /v1/sync/ops pages the caller's member log after a client-owned cursor. Both take the household, member and device from the bearer token only and never look at an op body. BodyTooLarge is 413 E_SCHEMA, a malformed body or base64 is 400 E_SCHEMA, and a store conflict is 409 E_CONFLICT. The mini-design records the tables, payloads, cursor and merge rules the client tasks build on. Part of #32 --- docs/project/plan/backend/tasks/week2-sync.md | 88 +++++ .../src/main/kotlin/com/hopa/backend/Main.kt | 5 + .../kotlin/com/hopa/backend/ServerConfig.kt | 4 + .../com/hopa/backend/sync/SyncRoutes.kt | 148 +++++++++ .../com/hopa/backend/sync/SyncHttpTest.kt | 309 ++++++++++++++++++ 5 files changed, 554 insertions(+) create mode 100644 docs/project/plan/backend/tasks/week2-sync.md create mode 100644 services/backend/src/main/kotlin/com/hopa/backend/sync/SyncRoutes.kt create mode 100644 services/backend/src/test/kotlin/com/hopa/backend/sync/SyncHttpTest.kt diff --git a/docs/project/plan/backend/tasks/week2-sync.md b/docs/project/plan/backend/tasks/week2-sync.md new file mode 100644 index 000000000..1cd3a13a5 --- /dev/null +++ b/docs/project/plan/backend/tasks/week2-sync.md @@ -0,0 +1,88 @@ +# Sync v0: the per-member op log + +> Week 2 backend slice, part of [#32](https://github.com/agents-demo/hopa/issues/32) +> Phase 2. Written before the client work so the wire shape is fixed once. + +**Goal.** Two devices of one household member — a phone and a PC — exchange +conversation turns through the backend without any plaintext leaving either +device. The server appends sealed ops to a log, hands out seqs and serves them +back after a client-owned cursor. Merge and rendering stay on the clients; the +server only orders. + +## Tables (`V10__sync.sql`) + +`sync_heads(household_id uuid pk, last_seq bigint >= 0)` is the household's seq +allocator. An append locks the row (inserting it at 0 when missing), takes the +next seq and updates it in the same tenant transaction, so one household's seqs +have no gap and no duplicate. + +`sync_ops` holds one row per op, with `pk (household_id, seq)` and +`unique (household_id, op_id)`: + +| column | type | meaning | +|---|---|---| +| `household_id`, `seq` | uuid, bigint | tenant and server order | +| `op_id` | text | client-chosen id, unique per household | +| `kind` | text | `thread.upsert` or `turn.append` | +| `thread_id` | text | client thread id (`c-…`) | +| `turn_id` | text null | client turn id (`m-…`), only on `turn.append` | +| `from_device`, `member_id` | uuid | server-attested actor | +| `body` | bytea | AES-GCM ciphertext the server never reads | +| `body_hash` | bytea | SHA-256 of `body`, for replay checks | +| `size`, `client_at` | int, bigint | ciphertext length and the author's clock | +| `created_at` | timestamptz | the server's clock, the merge's authority | + +`op_id`, `thread_id` and `turn_id` are `text` on purpose: they are client ids +(`c-…`, `m-…`), not UUIDs. A partial unique index on +`(household_id, thread_id, turn_id) where kind = 'turn.append'` stores a turn +once per thread; a violation is answered `E_CONFLICT`, never a 500. +`(household_id, member_id, seq)` serves the pull. Both tables enable and **force** +row level security with the board's household policy, and the log is append-only: +the app role gets `select, insert` on `sync_ops` and no `update` or `delete`. + +## Op kinds and sealed payloads + +`ct` is AES-256-GCM over canonical JSON under the household key (ADR-0026): +`IV(12) || ciphertext || tag(16)`, so the minimum is 28 bytes. The server treats +it as opaque; it stores the hash and size only to dedupe and bound. + +| kind | `turn_id` | plaintext (canonical JSON) | +|---|---|---| +| `thread.upsert` | absent | `{"id":"c-…","title":"…","titleAt":0,"created":0,"updated":0,"deletedAt":0}` | +| `turn.append` | `m-…` | `{"id":"m-…","role":"user\|assistant","text":"…","at":0}` | + +A `thread.upsert` carries the thread's current metadata and supersedes the +previous one; a turn is immutable and lands once per thread. + +## Cursor rule + +The cursor is **client-owned**: `GET /v1/sync/ops?after=&limit=`, with +no server cursor table. Each device stores the last seq it applied and passes it +as `after`; `after=0` reads from the start. The seq belongs to the household, so +a member sees gaps where another member appended. + +## Merge rule + +Server `seq` order is authoritative and the log is append-only. `clientAt` is +advisory — shown in the UI and usable by a client for its own tie-breaks — and +never orders ops on the server, so a clock-skewed device cannot insert an op +before one already stored. + +## Tombstones + +`thread.upsert` with `deletedAt > 0` is final in v0: a deleted thread stays +deleted and there is no restore. Deleting a thread does not delete its turns; +clients drop them locally and stop appending to the thread. + +## Limits + +- 100 ops per push, whole batch refused (`E_SCHEMA`) before any write if one op is bad +- 64 KiB ciphertext per op, 28 bytes minimum (IV + tag) +- 256 KiB request body +- pull page 1..200 ops, default and cap 200 + +## Out of scope in v0 + +attachments, pins, archive, shared household threads (the log is per member) and +push wake. No server-side merge, no compaction, no per-op ACL beyond the tenant +and member scoping. diff --git a/services/backend/src/main/kotlin/com/hopa/backend/Main.kt b/services/backend/src/main/kotlin/com/hopa/backend/Main.kt index 3f3a88668..0fae0c643 100644 --- a/services/backend/src/main/kotlin/com/hopa/backend/Main.kt +++ b/services/backend/src/main/kotlin/com/hopa/backend/Main.kt @@ -45,8 +45,11 @@ import com.hopa.backend.store.DbProbe import com.hopa.backend.store.PgBoardStore import com.hopa.backend.store.PgDevices import com.hopa.backend.store.PgMemberStore +import com.hopa.backend.store.PgSyncStore import com.hopa.backend.store.PgTaskStore import com.hopa.backend.store.PostgresProbe +import com.hopa.backend.sync.InMemorySyncStore +import com.hopa.backend.sync.syncRoutes import com.hopa.backend.tasks.DeviceDirectory import com.hopa.backend.tasks.InMemoryTaskStore import com.hopa.backend.tasks.TaskStore @@ -85,6 +88,7 @@ fun Application.module(config: ServerConfig) { consoleRoutes(config) traceRoutes(config) boardRoutes(config) + syncRoutes(config) scopeKeyRoutes(config) memberRoutes(config) gatewayRoutes(config) @@ -203,6 +207,7 @@ fun main() { tokenIssuer = tokens, tasks = database?.let { PgTaskStore(it) } ?: InMemoryTaskStore(), boardStore = database?.let { PgBoardStore(it) } ?: InMemoryBoardStore(), + syncStore = database?.let { PgSyncStore(it) } ?: InMemorySyncStore(), members = database?.let { PgMemberStore(it) } ?: MemberStore.Empty, push = push, traces = traceStore ?: TraceRecorder.None, diff --git a/services/backend/src/main/kotlin/com/hopa/backend/ServerConfig.kt b/services/backend/src/main/kotlin/com/hopa/backend/ServerConfig.kt index 1e46b1788..43fd75ed9 100644 --- a/services/backend/src/main/kotlin/com/hopa/backend/ServerConfig.kt +++ b/services/backend/src/main/kotlin/com/hopa/backend/ServerConfig.kt @@ -20,6 +20,8 @@ import com.hopa.backend.pairing.PendingPairingService import com.hopa.backend.pairing.TokenIssuer import com.hopa.backend.push.PushPort import com.hopa.backend.store.DbProbe +import com.hopa.backend.sync.InMemorySyncStore +import com.hopa.backend.sync.SyncStore import com.hopa.backend.tasks.DeviceDirectory import com.hopa.backend.tasks.InMemoryTaskStore import com.hopa.backend.tasks.TaskStore @@ -64,6 +66,8 @@ data class ServerConfig( val tasks: TaskStore = InMemoryTaskStore(), /** The board log and scope-key wraps (ADR-0033); Postgres in production. */ val boardStore: BoardStore = InMemoryBoardStore(), + /** The per-member sync op log (V10); Postgres in production. */ + val syncStore: SyncStore = InMemorySyncStore(), /** The group's members and their permissions (V7); Postgres in production. */ val members: MemberStore = MemberStore.Empty, val messageLimit: RateLimiter = RateLimiter(20, 1_000), diff --git a/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncRoutes.kt b/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncRoutes.kt new file mode 100644 index 000000000..009760ffb --- /dev/null +++ b/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncRoutes.kt @@ -0,0 +1,148 @@ +package com.hopa.backend.sync + +import com.hopa.backend.ServerConfig +import com.hopa.backend.http.BodyTooLarge +import com.hopa.backend.http.bearerDevice +import com.hopa.backend.http.receiveBounded +import com.hopa.backend.http.respondError +import com.hopa.backend.http.statusFor +import io.ktor.http.HttpStatusCode +import io.ktor.server.application.Application +import io.ktor.server.application.ApplicationCall +import io.ktor.server.response.respond +import io.ktor.server.routing.get +import io.ktor.server.routing.post +import io.ktor.server.routing.routing +import java.time.Instant +import java.util.Base64 +import kotlinx.serialization.SerializationException +import kotlinx.serialization.Serializable + +/** One op as a device pushes it: the sealed body arrives base64, never as plaintext. */ +@Serializable +internal class SyncPushOp( + val opId: String, + val kind: String, + val threadId: String, + val turnId: String? = null, + val ct: String, + val clientAt: Long, +) + +@Serializable +internal class SyncPushRequest(val ops: List) + +@Serializable +internal class SyncAckView(val opId: String, val seq: Long, val duplicate: Boolean) + +@Serializable +internal class SyncPushResponse(val head: Long, val accepted: List) + +/** One op as a device pulls it: the server-attested actor and the ciphertext. */ +@Serializable +internal class SyncOpView( + val seq: Long, + val opId: String, + val kind: String, + val threadId: String, + val turnId: String? = null, + val fromDevice: String, + val memberId: String, + val clientAt: Long, + val at: String, + val ct: String, +) + +@Serializable +internal class SyncOpsResponse(val ops: List, val hasMore: Boolean, val head: Long) + +/** + * Sync v0 (issue #32 Phase 2): push a batch of sealed ops, pull the caller's + * member log after a seq. The household and member always come from the bearer + * token, never from the wire, and no route ever reads an op body. + */ +fun Application.syncRoutes(config: ServerConfig, service: SyncService = SyncService(config.syncStore)) { + routing { + post("/v1/sync/ops") { + val identity = call.bearerDevice(config) ?: return@post + val request = try { + call.receiveBounded(SyncPushRequest.serializer(), SyncService.MAX_BODY_BYTES) + } catch (_: BodyTooLarge) { + call.respondError(HttpStatusCode.PayloadTooLarge, "E_SCHEMA", "body is too large") + return@post + } catch (_: SerializationException) { + call.respondError(HttpStatusCode.BadRequest, "E_SCHEMA", "body needs ops") + return@post + } catch (_: IllegalArgumentException) { + call.respondError(HttpStatusCode.BadRequest, "E_SCHEMA", "body needs ops") + return@post + } + val ops = try { + request.ops.map(::newOp) + } catch (_: IllegalArgumentException) { + call.respondError(HttpStatusCode.BadRequest, "E_SCHEMA", "ct is not base64") + return@post + } + when (val result = service.push(identity, ops)) { + is SyncResult.Ok -> call.respond( + SyncPushResponse( + head = service.head(identity), + accepted = result.value.map { SyncAckView(it.opId, it.seq, it.duplicate) }, + ), + ) + + is SyncResult.Failed -> call.respondFailure(result) + } + } + + get("/v1/sync/ops") { + val identity = call.bearerDevice(config) ?: return@get + val parameters = call.request.queryParameters + val after = parameters["after"]?.let { it.toLongOrNull() ?: -1L } ?: 0L + val limit = when (val raw = parameters["limit"]) { + null -> null + else -> raw.toIntOrNull() ?: run { + call.respondError(HttpStatusCode.BadRequest, "E_SCHEMA", "limit must be a number") + return@get + } + } + when (val result = service.pull(identity, after, limit)) { + is SyncResult.Ok -> call.respond( + SyncOpsResponse( + ops = result.value.ops.map(::view), + hasMore = result.value.hasMore, + head = result.value.head, + ), + ) + + is SyncResult.Failed -> call.respondFailure(result) + } + } + } +} + +private fun newOp(op: SyncPushOp) = NewSyncOp( + opId = op.opId, + kind = op.kind, + threadId = op.threadId, + turnId = op.turnId, + body = Base64.getDecoder().decode(op.ct), + clientAt = op.clientAt, +) + +private fun view(op: SyncOp) = SyncOpView( + seq = op.seq, + opId = op.opId, + kind = op.kind, + threadId = op.threadId, + turnId = op.turnId, + fromDevice = op.fromDevice, + memberId = op.memberId, + clientAt = op.clientAt, + at = Instant.ofEpochMilli(op.createdAt).toString(), + ct = Base64.getEncoder().encodeToString(op.body), +) + +internal suspend fun ApplicationCall.respondFailure(result: SyncResult.Failed) { + respondError(statusFor(result.error.code), result.error.code, result.error.message) +} diff --git a/services/backend/src/test/kotlin/com/hopa/backend/sync/SyncHttpTest.kt b/services/backend/src/test/kotlin/com/hopa/backend/sync/SyncHttpTest.kt new file mode 100644 index 000000000..5019528f6 --- /dev/null +++ b/services/backend/src/test/kotlin/com/hopa/backend/sync/SyncHttpTest.kt @@ -0,0 +1,309 @@ +package com.hopa.backend.sync + +import com.hopa.backend.ServerConfig +import com.hopa.backend.auth.AuthPort +import com.hopa.backend.auth.DeviceIdentity +import com.hopa.backend.harness.MapAuth +import com.hopa.backend.log.EventLog +import com.hopa.backend.module +import io.ktor.client.HttpClient +import io.ktor.client.request.get +import io.ktor.client.request.header +import io.ktor.client.request.post +import io.ktor.client.request.setBody +import io.ktor.client.statement.HttpResponse +import io.ktor.client.statement.bodyAsText +import io.ktor.http.ContentType +import io.ktor.http.HttpStatusCode +import io.ktor.http.contentType +import io.ktor.server.testing.testApplication +import java.util.Base64 +import java.util.UUID +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.boolean +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.long +import kotlinx.serialization.json.put +import org.junit.jupiter.api.Assertions.assertArrayEquals +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test + +/** `POST /v1/sync/ops` and `GET /v1/sync/ops` with the in-memory store. */ +class SyncHttpTest { + private val events = mutableListOf() + + private fun household(members: Int = 2): List { + val householdId = UUID.randomUUID().toString() + return (1..members).map { + DeviceIdentity(UUID.randomUUID().toString(), householdId, UUID.randomUUID().toString()) + } + } + + private fun config( + group: List, + auth: AuthPort = MapAuth(group.associateBy { "tok-${it.deviceId}" }), + ) = ServerConfig( + version = "0.1.0", + auth = auth, + syncStore = InMemorySyncStore(clock = { CREATED_AT }), + log = EventLog { name, fields -> events += "$name $fields" }, + ) + + private fun op( + opId: String = UUID.randomUUID().toString(), + kind: String = SyncService.KIND_TURN_APPEND, + threadId: String = "c-1", + turnId: String? = "m-" + UUID.randomUUID(), + ct: ByteArray = ByteArray(40) { 7 }, + clientAt: Long = CLIENT_AT, + ): JsonObject = buildJsonObject { + put("opId", opId) + put("kind", kind) + put("threadId", threadId) + if (turnId != null) put("turnId", turnId) + put("ct", Base64.getEncoder().encodeToString(ct)) + put("clientAt", clientAt) + } + + private fun batch(vararg ops: JsonObject): String = + buildJsonObject { put("ops", JsonArray(ops.toList())) }.toString() + + private suspend fun HttpClient.push(device: DeviceIdentity?, body: String): HttpResponse = + post("/v1/sync/ops") { + if (device != null) header("Authorization", "Bearer tok-${device.deviceId}") + contentType(ContentType.Application.Json) + setBody(body) + } + + private suspend fun HttpClient.pull(device: DeviceIdentity?, query: String = ""): HttpResponse = + get("/v1/sync/ops$query") { + if (device != null) header("Authorization", "Bearer tok-${device.deviceId}") + } + + private suspend fun HttpResponse.json(): JsonObject = Json.parseToJsonElement(bodyAsText()).jsonObject + + private suspend fun HttpResponse.code(): String = json()["code"]!!.jsonPrimitive.content + + private suspend fun HttpResponse.seqs(): List = + json()["accepted"]!!.jsonArray.map { it.jsonObject["seq"]!!.jsonPrimitive.long } + + @Test + fun `push acks two ops with consecutive seqs and the head`() = testApplication { + val group = household() + application { module(config(group)) } + + val response = client.push(group[0], batch(op(), op())) + + assertEquals(HttpStatusCode.OK, response.status) + val body = response.json() + assertEquals(listOf(1L, 2L), response.seqs()) + assertEquals(2L, body["head"]!!.jsonPrimitive.long) + assertFalse(body["accepted"]!!.jsonArray.first().jsonObject["duplicate"]!!.jsonPrimitive.boolean) + } + + @Test + fun `a replayed batch is all duplicates and the head does not move`() = testApplication { + val group = household() + application { module(config(group)) } + val sent = listOf(op(), op()) + client.push(group[0], batch(*sent.toTypedArray())) + + val replay = client.push(group[0], batch(*sent.toTypedArray())) + + assertEquals(HttpStatusCode.OK, replay.status) + assertEquals(listOf(1L, 2L), replay.seqs()) + assertTrue(replay.json()["accepted"]!!.jsonArray.all { it.jsonObject["duplicate"]!!.jsonPrimitive.boolean }) + assertEquals(2L, replay.json()["head"]!!.jsonPrimitive.long) + assertEquals(2, client.pull(group[0]).json()["ops"]!!.jsonArray.size) + } + + @Test + fun `pull pages the log with after and limit`() = testApplication { + val group = household() + val ana = group[0] + application { module(config(group)) } + val turnId = "m-" + UUID.randomUUID() + val sent = listOf(op(turnId = turnId), op()) + client.push(ana, batch(*sent.toTypedArray())) + + val all = client.pull(ana, "?after=0") + val page = client.pull(ana, "?after=0&limit=1") + val second = client.pull(ana, "?after=1") + + assertEquals(HttpStatusCode.OK, all.status) + val body = all.json() + assertEquals(2, body["ops"]!!.jsonArray.size) + assertFalse(body["hasMore"]!!.jsonPrimitive.boolean) + assertEquals(2L, body["head"]!!.jsonPrimitive.long) + val first = body["ops"]!!.jsonArray.first().jsonObject + assertEquals(1L, first["seq"]!!.jsonPrimitive.long) + assertEquals(sent[0]["opId"]!!.jsonPrimitive.content, first["opId"]!!.jsonPrimitive.content) + assertEquals(SyncService.KIND_TURN_APPEND, first["kind"]!!.jsonPrimitive.content) + assertEquals("c-1", first["threadId"]!!.jsonPrimitive.content) + assertEquals(turnId, first["turnId"]!!.jsonPrimitive.content) + assertEquals(ana.deviceId, first["fromDevice"]!!.jsonPrimitive.content) + assertEquals(ana.memberId, first["memberId"]!!.jsonPrimitive.content) + assertEquals(CLIENT_AT, first["clientAt"]!!.jsonPrimitive.long) + assertTrue(first["at"]!!.jsonPrimitive.content.endsWith("Z")) + + assertEquals(1, page.json()["ops"]!!.jsonArray.size) + assertTrue(page.json()["hasMore"]!!.jsonPrimitive.boolean) + assertEquals(listOf(2L), second.json()["ops"]!!.jsonArray.map { it.jsonObject["seq"]!!.jsonPrimitive.long }) + } + + @Test + fun `a thread upsert carries no turn id`() = testApplication { + val group = household() + application { module(config(group)) } + client.push(group[0], batch(op(kind = SyncService.KIND_THREAD_UPSERT, turnId = null))) + + val pulled = client.pull(group[0]).json()["ops"]!!.jsonArray.single().jsonObject + + assertEquals(SyncService.KIND_THREAD_UPSERT, pulled["kind"]!!.jsonPrimitive.content) + assertNull(pulled["turnId"]) + } + + @Test + fun `another household pulls its own empty log`() = testApplication { + val home = household().first() + val stranger = household().first() + application { module(config(listOf(home, stranger))) } + client.push(home, batch(op())) + + val pulled = client.pull(stranger, "?after=0") + + assertEquals(HttpStatusCode.OK, pulled.status) + assertTrue(pulled.json()["ops"]!!.jsonArray.isEmpty()) + assertEquals(0L, pulled.json()["head"]!!.jsonPrimitive.long) + } + + @Test + fun `a second member of the household reads none of the first member's ops`() = testApplication { + val (ana, ben) = household() + application { module(config(listOf(ana, ben))) } + client.push(ana, batch(op())) + + val pulled = client.pull(ben, "?after=0").json() + + assertTrue(pulled["ops"]!!.jsonArray.isEmpty()) + assertEquals(1L, pulled["head"]!!.jsonPrimitive.long, "the household head is shared, the log is not") + } + + @Test + fun `an unknown token is E_AUTH on both routes`() = testApplication { + val group = household() + application { module(config(group)) } + val stranger = DeviceIdentity(UUID.randomUUID().toString(), group[0].householdId, group[0].memberId) + + for (device in listOf(null, stranger)) { + val pushed = client.push(device, batch(op())) + assertEquals(HttpStatusCode.Unauthorized, pushed.status) + assertEquals("E_AUTH", pushed.code()) + val pulled = client.pull(device, "?after=0") + assertEquals(HttpStatusCode.Unauthorized, pulled.status) + assertEquals("E_AUTH", pulled.code()) + } + } + + @Test + fun `a revoked device token is E_AUTH on both routes`() = testApplication { + val group = household() + val auth = RevocableAuth(group.associateBy { "tok-${it.deviceId}" }.toMutableMap()) + application { module(config(group, auth)) } + val device = group[0] + assertEquals(HttpStatusCode.OK, client.push(device, batch(op())).status) + + auth.revoke("tok-${device.deviceId}") + + assertEquals(HttpStatusCode.Unauthorized, client.push(device, batch(op())).status) + assertEquals(HttpStatusCode.Unauthorized, client.pull(device, "?after=0").status) + } + + @Test + fun `malformed pushes are E_SCHEMA and an oversized body is 413`() = testApplication { + val group = household() + application { module(config(group)) } + val device = group[0] + val good = op() + val malformed = listOf( + "{}", + "not json", + """{"ops":[]}""", + batch(op(kind = "thread.delete")), + batch(op(turnId = null)), + buildJsonObject { + put("opId", UUID.randomUUID().toString()) + put("kind", SyncService.KIND_TURN_APPEND) + put("threadId", "c-1") + put("turnId", "m-1") + put("ct", "not base64") + put("clientAt", CLIENT_AT) + }.let { batch(it) }, + ) + for (body in malformed) { + val response = client.push(device, body) + assertEquals(HttpStatusCode.BadRequest, response.status, body) + assertEquals("E_SCHEMA", response.code(), body) + } + val oversized = batch( + buildJsonObject { + put("opId", UUID.randomUUID().toString()) + put("kind", SyncService.KIND_TURN_APPEND) + put("threadId", "c-1") + put("turnId", "m-2") + put("ct", Base64.getEncoder().encodeToString(ByteArray(300 * 1024))) + put("clientAt", CLIENT_AT) + }, + ) + val tooLarge = client.push(device, oversized) + assertEquals(HttpStatusCode.PayloadTooLarge, tooLarge.status) + assertEquals("E_SCHEMA", tooLarge.code()) + assertEquals(0L, client.pull(device).json()["head"]!!.jsonPrimitive.long) + val accepted = client.push(device, batch(good)).json()["accepted"]!!.jsonArray.single().jsonObject + assertEquals(good["opId"]!!.jsonPrimitive.content, accepted["opId"]!!.jsonPrimitive.content) + } + + @Test + fun `the stored body is exactly what was sent and no log line holds the plaintext`() = testApplication { + val group = household() + application { module(config(group)) } + val plaintext = "goal: buy milk" + val body = plaintext.toByteArray() + ByteArray(20) { 0x11 } + + client.push(group[0], batch(op(ct = body))) + val pulled = client.pull(group[0], "?after=0").json()["ops"]!!.jsonArray.single().jsonObject + val stored = Base64.getDecoder().decode(pulled["ct"]!!.jsonPrimitive.content) + + assertArrayEquals(body, stored) + // An oversized body is refused by size alone: nothing of it is echoed. + val refused = client.push( + group[0], + batch(op(turnId = "m-loud", ct = plaintext.toByteArray() + ByteArray(SyncService.MAX_OP_BYTES))), + ) + assertEquals(HttpStatusCode.BadRequest, refused.status) + assertFalse(refused.bodyAsText().contains(plaintext)) + assertTrue(events.none { it.contains(plaintext) }, events.toString()) + } + + private companion object { + const val CLIENT_AT = 1_733_000_000_000L + const val CREATED_AT = 1_733_000_600_000L + } + + /** A token map that can forget a device, as a revocation does. */ + private class RevocableAuth(private val byToken: MutableMap) : AuthPort { + override fun deviceFor(token: String): DeviceIdentity? = byToken[token] + + fun revoke(token: String) { + byToken.remove(token) + } + } +} From 24b6e67e4ff318ae5fe7820e8f4ff52394e385cd Mon Sep 17 00:00:00 2001 From: aharonamir Date: Sun, 29 Nov 2026 22:33:42 +0200 Subject: [PATCH 03/58] Put a minted device on the household's existing owner member mint inserted a fresh 'owner' member even when the caller named an existing household, so pairing a second device split the household into two members and two member-scoped sync logs. Resolve the household's first owner inside the tenant transaction and reuse its id; a member is created only for a household that has none. Part of #32 --- .../hopa/backend/pairing/PairingService.kt | 49 ++++++++--- .../hopa/backend/pairing/PairingMintTest.kt | 81 +++++++++++++++++++ 2 files changed, 121 insertions(+), 9 deletions(-) create mode 100644 services/backend/src/test/kotlin/com/hopa/backend/pairing/PairingMintTest.kt diff --git a/services/backend/src/main/kotlin/com/hopa/backend/pairing/PairingService.kt b/services/backend/src/main/kotlin/com/hopa/backend/pairing/PairingService.kt index 42fb02e5a..fbdf88933 100644 --- a/services/backend/src/main/kotlin/com/hopa/backend/pairing/PairingService.kt +++ b/services/backend/src/main/kotlin/com/hopa/backend/pairing/PairingService.kt @@ -3,6 +3,7 @@ package com.hopa.backend.pairing import com.hopa.backend.http.RateLimiter import com.hopa.backend.members.FounderPermissions import com.hopa.backend.store.Database +import java.sql.Connection import java.sql.Timestamp import java.time.Instant import java.util.Base64 @@ -68,7 +69,7 @@ class PairingService( return PairingOutcome.Refused("E_SCHEMA", "unknown household") } } - val member = UUID.randomUUID().toString() + val founder = UUID.randomUUID().toString() val session = Tokens.mint() val expiresAt = clock() + SESSION_MS @@ -80,14 +81,17 @@ class PairingService( it.executeUpdate() } } - connection.prepareStatement( - "insert into members(id, household_id, role, display_name) " + - "values (?::uuid, ?::uuid, 'owner', ?)", - ).use { - it.setString(1, member) - it.setString(2, household) - it.setString(3, memberName) - it.executeUpdate() + // A device minted into an existing household joins that household's + // owner member; a household of one per device would split the group. + // Only a household with no owner yet gets a member here. + val member = if (householdId == null) { + insertOwner(connection, household, founder, memberName) + founder + } else { + ownerOf(connection, household) ?: run { + insertOwner(connection, household, founder, memberName) + founder + } } if (householdId == null) FounderPermissions.grant(connection, household, member) connection.prepareStatement( @@ -219,6 +223,33 @@ class PairingService( else -> null } + /** Inserts the household's owner member. */ + private fun insertOwner(connection: Connection, household: String, member: String, name: String) { + connection.prepareStatement( + "insert into members(id, household_id, role, display_name) " + + "values (?::uuid, ?::uuid, 'owner', ?)", + ).use { + it.setString(1, member) + it.setString(2, household) + it.setString(3, name) + it.executeUpdate() + } + } + + /** + * The household's first owner member, under the caller's tenant setting. + * Ordered by `created_at, id` so an older roster without a founder still + * resolves deterministically. + */ + private fun ownerOf(connection: Connection, household: String): String? = + connection.prepareStatement( + "select id from members where household_id = ?::uuid and role = 'owner' " + + "order by created_at, id limit 1", + ).use { + it.setString(1, household) + it.executeQuery().use { rows -> if (rows.next()) rows.getString(1) else null } + } + private fun decodeKey(value: String): ByteArray? = try { Base64.getDecoder().decode(value) diff --git a/services/backend/src/test/kotlin/com/hopa/backend/pairing/PairingMintTest.kt b/services/backend/src/test/kotlin/com/hopa/backend/pairing/PairingMintTest.kt new file mode 100644 index 000000000..ea8c6187a --- /dev/null +++ b/services/backend/src/test/kotlin/com/hopa/backend/pairing/PairingMintTest.kt @@ -0,0 +1,81 @@ +package com.hopa.backend.pairing + +import com.hopa.backend.harness.PostgresHarness +import com.hopa.backend.harness.newDevice +import com.hopa.backend.harness.newHousehold +import com.hopa.backend.harness.seedHousehold +import java.util.Base64 +import java.util.UUID +import java.util.concurrent.atomic.AtomicLong +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test + +/** + * `mint` for an existing household: the claimed device joins that household's + * owner member, so a second pairing does not split the household in two. + */ +class PairingMintTest { + private val db = PostgresHarness.appDatabase() + private val clock = AtomicLong(1_763_212_800_000) + private val pairing = PairingService(db, clock = clock::get, perMinute = 100) + + private fun claim(session: String): PairingOutcome = pairing.claim( + ClaimRequest( + session = session, + platform = "windows", + name = "Desktop", + publicKey = Base64.getEncoder().encodeToString(ByteArray(32) { 1 }), + alg = "x25519", + ), + "198.51.100.1", + ) + + @Test + fun `a mint for an existing household puts the claimed device on its owner member`() { + val household = newHousehold() + val owner = UUID.randomUUID().toString() + seedHousehold(db, household, newDevice(), owner) + + val minted = (pairing.mint("Home", "Second PC", "198.51.100.1", household) as PairingOutcome.Ok).value + val claimed = (claim(minted.session) as PairingOutcome.Ok).value + + assertEquals(household, claimed.householdId) + assertEquals(1, db.tenant(household) { connection -> connection.count("select count(*) from members") }) + assertEquals( + listOf(owner, owner), + db.tenant(household) { connection -> + connection.strings("select member_id::text from devices order by created_at, id") + }, + ) + } + + @Test + fun `a mint for a new household creates its founder owner`() { + val minted = pairing.mint("Fresh", "First phone", "198.51.100.2", null) + + val created = (minted as PairingOutcome.Ok).value + val household = created.qr.substringAfter("&h=").substringBefore("&") + assertEquals(1, db.tenant(household) { connection -> connection.count("select count(*) from households") }) + assertEquals(1, db.tenant(household) { connection -> connection.count("select count(*) from members") }) + assertEquals( + listOf("owner"), + db.tenant(household) { connection -> connection.strings("select role from members") }, + ) + } + + private fun java.sql.Connection.count(sql: String): Int = + createStatement().use { statement -> + statement.executeQuery(sql).use { rows -> + rows.next() + rows.getInt(1) + } + } + + private fun java.sql.Connection.strings(sql: String): List = + createStatement().use { statement -> + statement.executeQuery(sql).use { rows -> + buildList { while (rows.next()) add(rows.getString(1)) } + } + } +} From 5ad80a38d7adf96ace9ae2d20dd5586554882084 Mon Sep 17 00:00:00 2001 From: aharonamir Date: Sun, 29 Nov 2026 22:33:50 +0200 Subject: [PATCH 04/58] Document the sync v0 routes in the backend OpenAPI The spec gains POST and GET /v1/sync/ops next to the board paths with the same bearerAuth security, the sealed op shapes, the batch and page limits, and the E_CONFLICT rule the store enforces. check-openapi.py passes both ways. Part of #32 --- spec/openapi/backend.v1.yaml | 127 +++++++++++++++++++++++++++++++++++ 1 file changed, 127 insertions(+) diff --git a/spec/openapi/backend.v1.yaml b/spec/openapi/backend.v1.yaml index 61d046930..7d473d742 100644 --- a/spec/openapi/backend.v1.yaml +++ b/spec/openapi/backend.v1.yaml @@ -1082,6 +1082,129 @@ paths: "401": { $ref: "#/components/responses/Unauthorized" } "403": { $ref: "#/components/responses/ScopeRefused" } "413": { $ref: "#/components/responses/PayloadTooLarge" } + /v1/sync/ops: + post: + summary: Push a batch of sealed ops to the caller's member log + description: | + Appends up to 100 ops for the bearer device's member, in order, at the + household's next seqs. The server attests `fromDevice` and `memberId` from + the token and never reads a body: `ct` is base64 of IV(12) || + ciphertext || tag(16), 28 bytes to 64 KiB. A replayed `opId` with the same + body is acked with its stored seq and `duplicate: true` and burns no seq; + the same `opId` with another body, or a second `turn.append` for a turn + already in its thread, is 409 `E_CONFLICT`. A rejected batch writes + nothing. The cursor is client-owned (there is no server cursor table); + `seq` order is authoritative and `clientAt` is advisory. + security: + - bearerAuth: [] + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [ops] + properties: + ops: + type: array + minItems: 1 + maxItems: 100 + items: + type: object + required: [opId, kind, threadId, ct, clientAt] + properties: + opId: { type: string, description: "Client-chosen id, unique per household." } + kind: { $ref: "#/components/schemas/SyncKind" } + threadId: { type: string, description: "Client thread id (`c-…`)." } + turnId: + type: string + nullable: true + description: Required by `turn.append`, absent from `thread.upsert`. + ct: { type: string, format: byte, description: "Base64 of IV(12) || ciphertext || tag(16)." } + clientAt: { type: integer, format: int64, minimum: 0, description: The author's clock, advisory. } + responses: + "200": + description: The batch's seqs and the household head after it + content: + application/json: + schema: + type: object + required: [head, accepted] + properties: + head: { type: integer, format: int64, minimum: 0 } + accepted: + type: array + items: + type: object + required: [opId, seq, duplicate] + properties: + opId: { type: string } + seq: { type: integer, format: int64, minimum: 1 } + duplicate: { type: boolean, description: Already stored; nothing was written and no seq burned. } + "400": + description: An empty batch, a bad kind or shape, a bad `ct` or an oversize ciphertext (`E_SCHEMA`) + content: + application/json: + schema: { $ref: "#/components/schemas/Error" } + "401": { $ref: "#/components/responses/Unauthorized" } + "409": + description: The op id is stored with another body, or the turn is already in its thread (`E_CONFLICT`) + content: + application/json: + schema: { $ref: "#/components/schemas/Error" } + "413": { $ref: "#/components/responses/PayloadTooLarge" } + get: + summary: Pull the caller's member log after a seq, ascending + description: | + The ops of the bearer device's member with a seq above `after`, oldest + first, at most `limit` (default and cap 200). Seqs are the household's, so + a member sees gaps where other members wrote; a member never reads another + member's ops. `head` is the household's latest seq. The cursor lives on the + client and travels as `after`. + security: + - bearerAuth: [] + parameters: + - name: after + in: query + required: false + schema: { type: integer, format: int64, minimum: 0, default: 0 } + - name: limit + in: query + required: false + schema: { type: integer, minimum: 1, maximum: 200, default: 200 } + responses: + "200": + description: One page of ops + content: + application/json: + schema: + type: object + required: [ops, hasMore, head] + properties: + hasMore: { type: boolean, description: More ops follow the last one on this page. } + head: { type: integer, format: int64, minimum: 0 } + ops: + type: array + items: + type: object + required: [seq, opId, kind, threadId, fromDevice, memberId, clientAt, at, ct] + properties: + seq: { type: integer, format: int64, minimum: 1 } + opId: { type: string } + kind: { $ref: "#/components/schemas/SyncKind" } + threadId: { type: string } + turnId: { type: string, nullable: true } + fromDevice: { type: string, format: uuid } + memberId: { type: string, format: uuid } + clientAt: { type: integer, format: int64, minimum: 0 } + at: { type: string, format: date-time, description: When the server stored the op. } + ct: { type: string, format: byte, description: "Base64 of IV(12) || ciphertext || tag(16)." } + "400": + description: A negative `after` or a non-numeric `limit` (`E_SCHEMA`) + content: + application/json: + schema: { $ref: "#/components/schemas/Error" } + "401": { $ref: "#/components/responses/Unauthorized" } /v1/scope-keys/{scope}: parameters: - name: scope @@ -1334,6 +1457,10 @@ components: type: string enum: [shared, private] description: "shared reads with the household key; private only with the current private-scope key (ADR-0033)." + SyncKind: + type: string + enum: [thread.upsert, turn.append] + description: "thread.upsert seals a thread's metadata (deletedAt > 0 is a tombstone); turn.append adds one turn to a thread." Permission: type: string enum: [board.private, group.manage] From 12ce232028712183d517aa752cf12228d9fbeee2 Mon Sep 17 00:00:00 2001 From: aharonamir Date: Sun, 29 Nov 2026 23:06:48 +0200 Subject: [PATCH 05/58] Fan out sync.changed to the sender's other devices of the member One frame per push carrying the highest new seq, only to the same household and member, never to the sender. A duplicate-only batch sends nothing. Part of #32. --- .../com/hopa/backend/sync/SyncGateway.kt | 56 +++++ .../com/hopa/backend/sync/SyncRoutes.kt | 30 ++- .../com/hopa/backend/sync/SyncGatewayTest.kt | 191 ++++++++++++++++++ 3 files changed, 270 insertions(+), 7 deletions(-) create mode 100644 services/backend/src/main/kotlin/com/hopa/backend/sync/SyncGateway.kt create mode 100644 services/backend/src/test/kotlin/com/hopa/backend/sync/SyncGatewayTest.kt diff --git a/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncGateway.kt b/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncGateway.kt new file mode 100644 index 000000000..09234eac6 --- /dev/null +++ b/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncGateway.kt @@ -0,0 +1,56 @@ +package com.hopa.backend.sync + +import com.hopa.backend.auth.DeviceIdentity +import com.hopa.backend.gateway.DeviceRegistry +import com.hopa.backend.protocol.Envelope +import com.hopa.backend.protocol.GatewayCodec +import com.hopa.backend.trace.TraceIds +import com.hopa.backend.trace.TraceRecorder +import java.util.UUID +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put + +/** + * The gateway side of sync v0 (issue #32 Phase 2): after a push, the sender's + * other online devices of the same household **and member** hear that a seq + * exists, so they pull after their own cursor. + * + * One frame per push, never one per op: the peer pages everything above its + * cursor anyway. The frame carries only the seq, never an op or its plaintext. + * The sender hears nothing, and a member's devices are invisible to the other + * members' devices. Offline peers get no frame and no push wake in v0; they + * pull from their cursor when they reconnect or come to the foreground. + */ +class SyncGateway( + private val registry: DeviceRegistry, + private val traces: TraceRecorder = TraceRecorder.None, + private val now: () -> Long = System::currentTimeMillis, +) { + /** Tells the sender's other online devices of the same member that [seq] exists. */ + fun changed(sender: DeviceIdentity, seq: Long, traceparent: String? = null) { + val trace = traceparent ?: TraceIds.newTraceparent() + val traceId = TraceIds.traceId(trace) ?: TraceIds.traceId(TraceIds.newTraceparent())!! + traces.span(sender.householdId, traceId, "sync.fanout", sender.deviceId, null) { + registry.householdSessions(sender.householdId) + .filter { it.identity.memberId == sender.memberId } + .filter { it.identity.deviceId != sender.deviceId } + .forEach { session -> + session.outgoing.trySend( + GatewayCodec.encode(changedFrame(session.identity.deviceId, seq, trace)), + ) + } + } + } + + private fun changedFrame(to: String, seq: Long, trace: String): Envelope = Envelope( + v = 1, + id = UUID.randomUUID().toString(), + type = "sync.changed", + ts = now(), + trace = trace, + to = to, + body = buildJsonObject { + put("seq", seq) + }, + ) +} diff --git a/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncRoutes.kt b/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncRoutes.kt index 009760ffb..679a6aa8d 100644 --- a/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncRoutes.kt +++ b/services/backend/src/main/kotlin/com/hopa/backend/sync/SyncRoutes.kt @@ -60,8 +60,16 @@ internal class SyncOpsResponse(val ops: List, val hasMore: Boolean, * Sync v0 (issue #32 Phase 2): push a batch of sealed ops, pull the caller's * member log after a seq. The household and member always come from the bearer * token, never from the wire, and no route ever reads an op body. + * + * A push with at least one new op tells the sender's other online devices of + * the same member (one `sync.changed` for the highest new seq); a batch that is + * entirely duplicates tells nobody, because the first push already did. */ -fun Application.syncRoutes(config: ServerConfig, service: SyncService = SyncService(config.syncStore)) { +fun Application.syncRoutes( + config: ServerConfig, + service: SyncService = SyncService(config.syncStore), + gateway: SyncGateway = SyncGateway(config.registry, config.traces), +) { routing { post("/v1/sync/ops") { val identity = call.bearerDevice(config) ?: return@post @@ -84,12 +92,20 @@ fun Application.syncRoutes(config: ServerConfig, service: SyncService = SyncServ return@post } when (val result = service.push(identity, ops)) { - is SyncResult.Ok -> call.respond( - SyncPushResponse( - head = service.head(identity), - accepted = result.value.map { SyncAckView(it.opId, it.seq, it.duplicate) }, - ), - ) + is SyncResult.Ok -> { + val fresh = result.value.filter { !it.duplicate } + if (fresh.isNotEmpty()) { + // One frame per push, not per op: the peer pulls + // everything after its cursor anyway. + gateway.changed(identity, fresh.maxOf { it.seq }) + } + call.respond( + SyncPushResponse( + head = service.head(identity), + accepted = result.value.map { SyncAckView(it.opId, it.seq, it.duplicate) }, + ), + ) + } is SyncResult.Failed -> call.respondFailure(result) } diff --git a/services/backend/src/test/kotlin/com/hopa/backend/sync/SyncGatewayTest.kt b/services/backend/src/test/kotlin/com/hopa/backend/sync/SyncGatewayTest.kt new file mode 100644 index 000000000..eaf3628ec --- /dev/null +++ b/services/backend/src/test/kotlin/com/hopa/backend/sync/SyncGatewayTest.kt @@ -0,0 +1,191 @@ +package com.hopa.backend.sync + +import com.hopa.backend.ServerConfig +import com.hopa.backend.auth.DeviceIdentity +import com.hopa.backend.board.BoardFrames.online +import com.hopa.backend.harness.MapAuth +import com.hopa.backend.harness.bodyString +import com.hopa.backend.module +import com.hopa.backend.protocol.Envelope +import com.hopa.backend.trace.TraceRecorder +import io.ktor.client.HttpClient +import io.ktor.client.plugins.websocket.WebSockets +import io.ktor.client.request.header +import io.ktor.client.request.post +import io.ktor.client.request.setBody +import io.ktor.client.statement.HttpResponse +import io.ktor.http.ContentType +import io.ktor.http.HttpStatusCode +import io.ktor.http.contentType +import io.ktor.server.testing.testApplication +import java.util.Base64 +import java.util.UUID +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +/** + * `sync.changed` after a push (M2): the sender's other devices of the same + * household **and member** hear that a seq exists, once per push, and nobody + * else does. The push goes through the real HTTP route; the peers are real + * gateway sockets. + */ +class SyncGatewayTest { + private val householdId = UUID.randomUUID().toString() + private val memberId = UUID.randomUUID().toString() + private val siblingId = UUID.randomUUID().toString() + + private fun device(member: String = memberId) = + DeviceIdentity(UUID.randomUUID().toString(), householdId, member) + + private fun config(group: List, traces: TraceRecorder = TraceRecorder.None) = ServerConfig( + version = "0.1.0", + auth = MapAuth(group.associateBy { "tok-${it.deviceId}" }), + syncStore = InMemorySyncStore(clock = { CLIENT_AT }), + traces = traces, + ) + + private fun op(turnId: String = "m-" + UUID.randomUUID()): JsonObject = buildJsonObject { + put("opId", UUID.randomUUID().toString()) + put("kind", SyncService.KIND_TURN_APPEND) + put("threadId", "c-1") + put("turnId", turnId) + put("ct", Base64.getEncoder().encodeToString(ByteArray(40) { 7 })) + put("clientAt", CLIENT_AT) + } + + private suspend fun HttpClient.push(sender: DeviceIdentity, vararg ops: JsonObject): HttpResponse = + post("/v1/sync/ops") { + header("Authorization", "Bearer tok-${sender.deviceId}") + contentType(ContentType.Application.Json) + setBody(buildJsonObject { put("ops", JsonArray(ops.toList())) }.toString()) + } + + @Test + fun `the sender gets no frame and the peer of the same member gets one sync changed`() = testApplication { + val (ana, ben) = listOf(device(), device()) + val traces = RecordingTraces() + application { module(config(listOf(ana, ben), traces)) } + val http = createClient { install(WebSockets) } + val anaSocket = online(http, ana.deviceId) + val benSocket = online(http, ben.deviceId) + + assertEquals(HttpStatusCode.OK, client.push(ana, op()).status) + + val changed = benSocket.expect("sync.changed") + assertEquals("1", changed.bodyString("seq")) + assertEquals(ben.deviceId, changed.to) + anaSocket.expectNothing("sync.changed") + assertEquals(1, traces.operations.count { it == "sync.fanout" }) + } + + @Test + fun `a device of another member in the same household gets no frame`() = testApplication { + val ana = device() + val ben = device() + val cai = device(siblingId) + application { module(config(listOf(ana, ben, cai))) } + val http = createClient { install(WebSockets) } + online(http, ana.deviceId) + val benSocket = online(http, ben.deviceId) + val caiSocket = online(http, cai.deviceId) + + assertEquals(HttpStatusCode.OK, client.push(ana, op()).status) + + assertEquals("1", benSocket.expect("sync.changed").bodyString("seq")) + caiSocket.expectNothing("sync.changed") + } + + @Test + fun `a duplicate-only push sends no frame`() = testApplication { + val (ana, ben) = listOf(device(), device()) + application { module(config(listOf(ana, ben))) } + val http = createClient { install(WebSockets) } + online(http, ana.deviceId) + val benSocket = online(http, ben.deviceId) + val first = op() + + client.push(ana, first) + assertEquals("1", benSocket.expect("sync.changed").bodyString("seq")) + + assertEquals(HttpStatusCode.OK, client.push(ana, first).status) + benSocket.expectNothing("sync.changed") + + // The socket is still usable and a genuinely new op still tells the peer. + client.push(ana, op()) + assertEquals("2", benSocket.expect("sync.changed").bodyString("seq")) + } + + @Test + fun `a batch of three new ops sends exactly one frame with the highest seq`() = testApplication { + val (ana, ben) = listOf(device(), device()) + application { module(config(listOf(ana, ben))) } + val http = createClient { install(WebSockets) } + online(http, ana.deviceId) + val benSocket = online(http, ben.deviceId) + + assertEquals(HttpStatusCode.OK, client.push(ana, op(), op(), op()).status) + + assertEquals("3", benSocket.expect("sync.changed").bodyString("seq")) + benSocket.expectNothing("sync.changed") + } + + @Test + fun `an offline peer costs nothing and the sender still gets no frame`() = testApplication { + val (ana, ben) = listOf(device(), device()) + application { module(config(listOf(ana, ben))) } + val http = createClient { install(WebSockets) } + val anaSocket = online(http, ana.deviceId) + + assertEquals(HttpStatusCode.OK, client.push(ana, op()).status) + + anaSocket.expectNothing("sync.changed") + } + + @Test + fun `a device cannot spoof a sync changed frame`() = testApplication { + val (ana, ben) = listOf(device(), device()) + application { module(config(listOf(ana, ben))) } + val http = createClient { install(WebSockets) } + val anaSocket = online(http, ana.deviceId) + val benSocket = online(http, ben.deviceId) + + anaSocket.send( + Envelope( + v = 1, + id = UUID.randomUUID().toString(), + type = "sync.changed", + ts = 1, + to = ben.deviceId, + body = buildJsonObject { put("seq", 9) }, + ), + ) + + assertEquals("E_UNSUPPORTED", anaSocket.expect("error").bodyString("code")) + benSocket.expectNothing("sync.changed") + } + + private companion object { + const val CLIENT_AT = 1_733_000_000_000L + } +} + +/** Remembers span operations, so the test can see the fan-out was traced. */ +private class RecordingTraces : TraceRecorder { + val operations = mutableListOf() + + override fun span( + householdId: String, + traceId: String, + operation: String, + deviceId: String?, + taskId: String?, + block: () -> T, + ): T { + operations += operation + return block() + } +} From 8d5222ef07702b24a30e103ec127d056c49b573d Mon Sep 17 00:00:00 2001 From: aharonamir Date: Sun, 29 Nov 2026 23:06:55 +0200 Subject: [PATCH 06/58] Add the sync.changed gateway protocol surface The validator accepts the type, the gateway schema enumerates it with a non-negative seq, a fixture pins body:{seq:7}, and the sync mini-design documents the one-frame-per-push rule. Part of #32. --- docs/project/plan/backend/tasks/week2-sync.md | 10 +++++++ .../backend/protocol/EnvelopeValidator.kt | 5 ++++ .../backend/protocol/EnvelopeValidatorTest.kt | 29 +++++++++++++++++++ spec/fixtures/gateway-sync.json | 22 ++++++++++++++ spec/schemas/gateway.v1.schema.json | 21 +++++++++++++- 5 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 spec/fixtures/gateway-sync.json diff --git a/docs/project/plan/backend/tasks/week2-sync.md b/docs/project/plan/backend/tasks/week2-sync.md index 1cd3a13a5..484a9dbb6 100644 --- a/docs/project/plan/backend/tasks/week2-sync.md +++ b/docs/project/plan/backend/tasks/week2-sync.md @@ -61,6 +61,16 @@ no server cursor table. Each device stores the last seq it applied and passes it as `after`; `after=0` reads from the start. The seq belongs to the household, so a member sees gaps where another member appended. +## Gateway notification + +After a push with at least one new op, the backend sends one `sync.changed +{seq}` frame, carrying the highest new seq, to every other **online** device of +the same `household_id` and `member_id`; never to the pusher. A batch that is +entirely duplicates sends nothing, because the first push already did. The +frame is server-authored and carries no op: the peer pulls +`GET /v1/sync/ops?after=`. v0 has no FCM wake; an offline device +pulls on reconnect or when it comes to the foreground. + ## Merge rule Server `seq` order is authoritative and the log is append-only. `clientAt` is diff --git a/services/backend/src/main/kotlin/com/hopa/backend/protocol/EnvelopeValidator.kt b/services/backend/src/main/kotlin/com/hopa/backend/protocol/EnvelopeValidator.kt index 7cf43412b..a70db514c 100644 --- a/services/backend/src/main/kotlin/com/hopa/backend/protocol/EnvelopeValidator.kt +++ b/services/backend/src/main/kotlin/com/hopa/backend/protocol/EnvelopeValidator.kt @@ -37,6 +37,11 @@ object EnvelopeValidator { "board.op", "board.op.ack", "board.changed", + // Sync v0 (issue #32 Phase 2): after a push, the sender's other devices + // of the same member hear that a seq exists. The body is only + // `{"seq": N}`; like `board.changed` it is not validated further, so a + // malformed seq is ignored by the client rather than refused. + "sync.changed", "error", "ping", "pong", diff --git a/services/backend/src/test/kotlin/com/hopa/backend/protocol/EnvelopeValidatorTest.kt b/services/backend/src/test/kotlin/com/hopa/backend/protocol/EnvelopeValidatorTest.kt index f3897b0e5..24066a39a 100644 --- a/services/backend/src/test/kotlin/com/hopa/backend/protocol/EnvelopeValidatorTest.kt +++ b/services/backend/src/test/kotlin/com/hopa/backend/protocol/EnvelopeValidatorTest.kt @@ -154,6 +154,35 @@ class EnvelopeValidatorTest { assertTrue(refused >= 4, "expected at least four schema-level board refusals") } + @Test + fun `a sync changed envelope validates`() { + val envelope = envelope().copy( + type = "sync.changed", + body = buildJsonObject { put("seq", JsonPrimitive(7)) }, + ) + + assertNull(EnvelopeValidator.validate(GatewayCodec.encode(envelope), envelope)) + } + + @Test + fun `the sync fixture replays through the validator`() { + val raw = requireNotNull(javaClass.getResource("/fixtures/gateway-sync.json")).readText() + val cases = Json.parseToJsonElement(raw).jsonObject["cases"]!!.jsonArray + var checked = 0 + for (element in cases) { + val case = element.jsonObject + val name = case["name"]!!.jsonPrimitive.content + val message = case["message"]!!.jsonObject.toString() + val actual = when (val decoded = GatewayCodec.decode(message)) { + is DecodeResult.Failed -> decoded.error.code + is DecodeResult.Ok -> EnvelopeValidator.validate(message, decoded.envelope)?.code + } + assertNull(actual, name) + checked++ + } + assertEquals(1, checked) + } + @Test fun `a board op at the ciphertext bounds passes and one byte over is refused`() { fun op(rawBytes: Int): Envelope = envelope().copy( diff --git a/spec/fixtures/gateway-sync.json b/spec/fixtures/gateway-sync.json new file mode 100644 index 000000000..2c967923a --- /dev/null +++ b/spec/fixtures/gateway-sync.json @@ -0,0 +1,22 @@ +{ + "version": 1, + "description": "Sync v0 vectors (issue #32 Phase 2). After a push, the gateway tells the sender's other online devices of the same household and member that a seq exists. The frame carries only the seq: never an op, its ciphertext or its plaintext.", + "cases": [ + { + "name": "sync.changed to another device of the same member", + "ok": true, + "schema": true, + "direction": "server", + "message": { + "v": 1, + "id": "7b2e4d3a-9c6f-4a5b-8d1e-3f4a5b6c7d8e", + "type": "sync.changed", + "ts": 1763300000030, + "to": "dev-01h-phone", + "body": { + "seq": 7 + } + } + } + ] +} diff --git a/spec/schemas/gateway.v1.schema.json b/spec/schemas/gateway.v1.schema.json index 4c8c28b93..d4b51b601 100644 --- a/spec/schemas/gateway.v1.schema.json +++ b/spec/schemas/gateway.v1.schema.json @@ -33,6 +33,7 @@ "board.op", "board.op.ack", "board.changed", + "sync.changed", "error", "ping", "pong" @@ -65,7 +66,7 @@ }, "body": { "type": "object", - "description": "Type-specific payload. Ciphertext from week 2 for task types; the server never renders those. The three diag types (diag.ping, diag.state, diag.reset) are the only plaintext payloads, authored by the admin console and capped at 32 KiB. The board types carry plaintext routing metadata only (scope, seq, keyEpoch, duplicate) next to the op ciphertext ct (ADR-0033).", + "description": "Type-specific payload. Ciphertext from week 2 for task types; the server never renders those. The three diag types (diag.ping, diag.state, diag.reset) are the only plaintext payloads, authored by the admin console and capped at 32 KiB. The board types carry plaintext routing metadata only (scope, seq, keyEpoch, duplicate) next to the op ciphertext ct (ADR-0033); sync.changed carries only seq.", "default": {} } }, @@ -110,6 +111,16 @@ "required": ["body"], "properties": { "body": { "$ref": "#/$defs/boardChanged" } } } + }, + { + "if": { + "required": ["type"], + "properties": { "type": { "const": "sync.changed" } } + }, + "then": { + "required": ["body"], + "properties": { "body": { "$ref": "#/$defs/syncChanged" } } + } } ], "$defs": { @@ -155,6 +166,14 @@ "scope": { "$ref": "#/$defs/boardScope" }, "seq": { "type": "integer", "minimum": 1 } } + }, + "syncChanged": { + "type": "object", + "description": "Server to every other online device of the same household and member: the member's log has an op up to seq (issue #32 Phase 2, sync v0). Never sent to the pusher. The client pulls after its own cursor; the frame carries no op.", + "required": ["seq"], + "properties": { + "seq": { "type": "integer", "minimum": 0 } + } } } } From c2c9ea6f6c0e658afd9846a9407f5fb39d548a0e Mon Sep 17 00:00:00 2001 From: aharonamir Date: Sun, 29 Nov 2026 23:07:01 +0200 Subject: [PATCH 07/58] Route sync.changed to onSyncChanged on the client The link exposes a seq-only handler; a missing, non-integer or negative seq is ignored so a malformed frame never costs the socket or logs a body. Part of #32. --- .../com/hopa/backend/link/BackendClient.kt | 35 ++++++++++++-- .../com/hopa/backend/link/BackendLink.kt | 9 ++++ .../backend/link/BackendDeliveriesTest.kt | 47 +++++++++++++++++++ 3 files changed, 87 insertions(+), 4 deletions(-) diff --git a/core/backend/src/main/kotlin/com/hopa/backend/link/BackendClient.kt b/core/backend/src/main/kotlin/com/hopa/backend/link/BackendClient.kt index e70527043..5ffee420f 100644 --- a/core/backend/src/main/kotlin/com/hopa/backend/link/BackendClient.kt +++ b/core/backend/src/main/kotlin/com/hopa/backend/link/BackendClient.kt @@ -23,6 +23,7 @@ import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.intOrNull import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.longOrNull import kotlinx.serialization.json.put import okhttp3.OkHttpClient import okhttp3.Request @@ -35,10 +36,10 @@ import java.util.concurrent.TimeUnit * `device.hello` as the first frame, `Live` once the ack arrives. A frame that * cannot be decoded is ignored so a malformed message never costs the socket. * A delivered `task.create` is handed to [onTask], a plaintext `diag.*` to - * [onDiagnostic], `task.needs_approval` to [onApproval], and a task reply - * (`task.ack`, `task.progress`, `task.result`, `task.error`) to [onReply] on the - * session's coroutine scope, so a slow handler neither stalls the reader nor - * dies when the socket reconnects. + * [onDiagnostic], `task.needs_approval` to [onApproval], a task reply + * (`task.ack`, `task.progress`, `task.result`, `task.error`) to [onReply] and a + * `sync.changed` seq to [onSyncChanged] on the session's coroutine scope, so a + * slow handler neither stalls the reader nor dies when the socket reconnects. * * A `1008 E_AUTH` close refreshes the credentials once; a null refresh asks for * pairing instead of retrying, because a rotated token may never be presented @@ -70,6 +71,9 @@ class BackendClient( @Volatile override var onBoard: (suspend (BackendEnvelope) -> Unit)? = null + @Volatile + override var onSyncChanged: (suspend (Long) -> Unit)? = null + @Volatile override var onReply: (suspend (BackendEnvelope) -> Unit)? = null @@ -207,6 +211,7 @@ class BackendClient( "task.needs_approval" -> dispatchApproval(frame) "diag.ping", "diag.state", "diag.reset" -> dispatch(frame, onDiagnostic) "board.op.ack", "board.changed", "error" -> dispatch(frame, onBoard) + "sync.changed" -> dispatchSyncChanged(frame) "task.ack", "task.progress", "task.result", "task.error" -> dispatch(frame, onReply) } } @@ -275,6 +280,28 @@ class BackendClient( } } + /** + * A `sync.changed` frame carries only a seq. A frame with no seq, a + * non-integer seq or a negative one is ignored: a malformed notification + * must not cost the socket, and the next pull still reconciles. Nothing + * about the body is logged. + */ + private fun dispatchSyncChanged(frame: BackendEnvelope) { + val handler = onSyncChanged ?: return + val seq = (frame.body["seq"] as? JsonPrimitive)?.takeIf { !it.isString }?.longOrNull ?: return + if (seq < 0) return + val live = session ?: return + live.launch { + try { + handler(seq) + } catch (cancelled: CancellationException) { + throw cancelled + } catch (error: Exception) { + // A failed sync handler must not close the link. + } + } + } + companion object { /** The contract's liveness answer is local; 10 s is generous. */ private const val PING_TIMEOUT_MS = 10_000L diff --git a/core/backend/src/main/kotlin/com/hopa/backend/link/BackendLink.kt b/core/backend/src/main/kotlin/com/hopa/backend/link/BackendLink.kt index 037d828ca..7d9e8914a 100644 --- a/core/backend/src/main/kotlin/com/hopa/backend/link/BackendLink.kt +++ b/core/backend/src/main/kotlin/com/hopa/backend/link/BackendLink.kt @@ -30,6 +30,15 @@ interface BackendLink { get() = null set(@Suppress("UNUSED_PARAMETER") value) {} + /** + * Sync notifications: `sync.changed {seq}` means a peer of the same member + * wrote up to [seq], so the app pulls after its own cursor. Null where sync + * is not wired. + */ + var onSyncChanged: (suspend (Long) -> Unit)? + get() = null + set(@Suppress("UNUSED_PARAMETER") value) {} + /** A `task.needs_approval` delivery: show the question, not run a goal. */ var onApproval: (suspend (BackendEnvelope) -> Unit)? diff --git a/core/backend/src/test/kotlin/com/hopa/backend/link/BackendDeliveriesTest.kt b/core/backend/src/test/kotlin/com/hopa/backend/link/BackendDeliveriesTest.kt index fed0c4f8a..2f9208188 100644 --- a/core/backend/src/test/kotlin/com/hopa/backend/link/BackendDeliveriesTest.kt +++ b/core/backend/src/test/kotlin/com/hopa/backend/link/BackendDeliveriesTest.kt @@ -327,6 +327,48 @@ class BackendDeliveriesTest { server.shutdown() } + @Test + fun `a sync changed frame reaches onSyncChanged with its seq`() = runBlocking { + val seen = CompletableDeferred() + val server = MockWebServer() + server.enqueue( + MockResponse().withWebSocketUpgrade(object : FakeGateway() { + override fun onOpen(webSocket: WebSocket, response: Response) { + webSocket.send(helloAck(id = "a1", queued = 0)) + webSocket.send(syncChanged(seq = 7)) + } + }), + ) + val client = clientFor(server) + client.onSyncChanged = { seq -> seen.complete(seq) } + client.start(this) + assertEquals(7L, withTimeout(5_000) { seen.await() }) + client.stop() + server.shutdown() + } + + @Test + fun `a sync changed frame without a seq never calls onSyncChanged`() = runBlocking { + val calls = AtomicInteger() + val server = MockWebServer() + server.enqueue( + MockResponse().withWebSocketUpgrade(object : FakeGateway() { + override fun onOpen(webSocket: WebSocket, response: Response) { + webSocket.send(helloAck(id = "a1", queued = 0)) + webSocket.send(syncChanged(seq = null)) + } + }), + ) + val client = clientFor(server) + client.onSyncChanged = { calls.incrementAndGet() } + client.start(this) + withTimeout(5_000) { client.state.first { it is BackendState.Live } } + delay(300) // a localhost frame is read in microseconds; this is ample + assertEquals(0, calls.get()) + client.stop() + server.shutdown() + } + @Test fun `a slow handler does not stall the socket reader`() = runBlocking { val gate = CompletableDeferred() @@ -543,6 +585,11 @@ class BackendDeliveriesTest { "task":"$task","trace":"$TRACE","body":{}} """.trimIndent() + private fun syncChanged(seq: Int?): String { + val body = seq?.let { """{"seq":$it}""" } ?: "{}" + return """{"v":1,"id":"s1","type":"sync.changed","ts":2,"to":"dev-1","body":$body}""" + } + private fun deliveryFrame(): BackendEnvelope = BackendEnvelope( id = "m1", type = "task.create", From 04dd8e7ef5345b559404fe5e5024baab0265f1f3 Mon Sep 17 00:00:00 2001 From: aharonamir Date: Sun, 29 Nov 2026 23:44:06 +0200 Subject: [PATCH 08/58] Add the sync wire types and OkHttp transport The sync client needs the wire types and a transport before it can move the household's op log: sealed ops out, remote ops in, and a typed refusal for a non-2xx answer. OkHttp stays confined to OkHttpSyncHttp so the engine remains a plain JVM component. Part of #32. --- .../backend/sync/client/OkHttpSyncHttp.kt | 142 ++++++++++++++++ .../hopa/backend/sync/client/PullAnswer.kt | 8 + .../com/hopa/backend/sync/client/PushAck.kt | 14 ++ .../hopa/backend/sync/client/RemoteSyncOp.kt | 31 ++++ .../com/hopa/backend/sync/client/SealedOp.kt | 14 ++ .../hopa/backend/sync/client/SyncCursor.kt | 8 + .../com/hopa/backend/sync/client/SyncDraft.kt | 25 +++ .../com/hopa/backend/sync/client/SyncHttp.kt | 12 ++ .../backend/sync/client/SyncHttpException.kt | 11 ++ .../com/hopa/backend/sync/client/SyncKind.kt | 13 ++ .../hopa/backend/sync/client/SyncTarget.kt | 16 ++ .../backend/sync/client/OkHttpSyncHttpTest.kt | 159 ++++++++++++++++++ 12 files changed, 453 insertions(+) create mode 100644 core/backend/src/main/kotlin/com/hopa/backend/sync/client/OkHttpSyncHttp.kt create mode 100644 core/backend/src/main/kotlin/com/hopa/backend/sync/client/PullAnswer.kt create mode 100644 core/backend/src/main/kotlin/com/hopa/backend/sync/client/PushAck.kt create mode 100644 core/backend/src/main/kotlin/com/hopa/backend/sync/client/RemoteSyncOp.kt create mode 100644 core/backend/src/main/kotlin/com/hopa/backend/sync/client/SealedOp.kt create mode 100644 core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncCursor.kt create mode 100644 core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncDraft.kt create mode 100644 core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncHttp.kt create mode 100644 core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncHttpException.kt create mode 100644 core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncKind.kt create mode 100644 core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncTarget.kt create mode 100644 core/backend/src/test/kotlin/com/hopa/backend/sync/client/OkHttpSyncHttpTest.kt diff --git a/core/backend/src/main/kotlin/com/hopa/backend/sync/client/OkHttpSyncHttp.kt b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/OkHttpSyncHttp.kt new file mode 100644 index 000000000..72da047d7 --- /dev/null +++ b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/OkHttpSyncHttp.kt @@ -0,0 +1,142 @@ +package com.hopa.backend.sync.client + +import com.hopa.contracts.json.HopaJson +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.boolean +import kotlinx.serialization.json.buildJsonObject +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.put +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody +import okhttp3.Response +import java.util.Base64 +import java.util.concurrent.TimeUnit + +/** + * [SyncHttp] over OkHttp: `POST /v1/sync/ops` and `GET /v1/sync/ops?after=&limit=` + * with the caller's bearer. It moves base64 ciphertext only; it never opens a + * payload. + */ +class OkHttpSyncHttp( + private val client: OkHttpClient = defaultClient(), +) : SyncHttp { + override suspend fun push(token: String, baseUrl: String, ops: List): PushAnswer { + val request = Request.Builder() + .url(url(baseUrl, SYNC_PATH)) + .header("Authorization", "Bearer $token") + .post(pushBody(ops).toRequestBody(json)) + .build() + return withContext(Dispatchers.IO) { + client.newCall(request).execute().use { response -> + if (!response.isSuccessful) throw failure(response) + parsePush(response.body?.string().orEmpty()) + } + } + } + + override suspend fun pull(token: String, baseUrl: String, after: Long, limit: Int): PullAnswer { + val request = Request.Builder() + .url(url(baseUrl, "$SYNC_PATH?after=$after&limit=$limit")) + .header("Authorization", "Bearer $token") + .get() + .build() + return withContext(Dispatchers.IO) { + client.newCall(request).execute().use { response -> + if (!response.isSuccessful) throw failure(response) + parsePull(response.body?.string().orEmpty()) + } + } + } + + private fun url(baseUrl: String, path: String): String = baseUrl.trimEnd('/') + path + + private fun pushBody(ops: List): String = buildJsonObject { + put( + "ops", + JsonArray( + ops.map { op -> + buildJsonObject { + put("opId", op.opId) + put("kind", op.kind.wire) + put("threadId", op.threadId) + op.turnId?.let { put("turnId", it) } + put("ct", op.ct) + put("clientAt", op.clientAt) + } + }, + ), + ) + }.toString() + + private fun parsePush(text: String): PushAnswer { + val root = HopaJson.element.parseToJsonElement(text).jsonObject + return PushAnswer( + head = root.getValue("head").jsonPrimitive.long, + accepted = root.getValue("accepted").jsonArray.map { element -> + val ack = element.jsonObject + PushAck( + opId = ack.getValue("opId").jsonPrimitive.content, + seq = ack.getValue("seq").jsonPrimitive.long, + duplicate = ack.getValue("duplicate").jsonPrimitive.boolean, + ) + }, + ) + } + + private fun parsePull(text: String): PullAnswer { + val root = HopaJson.element.parseToJsonElement(text).jsonObject + return PullAnswer( + ops = root.getValue("ops").jsonArray.map(::parseOp), + hasMore = root.getValue("hasMore").jsonPrimitive.boolean, + head = root.getValue("head").jsonPrimitive.long, + ) + } + + private fun parseOp(element: JsonElement): RemoteSyncOp { + val op = element.jsonObject + return RemoteSyncOp( + seq = op.getValue("seq").jsonPrimitive.long, + opId = op.getValue("opId").jsonPrimitive.content, + kind = SyncKind.fromWire(op.getValue("kind").jsonPrimitive.content), + threadId = op.getValue("threadId").jsonPrimitive.content, + turnId = op["turnId"]?.jsonPrimitive?.contentOrNull, + fromDevice = op.getValue("fromDevice").jsonPrimitive.content, + memberId = op.getValue("memberId").jsonPrimitive.content, + clientAt = op.getValue("clientAt").jsonPrimitive.long, + at = op.getValue("at").jsonPrimitive.content, + ciphertext = Base64.getDecoder().decode(op.getValue("ct").jsonPrimitive.content), + ) + } + + private fun failure(response: Response): SyncHttpException { + val error = runCatching { + HopaJson.element.parseToJsonElement(response.body?.string().orEmpty()) + .jsonObject.getValue("error").jsonObject + }.getOrNull() + return SyncHttpException( + code = error?.get("code")?.jsonPrimitive?.contentOrNull, + message = error?.get("message")?.jsonPrimitive?.contentOrNull ?: DEFAULT_FAILURE, + status = response.code, + ) + } + + companion object { + private const val SYNC_PATH = "/v1/sync/ops" + private const val DEFAULT_FAILURE = "sync call failed" + private val json = "application/json".toMediaType() + + /** The production client: a 10 s call timeout, so a sync pass cannot hang forever. */ + fun defaultClient(): OkHttpClient = OkHttpClient.Builder() + .callTimeout(10, TimeUnit.SECONDS) + .build() + } +} diff --git a/core/backend/src/main/kotlin/com/hopa/backend/sync/client/PullAnswer.kt b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/PullAnswer.kt new file mode 100644 index 000000000..f680794e2 --- /dev/null +++ b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/PullAnswer.kt @@ -0,0 +1,8 @@ +package com.hopa.backend.sync.client + +/** One page of the caller's op log after a cursor. */ +data class PullAnswer( + val ops: List, + val hasMore: Boolean, + val head: Long, +) diff --git a/core/backend/src/main/kotlin/com/hopa/backend/sync/client/PushAck.kt b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/PushAck.kt new file mode 100644 index 000000000..98a74e92f --- /dev/null +++ b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/PushAck.kt @@ -0,0 +1,14 @@ +package com.hopa.backend.sync.client + +/** The server's answer to one op of a push. [seq] is stable for a duplicate. */ +data class PushAck( + val opId: String, + val seq: Long, + val duplicate: Boolean, +) + +/** The answer to a push: the household head after it and one ack per op. */ +data class PushAnswer( + val head: Long, + val accepted: List, +) diff --git a/core/backend/src/main/kotlin/com/hopa/backend/sync/client/RemoteSyncOp.kt b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/RemoteSyncOp.kt new file mode 100644 index 000000000..b1e5e7ca5 --- /dev/null +++ b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/RemoteSyncOp.kt @@ -0,0 +1,31 @@ +package com.hopa.backend.sync.client + +/** + * One op as the server stores it and hands it back. [ciphertext] is still + * sealed; only [SyncCodec.open] sees plaintext. + * + * [kind] is null when this build does not know the op's wire kind, so an old + * client can skip a newer client's op instead of failing the whole pull. + * + * Equality and hashing use [seq] only: two views of the same log position are + * the same op, and [ciphertext] is a `ByteArray` (whose identity equality would + * otherwise surprise callers). + */ +class RemoteSyncOp( + val seq: Long, + val opId: String, + val kind: SyncKind?, + val threadId: String, + val turnId: String?, + val fromDevice: String, + val memberId: String, + val clientAt: Long, + val at: String, + val ciphertext: ByteArray, +) { + override fun equals(other: Any?): Boolean = other is RemoteSyncOp && other.seq == seq + + override fun hashCode(): Int = seq.hashCode() + + override fun toString(): String = "RemoteSyncOp(seq=$seq, opId=$opId, kind=$kind)" +} diff --git a/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SealedOp.kt b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SealedOp.kt new file mode 100644 index 000000000..cb9cc08ba --- /dev/null +++ b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SealedOp.kt @@ -0,0 +1,14 @@ +package com.hopa.backend.sync.client + +/** + * One op ready for the wire: [ct] is standard base64 of + * `PayloadCipher.seal(contentKey, payload)`. + */ +data class SealedOp( + val opId: String, + val kind: SyncKind, + val threadId: String, + val turnId: String?, + val ct: String, + val clientAt: Long, +) diff --git a/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncCursor.kt b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncCursor.kt new file mode 100644 index 000000000..5f0f36cce --- /dev/null +++ b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncCursor.kt @@ -0,0 +1,8 @@ +package com.hopa.backend.sync.client + +/** Where this device stores the seq it has applied up to. */ +interface SyncCursor { + fun read(): Long + + fun write(seq: Long) +} diff --git a/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncDraft.kt b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncDraft.kt new file mode 100644 index 000000000..c1dc95ffd --- /dev/null +++ b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncDraft.kt @@ -0,0 +1,25 @@ +package com.hopa.backend.sync.client + +import kotlinx.serialization.json.JsonObject + +/** + * A local change waiting to be sealed and pushed. + * + * [payload] is plaintext until [SyncCodec.seal] encrypts it; it must never be + * logged or put in an exception message. A `thread.upsert` payload is + * `{"title": "...", "deletedAt": 0, "clientAt": 173...}` (`deletedAt > 0` is a + * final tombstone); a `turn.append` payload is + * `{"role": "user"|"assistant", "text": "...", "at": 173...}`. + */ +data class SyncDraft( + val opId: String, + val kind: SyncKind, + val threadId: String, + val turnId: String?, + val payload: JsonObject, + val clientAt: Long, +) { + /** Never print [payload]: it is plaintext until [SyncCodec.seal]. */ + override fun toString(): String = + "SyncDraft(opId=$opId, kind=$kind, threadId=$threadId, turnId=$turnId, clientAt=$clientAt)" +} diff --git a/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncHttp.kt b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncHttp.kt new file mode 100644 index 000000000..505da2b11 --- /dev/null +++ b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncHttp.kt @@ -0,0 +1,12 @@ +package com.hopa.backend.sync.client + +/** + * The sync routes behind a port: OkHttp in the apps, an in-process fake in + * tests. A refused call is a [SyncHttpException] with the server's code; a + * network failure throws whatever the transport throws. + */ +interface SyncHttp { + suspend fun push(token: String, baseUrl: String, ops: List): PushAnswer + + suspend fun pull(token: String, baseUrl: String, after: Long, limit: Int): PullAnswer +} diff --git a/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncHttpException.kt b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncHttpException.kt new file mode 100644 index 000000000..4ed80f89c --- /dev/null +++ b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncHttpException.kt @@ -0,0 +1,11 @@ +package com.hopa.backend.sync.client + +/** + * A sync call the server refused. [message] is the server's safe message and + * never contains a payment or payload body. + */ +class SyncHttpException( + val code: String?, + override val message: String, + val status: Int, +) : RuntimeException(message) diff --git a/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncKind.kt b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncKind.kt new file mode 100644 index 000000000..04f140042 --- /dev/null +++ b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncKind.kt @@ -0,0 +1,13 @@ +package com.hopa.backend.sync.client + +/** The two op kinds sync v0 knows. */ +enum class SyncKind(val wire: String) { + THREAD_UPSERT("thread.upsert"), + TURN_APPEND("turn.append"), + ; + + companion object { + /** The kind whose [wire] value is [value], or null for a kind this build does not know. */ + fun fromWire(value: String): SyncKind? = entries.firstOrNull { it.wire == value } + } +} diff --git a/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncTarget.kt b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncTarget.kt new file mode 100644 index 000000000..ec0c70af2 --- /dev/null +++ b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncTarget.kt @@ -0,0 +1,16 @@ +package com.hopa.backend.sync.client + +/** + * What an app's local store must offer for [SyncEngine] to apply remote ops. + * The store owns the merge rules that need local state (turn dedupe and the + * tombstone rule), so the engine can stay stateless. + */ +interface SyncTarget { + /** True when this device already holds the turn (dedupe by turn id). */ + suspend fun hasTurn(threadId: String, turnId: String): Boolean + + suspend fun appendTurn(threadId: String, turnId: String, role: String, text: String, at: Long) + + /** A tombstone (deletedAt > 0) hides the thread; deleted threads never take a title. */ + suspend fun applyThread(threadId: String, title: String?, deletedAt: Long, clientAt: Long) +} diff --git a/core/backend/src/test/kotlin/com/hopa/backend/sync/client/OkHttpSyncHttpTest.kt b/core/backend/src/test/kotlin/com/hopa/backend/sync/client/OkHttpSyncHttpTest.kt new file mode 100644 index 000000000..efbbf5b91 --- /dev/null +++ b/core/backend/src/test/kotlin/com/hopa/backend/sync/client/OkHttpSyncHttpTest.kt @@ -0,0 +1,159 @@ +package com.hopa.backend.sync.client + +import com.hopa.contracts.json.HopaJson +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import okhttp3.OkHttpClient +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import java.util.Base64 + +class OkHttpSyncHttpTest { + @Test + fun `push sends the path, bearer and sealed ops`() = runBlocking { + val server = MockWebServer() + try { + val pushAnswer = + """{"head":2,"accepted":[{"opId":"o-1","seq":1,"duplicate":false},""" + + """{"opId":"t-1","seq":2,"duplicate":true}]}""" + server.enqueue( + MockResponse() + .setHeader("Content-Type", "application/json") + .setBody(pushAnswer), + ) + val http = OkHttpSyncHttp(OkHttpClient()) + val ops = listOf( + SealedOp("o-1", SyncKind.TURN_APPEND, "c-1", "m-1", "Y3Q=", 100), + SealedOp("t-1", SyncKind.THREAD_UPSERT, "c-1", null, "Y3Q=", 101), + ) + + val answer = http.push("tok-1", server.url("/").toString(), ops) + + assertEquals( + PushAnswer(2, listOf(PushAck("o-1", 1, false), PushAck("t-1", 2, true))), + answer, + ) + val request = server.takeRequest() + assertEquals("POST", request.method) + assertEquals("/v1/sync/ops", request.path) + assertEquals("Bearer tok-1", request.getHeader("Authorization")) + assertTrue(request.getHeader("Content-Type")!!.startsWith("application/json")) + val body = HopaJson.element.parseToJsonElement(request.body.readUtf8()).jsonObject + val sent = body.getValue("ops").jsonArray.map { it.jsonObject } + assertEquals(listOf("o-1", "t-1"), sent.map { it.getValue("opId").jsonPrimitive.content }) + assertEquals("turn.append", sent[0].getValue("kind").jsonPrimitive.content) + assertEquals("m-1", sent[0].getValue("turnId").jsonPrimitive.content) + assertEquals("Y3Q=", sent[0].getValue("ct").jsonPrimitive.content) + assertEquals(100L, sent[0].getValue("clientAt").jsonPrimitive.content.toLong()) + assertFalse(sent[1].containsKey("turnId")) + } finally { + server.shutdown() + } + } + + @Test + fun `a refused push becomes a sync http exception with the server code`() { + val server = MockWebServer() + try { + server.enqueue( + MockResponse().setResponseCode(409) + .setBody("""{"error":{"code":"E_CONFLICT","message":"already stored"}}"""), + ) + server.enqueue( + MockResponse().setResponseCode(400) + .setBody("""{"error":{"code":"E_SCHEMA","message":"threadId must not be blank"}}"""), + ) + val http = OkHttpSyncHttp(OkHttpClient()) + val op = SealedOp("o-1", SyncKind.TURN_APPEND, "c-1", "m-1", "Y3Q=", 100) + + val conflict = assertThrows(SyncHttpException::class.java) { + runBlocking { http.push("tok", server.url("/").toString(), listOf(op)) } + } + assertEquals("E_CONFLICT", conflict.code) + assertEquals("already stored", conflict.message) + assertEquals(409, conflict.status) + + val schema = assertThrows(SyncHttpException::class.java) { + runBlocking { http.push("tok", server.url("/").toString(), listOf(op)) } + } + assertEquals("E_SCHEMA", schema.code) + assertEquals(400, schema.status) + } finally { + server.shutdown() + } + } + + @Test + fun `pull parses the page and keeps an unknown kind as unknown`() = runBlocking { + val server = MockWebServer() + try { + val ct = Base64.getEncoder().encodeToString(byteArrayOf(9, 8, 7)) + server.enqueue( + MockResponse() + .setHeader("Content-Type", "application/json") + .setBody( + """{"ops":[""" + + """{"seq":41,"opId":"o-1","kind":"turn.append","threadId":"c-1","turnId":"m-1",""" + + """"fromDevice":"d-1","memberId":"m-1","clientAt":1733000000000,""" + + """"at":"2026-11-29T10:00:00Z","ct":"$ct"},""" + + """{"seq":42,"opId":"o-2","kind":"thread.rename","threadId":"c-1",""" + + """"fromDevice":"d-2","memberId":"m-1","clientAt":1733000000001,""" + + """"at":"2026-11-29T10:00:01Z","ct":"$ct"}],""" + + """"hasMore":false,"head":42}""", + ), + ) + val http = OkHttpSyncHttp(OkHttpClient()) + + val page = http.pull("tok-2", server.url("/").toString(), after = 40, limit = 2) + + assertEquals(42L, page.head) + assertFalse(page.hasMore) + assertEquals(2, page.ops.size) + val op = page.ops[0] + assertEquals(41L, op.seq) + assertEquals("o-1", op.opId) + assertEquals(SyncKind.TURN_APPEND, op.kind) + assertEquals("c-1", op.threadId) + assertEquals("m-1", op.turnId) + assertEquals("d-1", op.fromDevice) + assertEquals("m-1", op.memberId) + assertEquals(1733000000000L, op.clientAt) + assertEquals("2026-11-29T10:00:00Z", op.at) + assertEquals(byteArrayOf(9, 8, 7).toList(), op.ciphertext.toList()) + assertNull(page.ops[1].kind) + + val request = server.takeRequest() + assertEquals("GET", request.method) + assertEquals("/v1/sync/ops?after=40&limit=2", request.path) + assertEquals("Bearer tok-2", request.getHeader("Authorization")) + } finally { + server.shutdown() + } + } + + @Test + fun `an error body that is not json still reports the status`() = runBlocking { + val server = MockWebServer() + try { + server.enqueue(MockResponse().setResponseCode(500).setBody("upstream is down")) + val http = OkHttpSyncHttp(OkHttpClient()) + + val failure = assertThrows(SyncHttpException::class.java) { + runBlocking { http.pull("tok", server.url("/").toString(), after = 0, limit = 2) } + } + assertNull(failure.code) + assertEquals(500, failure.status) + assertTrue(failure.message.isNotBlank()) + } finally { + server.shutdown() + } + } +} From bc6dd4bd700f6e0a05fdef527abea03082142e34 Mon Sep 17 00:00:00 2001 From: aharonamir Date: Sun, 29 Nov 2026 23:44:14 +0200 Subject: [PATCH 09/58] Seal and open sync payloads with SyncCodec Payloads travel sealed inside SyncDraft, so SyncCodec is the only place that touches PayloadCipher. It refuses what the server would refuse (blank ids, a turn without a turn id, a thread upsert with one) and the 64 KiB ciphertext cap, without putting plaintext in an exception message. Part of #32. --- .../com/hopa/backend/sync/client/SyncCodec.kt | 57 +++++++++ .../hopa/backend/sync/client/SyncCodecTest.kt | 115 ++++++++++++++++++ 2 files changed, 172 insertions(+) create mode 100644 core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncCodec.kt create mode 100644 core/backend/src/test/kotlin/com/hopa/backend/sync/client/SyncCodecTest.kt diff --git a/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncCodec.kt b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncCodec.kt new file mode 100644 index 000000000..ba5420a05 --- /dev/null +++ b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncCodec.kt @@ -0,0 +1,57 @@ +package com.hopa.backend.sync.client + +import com.hopa.backend.crypto.PayloadCipher +import com.hopa.contracts.json.HopaJson +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonObject +import java.util.Base64 + +/** + * Seals and opens sync payloads with [PayloadCipher] under one household + * content key. Sealed bytes are standard base64 on the wire. + * + * [open] throws [javax.crypto.AEADBadTagException] for the wrong key or a + * tampered blob. [seal] refuses ids the server would refuse, a turn without a + * turn id, a thread upsert with one, and a ciphertext over 64 KiB. + */ +class SyncCodec(private val contentKey: ByteArray) { + fun seal(draft: SyncDraft): SealedOp { + validate(draft) + val sealed = PayloadCipher.seal(contentKey, draft.payload.toString().toByteArray()) + require(sealed.size <= MAX_CIPHERTEXT_BYTES) { + "ciphertext is larger than $MAX_CIPHERTEXT_BYTES bytes" + } + return SealedOp( + opId = draft.opId, + kind = draft.kind, + threadId = draft.threadId, + turnId = draft.turnId, + ct = Base64.getEncoder().encodeToString(sealed), + clientAt = draft.clientAt, + ) + } + + fun open(op: RemoteSyncOp): JsonObject { + val plaintext = String(PayloadCipher.open(contentKey, op.ciphertext), Charsets.UTF_8) + return try { + HopaJson.element.parseToJsonElement(plaintext).jsonObject + } catch (_: IllegalArgumentException) { + // Do not chain the parser failure: its message can quote the plaintext. + throw IllegalArgumentException("sync payload is not a json object") + } + } + + private fun validate(draft: SyncDraft) { + require(draft.opId.isNotBlank()) { "opId must not be blank" } + require(draft.threadId.isNotBlank()) { "threadId must not be blank" } + when (draft.kind) { + SyncKind.TURN_APPEND -> require(!draft.turnId.isNullOrBlank()) { "a turn needs a turnId" } + SyncKind.THREAD_UPSERT -> require(draft.turnId == null) { "a thread upsert carries no turnId" } + } + } + + companion object { + /** Raw ciphertext cap of one op, matching the server's `MAX_OP_BYTES`. */ + const val MAX_CIPHERTEXT_BYTES = 64 * 1024 + } +} diff --git a/core/backend/src/test/kotlin/com/hopa/backend/sync/client/SyncCodecTest.kt b/core/backend/src/test/kotlin/com/hopa/backend/sync/client/SyncCodecTest.kt new file mode 100644 index 000000000..1ac2cebe2 --- /dev/null +++ b/core/backend/src/test/kotlin/com/hopa/backend/sync/client/SyncCodecTest.kt @@ -0,0 +1,115 @@ +package com.hopa.backend.sync.client + +import com.hopa.backend.crypto.PayloadCipher +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Test +import java.util.Base64 +import javax.crypto.AEADBadTagException + +class SyncCodecTest { + private val key = ByteArray(32) { (it + 1).toByte() } + + private fun remote(op: SealedOp): RemoteSyncOp = RemoteSyncOp( + seq = 1, + opId = op.opId, + kind = op.kind, + threadId = op.threadId, + turnId = op.turnId, + fromDevice = "d-1", + memberId = "m-1", + clientAt = op.clientAt, + at = "2026-11-29T00:00:00Z", + ciphertext = Base64.getDecoder().decode(op.ct), + ) + + @Test + fun `seal then open round trips both kinds`() { + val codec = SyncCodec(key) + val threadPayload = buildJsonObject { + put("title", "Groceries") + put("deletedAt", 0) + put("clientAt", 1733000000000) + } + val thread = SyncDraft("op-thread", SyncKind.THREAD_UPSERT, "c-1", null, threadPayload, 1733000000000) + val sealedThread = codec.seal(thread) + assertEquals("op-thread", sealedThread.opId) + assertEquals(SyncKind.THREAD_UPSERT, sealedThread.kind) + assertEquals("c-1", sealedThread.threadId) + assertEquals(null, sealedThread.turnId) + assertEquals(1733000000000, sealedThread.clientAt) + assertFalse(sealedThread.ct.isBlank()) + assertEquals(threadPayload, codec.open(remote(sealedThread))) + + val turnPayload = buildJsonObject { + put("role", "assistant") + put("text", "the bins are out") + put("at", 1733000001000) + } + val turn = SyncDraft("m-1", SyncKind.TURN_APPEND, "c-1", "m-1", turnPayload, 1733000001000) + val sealedTurn = codec.seal(turn) + assertEquals(SyncKind.TURN_APPEND, sealedTurn.kind) + assertEquals("m-1", sealedTurn.turnId) + assertEquals(turnPayload, codec.open(remote(sealedTurn))) + } + + @Test + fun `another key cannot open the payload`() { + val sealed = SyncCodec(key).seal( + SyncDraft("m-1", SyncKind.TURN_APPEND, "c-1", "m-1", buildJsonObject { put("text", "hi") }, 1), + ) + val other = SyncCodec(ByteArray(32) { (it + 99).toByte() }) + assertThrows(AEADBadTagException::class.java) { other.open(remote(sealed)) } + } + + @Test + fun `a ciphertext over the cap is refused without echoing the payload`() { + val codec = SyncCodec(key) + val payload = buildJsonObject { + put("role", "user") + put("text", "secret-token " + "x".repeat(70_000)) + put("at", 1) + } + val draft = SyncDraft("m-1", SyncKind.TURN_APPEND, "c-1", "m-1", payload, 1) + val failure = assertThrows(IllegalArgumentException::class.java) { codec.seal(draft) } + assertFalse(failure.message.orEmpty().contains("secret-token")) + } + + @Test + fun `a decrypted payload that is not json does not echo its content`() { + val codec = SyncCodec(key) + val secret = "secret-plaintext" + val op = RemoteSyncOp( + seq = 1, + opId = "o-1", + kind = SyncKind.TURN_APPEND, + threadId = "c-1", + turnId = "m-1", + fromDevice = "d-1", + memberId = "m-1", + clientAt = 1, + at = "2026-11-29T00:00:00Z", + ciphertext = PayloadCipher.seal(key, secret.toByteArray()), + ) + val failure = assertThrows(IllegalArgumentException::class.java) { codec.open(op) } + assertFalse(failure.message.orEmpty().contains(secret)) + } + + @Test + fun `blank ids and mismatched turn ids are refused`() { + val codec = SyncCodec(key) + val turnPayload = buildJsonObject { put("text", "hi") } + fun draft(opId: String = "m-1", threadId: String = "c-1", turnId: String? = "m-1") = + SyncDraft(opId, SyncKind.TURN_APPEND, threadId, turnId, turnPayload, 1) + + assertThrows(IllegalArgumentException::class.java) { codec.seal(draft(opId = " ")) } + assertThrows(IllegalArgumentException::class.java) { codec.seal(draft(threadId = "")) } + assertThrows(IllegalArgumentException::class.java) { codec.seal(draft(turnId = null)) } + assertThrows(IllegalArgumentException::class.java) { codec.seal(draft(turnId = " ")) } + val upsert = SyncDraft("t-1", SyncKind.THREAD_UPSERT, "c-1", "m-1", turnPayload, 1) + assertThrows(IllegalArgumentException::class.java) { codec.seal(upsert) } + } +} From 1ef1468d98aad4b1189d4a526c5bba3e11882224 Mon Sep 17 00:00:00 2001 From: aharonamir Date: Sun, 29 Nov 2026 23:44:20 +0200 Subject: [PATCH 10/58] Push, pull and apply the sync op log with SyncEngine The engine batches pushes by 100, pulls page by page and applies in seq order, writing the cursor after each op. An unknown kind is skipped so a newer client cannot wedge an older one, while a bad tag still throws and leaves the cursor at the last good seq. SyncBacklog gives the apps deterministic turn order and title op ids. Part of #32. --- .../hopa/backend/sync/client/SyncBacklog.kt | 17 + .../hopa/backend/sync/client/SyncEngine.kt | 100 +++++ .../backend/sync/client/SyncBacklogTest.kt | 60 +++ .../backend/sync/client/SyncEngineTest.kt | 342 ++++++++++++++++++ 4 files changed, 519 insertions(+) create mode 100644 core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncBacklog.kt create mode 100644 core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncEngine.kt create mode 100644 core/backend/src/test/kotlin/com/hopa/backend/sync/client/SyncBacklogTest.kt create mode 100644 core/backend/src/test/kotlin/com/hopa/backend/sync/client/SyncEngineTest.kt diff --git a/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncBacklog.kt b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncBacklog.kt new file mode 100644 index 000000000..45587dcea --- /dev/null +++ b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncBacklog.kt @@ -0,0 +1,17 @@ +package com.hopa.backend.sync.client + +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.longOrNull + +/** Pure helpers an app uses to build its push batch. */ +object SyncBacklog { + /** Turns per thread in ascending `at` (the payload's), tie by turn id. */ + fun orderTurns(turns: List): List = turns.sortedWith( + compareBy({ it.threadId }, { atOf(it) }, { it.turnId.orEmpty() }), + ) + + /** Deterministic id for a title push: `"::"`. */ + fun titleOpId(threadId: String, updatedAt: Long, deviceId: String): String = "$threadId:$updatedAt:$deviceId" + + private fun atOf(draft: SyncDraft): Long = draft.payload["at"]?.jsonPrimitive?.longOrNull ?: draft.clientAt +} diff --git a/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncEngine.kt b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncEngine.kt new file mode 100644 index 000000000..640149fcc --- /dev/null +++ b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncEngine.kt @@ -0,0 +1,100 @@ +package com.hopa.backend.sync.client + +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.longOrNull + +/** + * Pushes sealed drafts and applies remote ops in seq order. It owns no storage: + * [SyncTarget] merges into the app's store and [SyncCursor] remembers the last + * applied seq. + * + * A pull never skips an op it cannot open (a bad tag throws and leaves the + * cursor at the last good seq) but does skip an op whose kind this build does + * not know, writing the cursor past it so a newer client cannot wedge an older + * one. + */ +class SyncEngine( + private val http: SyncHttp, + private val codec: SyncCodec, + private val target: SyncTarget, + private val cursor: SyncCursor, + private val token: () -> String, + private val baseUrl: () -> String, +) { + /** + * Seals every draft, then sends them in batches of at most [MAX_BATCH] and + * merges the answers ([PushAnswer.head] of the last batch, acks in order). + * An empty input makes no call. A push never advances the cursor. + */ + suspend fun push(drafts: List): PushAnswer { + if (drafts.isEmpty()) return PushAnswer(cursor.read(), emptyList()) + val sealed = drafts.map(codec::seal) + var head = cursor.read() + val accepted = mutableListOf() + for (batch in sealed.chunked(MAX_BATCH)) { + val answer = http.push(token(), baseUrl(), batch) + head = answer.head + accepted += answer.accepted + } + return PushAnswer(head, accepted) + } + + /** Pulls every page after the cursor and returns how many ops were applied. */ + suspend fun pull(limit: Int = DEFAULT_PULL_LIMIT): Int { + require(limit > 0) { "limit must be positive" } + var applied = 0 + var more: Boolean + do { + val before = cursor.read() + val page = http.pull(token(), baseUrl(), before, limit) + var last = before + for (op in page.ops.sortedBy { it.seq }) { + if (op.seq <= last) continue + if (apply(op)) applied++ + cursor.write(op.seq) + last = op.seq + } + more = page.hasMore && last > before + } while (more) + return applied + } + + private suspend fun apply(op: RemoteSyncOp): Boolean = when (op.kind) { + SyncKind.TURN_APPEND -> applyTurn(op) + SyncKind.THREAD_UPSERT -> applyThread(op) + null -> false + } + + private suspend fun applyTurn(op: RemoteSyncOp): Boolean { + val turnId = op.turnId + if (turnId.isNullOrBlank()) return false + if (target.hasTurn(op.threadId, turnId)) return false + val payload = codec.open(op) + val role = payload["role"]?.jsonPrimitive?.contentOrNull + val text = payload["text"]?.jsonPrimitive?.contentOrNull + if (role == null || role !in ROLES || text.isNullOrBlank()) return false + val at = payload["at"]?.jsonPrimitive?.longOrNull ?: op.clientAt + target.appendTurn(op.threadId, turnId, role, text, at) + return true + } + + private suspend fun applyThread(op: RemoteSyncOp): Boolean { + val payload = codec.open(op) + val deletedAt = payload["deletedAt"]?.jsonPrimitive?.longOrNull ?: 0L + val title = payload["title"]?.jsonPrimitive?.contentOrNull + val clientAt = payload["clientAt"]?.jsonPrimitive?.longOrNull ?: op.clientAt + target.applyThread(op.threadId, title, deletedAt, clientAt) + return true + } + + companion object { + /** Ops one push may carry, matching the server. */ + const val MAX_BATCH = 100 + + /** The default page size, matching the server's maximum. */ + const val DEFAULT_PULL_LIMIT = 200 + + private val ROLES = setOf("user", "assistant") + } +} diff --git a/core/backend/src/test/kotlin/com/hopa/backend/sync/client/SyncBacklogTest.kt b/core/backend/src/test/kotlin/com/hopa/backend/sync/client/SyncBacklogTest.kt new file mode 100644 index 000000000..f5c99a892 --- /dev/null +++ b/core/backend/src/test/kotlin/com/hopa/backend/sync/client/SyncBacklogTest.kt @@ -0,0 +1,60 @@ +package com.hopa.backend.sync.client + +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotEquals +import org.junit.jupiter.api.Test + +class SyncBacklogTest { + private fun turn(opId: String, threadId: String, at: Long): SyncDraft = SyncDraft( + opId = opId, + kind = SyncKind.TURN_APPEND, + threadId = threadId, + turnId = opId, + payload = buildJsonObject { + put("role", "user") + put("text", "text-$opId") + put("at", at) + }, + clientAt = at, + ) + + @Test + fun `turns are ordered by at and tie broken by turn id`() { + val late = turn("m-b", "c-1", 5) + val early = turn("m-c", "c-1", 3) + val sameTime = turn("m-a", "c-1", 5) + + val ordered = SyncBacklog.orderTurns(listOf(late, early, sameTime)) + + assertEquals(listOf("m-c", "m-a", "m-b"), ordered.map { it.turnId }) + } + + @Test + fun `turns stay grouped per thread`() { + val secondThread = turn("m-9", "c-2", 1) + val firstThreadLate = turn("m-2", "c-1", 20) + val firstThreadEarly = turn("m-1", "c-1", 10) + + val ordered = SyncBacklog.orderTurns(listOf(secondThread, firstThreadLate, firstThreadEarly)) + + assertEquals( + listOf("c-1" to "m-1", "c-1" to "m-2", "c-2" to "m-9"), + ordered.map { it.threadId to it.turnId }, + ) + } + + @Test + fun `a title op id names the thread, its update time and the device`() { + assertEquals("c-1:1733000000000:phone", SyncBacklog.titleOpId("c-1", 1733000000000, "phone")) + } + + @Test + fun `two devices renaming in the same millisecond get different ids`() { + assertNotEquals( + SyncBacklog.titleOpId("c-1", 1733000000000, "phone"), + SyncBacklog.titleOpId("c-1", 1733000000000, "laptop"), + ) + } +} diff --git a/core/backend/src/test/kotlin/com/hopa/backend/sync/client/SyncEngineTest.kt b/core/backend/src/test/kotlin/com/hopa/backend/sync/client/SyncEngineTest.kt new file mode 100644 index 000000000..bf79f9e87 --- /dev/null +++ b/core/backend/src/test/kotlin/com/hopa/backend/sync/client/SyncEngineTest.kt @@ -0,0 +1,342 @@ +package com.hopa.backend.sync.client + +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import java.util.Base64 +import javax.crypto.AEADBadTagException + +class SyncEngineTest { + private val key = ByteArray(32) { (it + 1).toByte() } + + private val http = FakeSyncHttp() + + private fun engine(target: SyncTarget = MemoryTarget(), cursor: SyncCursor = MemoryCursor()): SyncEngine = + SyncEngine( + http = http, + codec = SyncCodec(key), + target = target, + cursor = cursor, + token = { "tok" }, + baseUrl = { "http://sync.test" }, + ) + + private suspend fun seed(vararg drafts: SyncDraft) { + http.push("tok", "http://sync.test", drafts.map { SyncCodec(key).seal(it) }) + } + + private fun turn( + opId: String, + threadId: String = "c-1", + turnId: String = opId, + text: String = "text-$opId", + at: Long = 1, + ): SyncDraft = SyncDraft( + opId = opId, + kind = SyncKind.TURN_APPEND, + threadId = threadId, + turnId = turnId, + payload = buildJsonObject { + put("role", "user") + put("text", text) + put("at", at) + }, + clientAt = at, + ) + + private fun title( + opId: String, + threadId: String = "c-1", + value: String, + at: Long, + deletedAt: Long = 0, + ): SyncDraft = SyncDraft( + opId = opId, + kind = SyncKind.THREAD_UPSERT, + threadId = threadId, + turnId = null, + payload = buildJsonObject { + put("title", value) + put("deletedAt", deletedAt) + put("clientAt", at) + }, + clientAt = at, + ) + + @Test + fun `a turn applies once on the other device`() = runBlocking { + val aTarget = MemoryTarget() + val aCursor = MemoryCursor() + val a = engine(target = aTarget, cursor = aCursor) + val bTarget = MemoryTarget() + val bCursor = MemoryCursor() + val b = engine(target = bTarget, cursor = bCursor) + + a.push(listOf(turn("m-1", text = "hello", at = 100))) + aTarget.appendTurn("c-1", "m-1", "user", "hello", 100) + assertEquals(1, b.pull()) + assertEquals(listOf("hello"), bTarget.orderedTurns().map { it.text }) + assertEquals(1L, bCursor.read()) + + b.push(listOf(turn("m-2", text = "back", at = 200))) + assertEquals(1, a.pull()) + assertEquals(listOf("hello", "back"), aTarget.orderedTurns().map { it.text }) + assertEquals(2L, aCursor.read()) + } + + @Test + fun `a duplicate push is acknowledged with the stored seq and applies once`() = runBlocking { + val target = MemoryTarget() + val pusher = engine() + val draft = turn("m-1") + + val first = pusher.push(listOf(draft)).accepted.single() + val second = pusher.push(listOf(draft)).accepted.single() + assertFalse(first.duplicate) + assertTrue(second.duplicate) + assertEquals(first.seq, second.seq) + + assertEquals(1, engine(target = target).pull()) + assertEquals(1, target.turnCount()) + } + + @Test + fun `the later title in seq order wins`() = runBlocking { + val target = MemoryTarget() + engine().push(listOf(title("t-1", value = "first", at = 10))) + engine().push(listOf(title("t-2", value = "second", at = 11))) + + engine(target = target).pull() + + assertEquals("second", target.titleOf("c-1")) + assertEquals(listOf("first", "second"), target.appliedTitles()) + } + + @Test + fun `a tombstone hides the thread and a later title does not resurrect it`() = runBlocking { + val target = MemoryTarget() + engine().push(listOf(title("t-1", value = "before", at = 10))) + engine().push(listOf(title("t-2", value = "", at = 20, deletedAt = 123))) + engine().push(listOf(title("t-3", value = "after", at = 30))) + + assertEquals(3, engine(target = target).pull()) + + assertTrue(target.isDeleted("c-1")) + assertNull(target.titleOf("c-1")) + assertEquals(listOf(0L, 123L, 0L), target.appliedDeletions()) + } + + @Test + fun `pull follows pages and leaves the cursor at the head`() = runBlocking { + seed(turn("m-1"), turn("m-2"), turn("m-3"), turn("m-4"), turn("m-5")) + val target = MemoryTarget() + val cursor = MemoryCursor() + + assertEquals(5, engine(target = target, cursor = cursor).pull(limit = 2)) + + assertEquals(listOf(0L to 2, 2L to 2, 4L to 2), http.pulls) + assertEquals(5L, cursor.read()) + assertEquals(5, target.turnCount()) + } + + @Test + fun `a reconnect pulls only what came after the cursor`() = runBlocking { + seed(turn("m-1"), turn("m-2"), turn("m-3")) + val cursor = MemoryCursor(3) + seed(turn("m-4"), turn("m-5"), turn("m-6")) + val target = MemoryTarget() + + assertEquals(3, engine(target = target, cursor = cursor).pull()) + + assertEquals(listOf("m-4", "m-5", "m-6"), target.orderedTurns().map { it.turnId }) + assertEquals(6L, cursor.read()) + } + + @Test + fun `interleaved turns keep chronological order by at`() = runBlocking { + engine().push(listOf(turn("m-2", text = "later", at = 200))) + engine().push(listOf(turn("m-1", text = "earlier", at = 100))) + val target = MemoryTarget() + + engine(target = target).pull() + + assertEquals(listOf("m-1", "m-2"), target.orderedTurns().map { it.turnId }) + } + + @Test + fun `a bad tag throws and leaves the cursor at the last good seq`() { + val cursor = MemoryCursor() + assertThrows(AEADBadTagException::class.java) { + runBlocking { + seed(turn("m-1")) + http.seedRaw( + wireKind = "turn.append", + threadId = "c-1", + turnId = "m-2", + ct = Base64.getEncoder().encodeToString(ByteArray(32) { 7 }), + ) + engine(cursor = cursor).pull() + } + } + assertEquals(1L, cursor.read()) + } + + @Test + fun `an unknown kind is skipped and the cursor moves past it`() = runBlocking { + http.seedRaw( + wireKind = "thread.rename", + threadId = "c-1", + turnId = null, + ct = Base64.getEncoder().encodeToString(byteArrayOf(1, 2, 3)), + ) + seed(turn("m-1")) + val target = MemoryTarget() + val cursor = MemoryCursor() + + assertEquals(1, engine(target = target, cursor = cursor).pull()) + + assertEquals(1, target.turnCount()) + assertEquals(2L, cursor.read()) + } + + @Test + fun `a large push is sent in batches of at most a hundred`() = runBlocking { + val cursor = MemoryCursor(7) + val drafts = (1..150).map { turn("m-$it") } + + val answer = engine(cursor = cursor).push(drafts) + + assertEquals(listOf(100, 50), http.pushBatches.map { it.size }) + assertEquals(150, answer.accepted.size) + assertEquals(150L, answer.head) + assertEquals(7L, cursor.read()) + } + + @Test + fun `an empty push makes no request`() = runBlocking { + val cursor = MemoryCursor(4) + + assertEquals(PushAnswer(4, emptyList()), engine(cursor = cursor).push(emptyList())) + assertTrue(http.pushBatches.isEmpty()) + } + + private class MemoryCursor(private var seq: Long = 0) : SyncCursor { + override fun read(): Long = seq + + override fun write(seq: Long) { + this.seq = seq + } + } + + private class MemoryTarget : SyncTarget { + data class Turn(val threadId: String, val turnId: String, val role: String, val text: String, val at: Long) + + private val turns = mutableListOf() + private val titles = mutableMapOf() + private val deleted = mutableSetOf() + private val applications = mutableListOf>() + + override suspend fun hasTurn(threadId: String, turnId: String): Boolean = + turns.any { it.threadId == threadId && it.turnId == turnId } + + override suspend fun appendTurn(threadId: String, turnId: String, role: String, text: String, at: Long) { + turns += Turn(threadId, turnId, role, text, at) + } + + override suspend fun applyThread(threadId: String, title: String?, deletedAt: Long, clientAt: Long) { + applications += Triple(threadId, title, deletedAt) + if (deletedAt > 0) { + deleted += threadId + titles.remove(threadId) + } else if (threadId !in deleted) { + titles[threadId] = title + } + } + + fun orderedTurns(): List = turns.sortedWith(compareBy({ it.at }, { it.turnId })) + + fun titleOf(threadId: String): String? = titles[threadId] + + fun isDeleted(threadId: String): Boolean = threadId in deleted + + fun turnCount(): Int = turns.size + + fun appliedTitles(): List = applications.map { it.second } + + fun appliedDeletions(): List = applications.map { it.third } + } + + private class FakeSyncHttp : SyncHttp { + private data class Stored( + val seq: Long, + val opId: String, + val wireKind: String, + val threadId: String, + val turnId: String?, + val ct: String, + val clientAt: Long, + val fromDevice: String, + ) + + private val stored = mutableListOf() + private var nextSeq = 0L + + val pushBatches = mutableListOf>() + val pulls = mutableListOf>() + + override suspend fun push(token: String, baseUrl: String, ops: List): PushAnswer { + pushBatches += ops + val acks = ops.map { op -> + val existing = stored.firstOrNull { it.opId == op.opId } + if (existing != null) { + PushAck(op.opId, existing.seq, true) + } else { + val seq = ++nextSeq + stored += Stored( + seq = seq, + opId = op.opId, + wireKind = op.kind.wire, + threadId = op.threadId, + turnId = op.turnId, + ct = op.ct, + clientAt = op.clientAt, + fromDevice = "dev-$token", + ) + PushAck(op.opId, seq, false) + } + } + return PushAnswer(nextSeq, acks) + } + + override suspend fun pull(token: String, baseUrl: String, after: Long, limit: Int): PullAnswer { + pulls += after to limit + val rest = stored.filter { it.seq > after }.sortedBy { it.seq } + val page = rest.take(limit) + return PullAnswer(page.map(::remote), rest.size > limit, nextSeq) + } + + fun seedRaw(wireKind: String, threadId: String, turnId: String?, ct: String) { + val seq = ++nextSeq + stored += Stored(seq, "raw-$seq", wireKind, threadId, turnId, ct, 1, "dev-other") + } + + private fun remote(op: Stored): RemoteSyncOp = RemoteSyncOp( + seq = op.seq, + opId = op.opId, + kind = SyncKind.fromWire(op.wireKind), + threadId = op.threadId, + turnId = op.turnId, + fromDevice = op.fromDevice, + memberId = "m-1", + clientAt = op.clientAt, + at = "2026-11-29T00:00:00Z", + ciphertext = Base64.getDecoder().decode(op.ct), + ) + } +} From 77cfe7761a37f90da0c693827dc77c1cb7675cff Mon Sep 17 00:00:00 2001 From: aharonamir Date: Mon, 30 Nov 2026 00:01:18 +0200 Subject: [PATCH 11/58] Bound sync pushes by body size and report skipped ops The server refuses a body over 256 KiB, so a 100-op batch of near-cap or even ordinary turns could never upload. Batches now split on count and on a conservative JSON-size estimate with headroom under the cap, and one oversized op still travels alone. Pulls now open before dedupe, throw on a bad tag even when the turn is held, and return a SyncReport whose skipped seqs make a shape/value problem observable instead of losing the turn or wedging the log. Part of #32. --- .../hopa/backend/sync/client/SyncEngine.kt | 133 ++++++++++---- .../hopa/backend/sync/client/SyncReport.kt | 15 ++ .../hopa/backend/sync/client/SyncTarget.kt | 5 +- .../backend/sync/client/SyncEngineTest.kt | 169 +++++++++++++++++- 4 files changed, 284 insertions(+), 38 deletions(-) create mode 100644 core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncReport.kt diff --git a/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncEngine.kt b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncEngine.kt index 640149fcc..044361e62 100644 --- a/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncEngine.kt +++ b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncEngine.kt @@ -1,7 +1,8 @@ package com.hopa.backend.sync.client -import kotlinx.serialization.json.contentOrNull -import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.longOrNull /** @@ -9,10 +10,12 @@ import kotlinx.serialization.json.longOrNull * [SyncTarget] merges into the app's store and [SyncCursor] remembers the last * applied seq. * - * A pull never skips an op it cannot open (a bad tag throws and leaves the - * cursor at the last good seq) but does skip an op whose kind this build does - * not know, writing the cursor past it so a newer client cannot wedge an older - * one. + * A pull reports what it skipped. An op it cannot open (a bad tag, or plaintext + * that is not a JSON object) throws and leaves the cursor at the last good seq, + * even when the store already holds the turn. An op with a shape or value + * problem (an unknown kind, a blank turn id, a role other than `user` or + * `assistant`, a non-string title, a non-numeric `deletedAt`) is a recorded skip: + * the cursor moves past it so it cannot wedge the member's log. */ class SyncEngine( private val http: SyncHttp, @@ -23,16 +26,21 @@ class SyncEngine( private val baseUrl: () -> String, ) { /** - * Seals every draft, then sends them in batches of at most [MAX_BATCH] and - * merges the answers ([PushAnswer.head] of the last batch, acks in order). - * An empty input makes no call. A push never advances the cursor. + * Seals every draft, then sends them in batches bounded by [MAX_BATCH] ops + * and roughly [MAX_BATCH_BYTES] of JSON, and merges the answers + * ([PushAnswer.head] of the last batch, acks in order). An empty input makes + * no call. A push never advances the cursor. + * + * A failure part-way loses the acks of the batches already sent; retrying + * the whole list is safe because ids are deterministic and the server + * dedupes them. */ suspend fun push(drafts: List): PushAnswer { if (drafts.isEmpty()) return PushAnswer(cursor.read(), emptyList()) val sealed = drafts.map(codec::seal) var head = cursor.read() val accepted = mutableListOf() - for (batch in sealed.chunked(MAX_BATCH)) { + for (batch in batches(sealed)) { val answer = http.push(token(), baseUrl(), batch) head = answer.head accepted += answer.accepted @@ -40,10 +48,40 @@ class SyncEngine( return PushAnswer(head, accepted) } - /** Pulls every page after the cursor and returns how many ops were applied. */ - suspend fun pull(limit: Int = DEFAULT_PULL_LIMIT): Int { + /** + * Splits on count and on an upper bound of the JSON body size, keeping + * headroom under the server's 256 KiB cap. The estimate is conservative: + * base64 lengths are exact and each op gets more overhead than its keys and + * punctuation need. One op over the budget still travels alone. + */ + private fun batches(sealed: List): List> { + val batches = mutableListOf>() + var current = mutableListOf() + var size = BODY_OVERHEAD_BYTES + for (op in sealed) { + val opBytes = OP_OVERHEAD_BYTES + op.ct.length + op.opId.length + op.kind.wire.length + + op.threadId.length + (op.turnId?.length ?: 0) + if (current.isNotEmpty() && (current.size >= MAX_BATCH || size + opBytes > MAX_BATCH_BYTES)) { + batches += current + current = mutableListOf() + size = BODY_OVERHEAD_BYTES + } + current += op + size += opBytes + } + if (current.isNotEmpty()) batches += current + return batches + } + + /** + * Pulls every page after the cursor and reports what was applied and what + * was skipped. A skipped op still advances the cursor; an op that cannot be + * opened throws and leaves the cursor at the last good seq. + */ + suspend fun pull(limit: Int = DEFAULT_PULL_LIMIT): SyncReport { require(limit > 0) { "limit must be positive" } var applied = 0 + val skipped = mutableListOf() var more: Boolean do { val before = cursor.read() @@ -51,50 +89,85 @@ class SyncEngine( var last = before for (op in page.ops.sortedBy { it.seq }) { if (op.seq <= last) continue - if (apply(op)) applied++ + when (apply(op)) { + Outcome.APPLIED -> applied++ + Outcome.SKIPPED -> skipped += op.seq + Outcome.DUPLICATE -> Unit + } cursor.write(op.seq) last = op.seq } more = page.hasMore && last > before } while (more) - return applied + return SyncReport(applied, skipped) } - private suspend fun apply(op: RemoteSyncOp): Boolean = when (op.kind) { + private suspend fun apply(op: RemoteSyncOp): Outcome = when (op.kind) { SyncKind.TURN_APPEND -> applyTurn(op) SyncKind.THREAD_UPSERT -> applyThread(op) - null -> false + null -> Outcome.SKIPPED } - private suspend fun applyTurn(op: RemoteSyncOp): Boolean { - val turnId = op.turnId - if (turnId.isNullOrBlank()) return false - if (target.hasTurn(op.threadId, turnId)) return false + private suspend fun applyTurn(op: RemoteSyncOp): Outcome { + // Open first: a bad tag must throw even when the store already has the turn. val payload = codec.open(op) - val role = payload["role"]?.jsonPrimitive?.contentOrNull - val text = payload["text"]?.jsonPrimitive?.contentOrNull - if (role == null || role !in ROLES || text.isNullOrBlank()) return false - val at = payload["at"]?.jsonPrimitive?.longOrNull ?: op.clientAt + val turnId = op.turnId + if (turnId.isNullOrBlank()) return Outcome.SKIPPED + if (target.hasTurn(op.threadId, turnId)) return Outcome.DUPLICATE + val role = payload.stringField("role") + val text = payload.stringField("text") + if (role == null || role !in ROLES || text.isNullOrBlank()) return Outcome.SKIPPED + val at = payload.longField("at") ?: op.clientAt target.appendTurn(op.threadId, turnId, role, text, at) - return true + return Outcome.APPLIED } - private suspend fun applyThread(op: RemoteSyncOp): Boolean { + private suspend fun applyThread(op: RemoteSyncOp): Outcome { val payload = codec.open(op) - val deletedAt = payload["deletedAt"]?.jsonPrimitive?.longOrNull ?: 0L - val title = payload["title"]?.jsonPrimitive?.contentOrNull - val clientAt = payload["clientAt"]?.jsonPrimitive?.longOrNull ?: op.clientAt + val deletedElement = payload["deletedAt"] + val deletedAt = when { + deletedElement == null || deletedElement is JsonNull -> 0L + else -> payload.longField("deletedAt") ?: return Outcome.SKIPPED + } + val titleElement = payload["title"] + val title = when { + titleElement == null || titleElement is JsonNull -> null + titleElement is JsonPrimitive && titleElement.isString -> titleElement.content + else -> return Outcome.SKIPPED + } + val clientAt = payload.longField("clientAt") ?: op.clientAt target.applyThread(op.threadId, title, deletedAt, clientAt) - return true + return Outcome.APPLIED + } + + /** A string field, or null when absent, JSON null, or another JSON type. */ + private fun JsonObject.stringField(key: String): String? { + val primitive = this[key] as? JsonPrimitive ?: return null + return if (primitive.isString) primitive.content else null + } + + /** A numeric field, or null when absent, JSON null, or another JSON type. */ + private fun JsonObject.longField(key: String): Long? = (this[key] as? JsonPrimitive)?.longOrNull + + private enum class Outcome { + APPLIED, + SKIPPED, + DUPLICATE, } companion object { /** Ops one push may carry, matching the server. */ const val MAX_BATCH = 100 + /** A conservative ceiling for one push body, under the server's 256 KiB. */ + const val MAX_BATCH_BYTES = 200 * 1024 + /** The default page size, matching the server's maximum. */ const val DEFAULT_PULL_LIMIT = 200 + private const val BODY_OVERHEAD_BYTES = 32 + private const val OP_OVERHEAD_BYTES = 256 + private val ROLES = setOf("user", "assistant") } } diff --git a/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncReport.kt b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncReport.kt new file mode 100644 index 000000000..1aba498a3 --- /dev/null +++ b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncReport.kt @@ -0,0 +1,15 @@ +package com.hopa.backend.sync.client + +/** + * What one [SyncEngine.pull] did. [skipped] lists the seqs that were not applied + * because the op was unusable: an unknown kind, or a known kind whose decrypted + * payload has a shape or value problem. A skipped op still advances the cursor, + * so it cannot wedge the member's log. + * + * A duplicate turn is not a skip: the store already holds it, so nothing was + * lost. + */ +data class SyncReport( + val applied: Int, + val skipped: List, +) diff --git a/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncTarget.kt b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncTarget.kt index ec0c70af2..800bfd986 100644 --- a/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncTarget.kt +++ b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncTarget.kt @@ -11,6 +11,9 @@ interface SyncTarget { suspend fun appendTurn(threadId: String, turnId: String, role: String, text: String, at: Long) - /** A tombstone (deletedAt > 0) hides the thread; deleted threads never take a title. */ + /** + * A tombstone (deletedAt > 0) hides the thread; deleted threads never take a + * title. [title] `null` means "no title change", never "clear the title". + */ suspend fun applyThread(threadId: String, title: String?, deletedAt: Long, clientAt: Long) } diff --git a/core/backend/src/test/kotlin/com/hopa/backend/sync/client/SyncEngineTest.kt b/core/backend/src/test/kotlin/com/hopa/backend/sync/client/SyncEngineTest.kt index bf79f9e87..0b681e88a 100644 --- a/core/backend/src/test/kotlin/com/hopa/backend/sync/client/SyncEngineTest.kt +++ b/core/backend/src/test/kotlin/com/hopa/backend/sync/client/SyncEngineTest.kt @@ -1,6 +1,7 @@ package com.hopa.backend.sync.client import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put import org.junit.jupiter.api.Assertions.assertEquals @@ -80,12 +81,12 @@ class SyncEngineTest { a.push(listOf(turn("m-1", text = "hello", at = 100))) aTarget.appendTurn("c-1", "m-1", "user", "hello", 100) - assertEquals(1, b.pull()) + assertEquals(1, b.pull().applied) assertEquals(listOf("hello"), bTarget.orderedTurns().map { it.text }) assertEquals(1L, bCursor.read()) b.push(listOf(turn("m-2", text = "back", at = 200))) - assertEquals(1, a.pull()) + assertEquals(1, a.pull().applied) assertEquals(listOf("hello", "back"), aTarget.orderedTurns().map { it.text }) assertEquals(2L, aCursor.read()) } @@ -102,7 +103,7 @@ class SyncEngineTest { assertTrue(second.duplicate) assertEquals(first.seq, second.seq) - assertEquals(1, engine(target = target).pull()) + assertEquals(1, engine(target = target).pull().applied) assertEquals(1, target.turnCount()) } @@ -125,7 +126,7 @@ class SyncEngineTest { engine().push(listOf(title("t-2", value = "", at = 20, deletedAt = 123))) engine().push(listOf(title("t-3", value = "after", at = 30))) - assertEquals(3, engine(target = target).pull()) + assertEquals(3, engine(target = target).pull().applied) assertTrue(target.isDeleted("c-1")) assertNull(target.titleOf("c-1")) @@ -138,7 +139,7 @@ class SyncEngineTest { val target = MemoryTarget() val cursor = MemoryCursor() - assertEquals(5, engine(target = target, cursor = cursor).pull(limit = 2)) + assertEquals(5, engine(target = target, cursor = cursor).pull(limit = 2).applied) assertEquals(listOf(0L to 2, 2L to 2, 4L to 2), http.pulls) assertEquals(5L, cursor.read()) @@ -152,7 +153,7 @@ class SyncEngineTest { seed(turn("m-4"), turn("m-5"), turn("m-6")) val target = MemoryTarget() - assertEquals(3, engine(target = target, cursor = cursor).pull()) + assertEquals(3, engine(target = target, cursor = cursor).pull().applied) assertEquals(listOf("m-4", "m-5", "m-6"), target.orderedTurns().map { it.turnId }) assertEquals(6L, cursor.read()) @@ -187,6 +188,108 @@ class SyncEngineTest { assertEquals(1L, cursor.read()) } + @Test + fun `a payload with a wrong field type is skipped instead of wedging the pull`() = runBlocking { + val malformed = SyncCodec(key).seal( + turn("m-1").copy( + payload = buildJsonObject { + put("role", buildJsonObject { put("unexpected", "object") }) + put("text", "hello") + put("at", 1) + }, + ), + ) + http.push("tok", "http://sync.test", listOf(malformed)) + val target = MemoryTarget() + val cursor = MemoryCursor() + + val report = engine(target = target, cursor = cursor).pull() + + assertEquals(0, report.applied) + assertEquals(listOf(1L), report.skipped) + assertEquals(0, target.turnCount()) + assertEquals(1L, cursor.read()) + } + + @Test + fun `wrong values are recorded as skips and the cursor advances`() = runBlocking { + val codec = SyncCodec(key) + val blank = codec.seal(turn("m-blank")).ct + val badRole = codec.seal( + turn("m-role").copy( + payload = buildJsonObject { + put("role", "system") + put("text", "hello") + put("at", 1) + }, + ), + ).ct + val blankText = codec.seal( + turn("m-text").copy( + payload = buildJsonObject { + put("role", "user") + put("text", " ") + put("at", 1) + }, + ), + ).ct + http.seedRaw("turn.append", "c-1", turnId = " ", ct = blank) + http.seedRaw("turn.append", "c-1", turnId = "m-role", ct = badRole) + http.seedRaw("turn.append", "c-1", turnId = "m-text", ct = blankText) + val target = MemoryTarget() + val cursor = MemoryCursor() + + val report = engine(target = target, cursor = cursor).pull() + + assertEquals(0, report.applied) + assertEquals(listOf(1L, 2L, 3L), report.skipped) + assertEquals(0, target.turnCount()) + assertEquals(3L, cursor.read()) + } + + @Test + fun `a thread payload with a wrong deletedAt type is recorded as skipped`() = runBlocking { + val malformed = SyncCodec(key).seal( + title("t-1", value = "keep", at = 5).copy( + payload = buildJsonObject { + put("title", "keep") + put("deletedAt", buildJsonObject { put("unexpected", "object") }) + put("clientAt", 5) + }, + ), + ) + http.push("tok", "http://sync.test", listOf(malformed)) + val target = MemoryTarget() + val cursor = MemoryCursor() + + val report = engine(target = target, cursor = cursor).pull() + + assertEquals(0, report.applied) + assertEquals(listOf(1L), report.skipped) + assertTrue(target.appliedTitles().isEmpty()) + assertEquals(1L, cursor.read()) + } + + @Test + fun `a bad tag on an already held turn still throws and holds the cursor`() { + val target = MemoryTarget() + val cursor = MemoryCursor() + assertThrows(AEADBadTagException::class.java) { + runBlocking { + seed(turn("m-1")) + engine(target = target, cursor = cursor).pull() + http.seedRaw( + wireKind = "turn.append", + threadId = "c-1", + turnId = "m-1", + ct = Base64.getEncoder().encodeToString(ByteArray(32) { 7 }), + ) + engine(target = target, cursor = cursor).pull() + } + } + assertEquals(1L, cursor.read()) + } + @Test fun `an unknown kind is skipped and the cursor moves past it`() = runBlocking { http.seedRaw( @@ -199,8 +302,10 @@ class SyncEngineTest { val target = MemoryTarget() val cursor = MemoryCursor() - assertEquals(1, engine(target = target, cursor = cursor).pull()) + val report = engine(target = target, cursor = cursor).pull() + assertEquals(1, report.applied) + assertEquals(listOf(1L), report.skipped) assertEquals(1, target.turnCount()) assertEquals(2L, cursor.read()) } @@ -218,6 +323,33 @@ class SyncEngineTest { assertEquals(7L, cursor.read()) } + @Test + fun `near cap ops are split so no push body exceeds the server cap`() = runBlocking { + val text = "x".repeat(65_476) + val drafts = (1..3).map { turn("m-$it", text = text, at = it.toLong()) } + + val answer = engine().push(drafts) + + assertEquals(3, answer.accepted.size) + assertTrue(http.pushBatches.size >= 2, "one body would exceed the server cap") + assertEquals(3, http.pushBatches.sumOf { it.size }) + http.pushBatches.forEach { assertTrue(bodyBytes(it) < MAX_BODY_BYTES) } + } + + @Test + fun `a large op mixed with small ones still makes progress`() = runBlocking { + val large = turn("m-large", text = "x".repeat(65_476), at = 9) + val small = (1..120).map { turn("m-$it", text = "y".repeat(1_800), at = it.toLong()) } + + val answer = engine().push(listOf(large) + small) + + assertEquals(121, answer.accepted.size) + assertEquals(121L, answer.head) + assertEquals(121, http.pushBatches.sumOf { it.size }) + assertEquals(1, http.pushBatches.sumOf { batch -> batch.count { it.opId == "m-large" } }) + http.pushBatches.forEach { assertTrue(bodyBytes(it) < MAX_BODY_BYTES) } + } + @Test fun `an empty push makes no request`() = runBlocking { val cursor = MemoryCursor(4) @@ -226,6 +358,29 @@ class SyncEngineTest { assertTrue(http.pushBatches.isEmpty()) } + /** The same JSON shape and encoding OkHttpSyncHttp puts on the wire. */ + private fun bodyBytes(ops: List): Int = buildJsonObject { + put( + "ops", + JsonArray( + ops.map { op -> + buildJsonObject { + put("opId", op.opId) + put("kind", op.kind.wire) + put("threadId", op.threadId) + op.turnId?.let { put("turnId", it) } + put("ct", op.ct) + put("clientAt", op.clientAt) + } + }, + ), + ) + }.toString().toByteArray(Charsets.UTF_8).size + + private companion object { + const val MAX_BODY_BYTES = 256 * 1024 + } + private class MemoryCursor(private var seq: Long = 0) : SyncCursor { override fun read(): Long = seq From 197e0194f260adabc4329a7540310c8ff1ee6bc5 Mon Sep 17 00:00:00 2001 From: aharonamir Date: Mon, 30 Nov 2026 00:31:28 +0200 Subject: [PATCH 12/58] Store the sync cursor as plain settings The last applied sync seq is metadata, not a secret: it lives beside the other mapping values instead of in the keystore, and a lost cursor only replays idempotent ops. Clearing the gateway resets it so a new identity cannot start mid-log. Part of #32. --- .../data/store/DataStoreSettingsRepository.kt | 5 +++++ .../hopa/data/store/SettingsDefaultsTest.kt | 18 ++++++++++++++++++ .../main/kotlin/com/hopa/stores/AppSettings.kt | 6 ++++++ .../com/hopa/stores/SettingsRepository.kt | 7 +++++++ 4 files changed, 36 insertions(+) diff --git a/apps/android/data/src/main/kotlin/com/hopa/data/store/DataStoreSettingsRepository.kt b/apps/android/data/src/main/kotlin/com/hopa/data/store/DataStoreSettingsRepository.kt index f90e99db4..59930a5ab 100644 --- a/apps/android/data/src/main/kotlin/com/hopa/data/store/DataStoreSettingsRepository.kt +++ b/apps/android/data/src/main/kotlin/com/hopa/data/store/DataStoreSettingsRepository.kt @@ -4,6 +4,7 @@ import android.content.Context import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit +import androidx.datastore.preferences.core.longPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.core.stringSetPreferencesKey import androidx.datastore.preferences.preferencesDataStore @@ -55,6 +56,7 @@ class DataStoreSettingsRepository( prefs[BACKEND_URL] = next.backendUrl prefs[BACKEND_DEVICE_ID] = next.backendDeviceId prefs[BACKEND_HOUSEHOLD_ID] = next.backendHouseholdId + prefs[BACKEND_SYNC_SEQ] = next.backendSyncSeq prefs[ACCOUNT_SKIPPED] = next.accountSkipped prefs[BACKEND_PHONE] = next.backendPhone } @@ -116,6 +118,7 @@ class DataStoreSettingsRepository( backendUrl = DEFAULT_BACKEND_URL, backendDeviceId = "", backendHouseholdId = "", + backendSyncSeq = 0, backendPhone = "", ) } @@ -155,6 +158,7 @@ class DataStoreSettingsRepository( backendUrl = prefs[BACKEND_URL] ?: DEFAULT_BACKEND_URL, backendDeviceId = prefs[BACKEND_DEVICE_ID] ?: "", backendHouseholdId = prefs[BACKEND_HOUSEHOLD_ID] ?: "", + backendSyncSeq = prefs[BACKEND_SYNC_SEQ] ?: 0, accountSkipped = prefs[ACCOUNT_SKIPPED] ?: false, backendPhone = prefs[BACKEND_PHONE] ?: "", ) @@ -188,6 +192,7 @@ class DataStoreSettingsRepository( val BACKEND_URL = stringPreferencesKey("backend_url") val BACKEND_DEVICE_ID = stringPreferencesKey("backend_device_id") val BACKEND_HOUSEHOLD_ID = stringPreferencesKey("backend_household_id") + val BACKEND_SYNC_SEQ = longPreferencesKey("backend_sync_seq") val ACCOUNT_SKIPPED = booleanPreferencesKey("account_skipped") val BACKEND_PHONE = stringPreferencesKey("backend_phone") const val MODEL_KEY = "model_key" diff --git a/apps/android/data/src/test/kotlin/com/hopa/data/store/SettingsDefaultsTest.kt b/apps/android/data/src/test/kotlin/com/hopa/data/store/SettingsDefaultsTest.kt index d01dc809c..fd2c861cf 100644 --- a/apps/android/data/src/test/kotlin/com/hopa/data/store/SettingsDefaultsTest.kt +++ b/apps/android/data/src/test/kotlin/com/hopa/data/store/SettingsDefaultsTest.kt @@ -26,4 +26,22 @@ class SettingsDefaultsTest { assertEquals("wss://other.example/v1/gateway", settings.backendUrl) } + + @Test + fun `a fresh settings file has no sync cursor`() { + val settings = DataStoreSettingsRepository.settingsFrom(emptyPreferences()) + + assertEquals(0L, settings.backendSyncSeq) + } + + @Test + fun `a stored sync cursor is read back`() { + val prefs = mutablePreferencesOf( + DataStoreSettingsRepository.BACKEND_SYNC_SEQ to 42L, + ) + + val settings = DataStoreSettingsRepository.settingsFrom(prefs) + + assertEquals(42L, settings.backendSyncSeq) + } } diff --git a/apps/android/stores/src/main/kotlin/com/hopa/stores/AppSettings.kt b/apps/android/stores/src/main/kotlin/com/hopa/stores/AppSettings.kt index 515e9ea28..01fde0d2a 100644 --- a/apps/android/stores/src/main/kotlin/com/hopa/stores/AppSettings.kt +++ b/apps/android/stores/src/main/kotlin/com/hopa/stores/AppSettings.kt @@ -71,6 +71,12 @@ data class AppSettings( /** Identity this device was given when it joined the household. */ val backendDeviceId: String = "", val backendHouseholdId: String = "", + /** + * The last sync seq this device pulled and applied. Plain metadata, not a + * secret: a lost cursor only means the next pull replays ops it already + * holds, which the store dedupes. + */ + val backendSyncSeq: Long = 0, /** * The person chose "use this phone without an account". It wins over the * gateway until a real sign-in clears it, so a reachable gateway cannot diff --git a/apps/android/stores/src/main/kotlin/com/hopa/stores/SettingsRepository.kt b/apps/android/stores/src/main/kotlin/com/hopa/stores/SettingsRepository.kt index 1d51958d4..85af3def9 100644 --- a/apps/android/stores/src/main/kotlin/com/hopa/stores/SettingsRepository.kt +++ b/apps/android/stores/src/main/kotlin/com/hopa/stores/SettingsRepository.kt @@ -43,6 +43,13 @@ interface SettingsRepository { suspend fun setBackendContentKey(value: String) + /** + * The last sync seq the op log was applied up to. It belongs in settings, + * not the secret store: it is not secret, and a replay is harmless because + * every op is idempotent. + */ + suspend fun setBackendSyncSeq(value: Long) = update { it.copy(backendSyncSeq = value) } + /** * The Ed25519 seed that signs this phone's approval answers (ADR-0032), * base64. Blank until the first answer creates it. A store that cannot From 898fa90aa7075f97c40c7d40234f14ef698d0629 Mon Sep 17 00:00:00 2001 From: aharonamir Date: Mon, 30 Nov 2026 00:31:35 +0200 Subject: [PATCH 13/58] Treat a rename as a newer thread revision A title push is keyed by the thread's revision, so a rename that leaves updatedAt unchanged could never be told apart from the last push and the server would dedupe it away. Rename now writes a strictly newer revision (max(updatedAt + 1, now)) in both stores. An adopted thread with a blank title also gets the same 'New chat' default the Room store already used, so a thread created by a remote turn is not nameless. Part of #32. --- .../com/hopa/data/database/dao/SessionDao.kt | 4 ++-- .../com/hopa/data/store/DbConversationStore.kt | 4 +++- .../com/hopa/stores/InMemoryConversationStore.kt | 14 ++++++++++++-- 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/apps/android/data/src/main/kotlin/com/hopa/data/database/dao/SessionDao.kt b/apps/android/data/src/main/kotlin/com/hopa/data/database/dao/SessionDao.kt index 46ed093a5..cb19c5a30 100644 --- a/apps/android/data/src/main/kotlin/com/hopa/data/database/dao/SessionDao.kt +++ b/apps/android/data/src/main/kotlin/com/hopa/data/database/dao/SessionDao.kt @@ -46,8 +46,8 @@ interface SessionDao { @Query("UPDATE sessions SET title = :title, updatedAt = :updatedAt WHERE id = :id") suspend fun updateMeta(id: String, title: String, updatedAt: Long) - @Query("UPDATE sessions SET title = :title WHERE id = :id") - suspend fun rename(id: String, title: String) + @Query("UPDATE sessions SET title = :title, updatedAt = max(updatedAt + 1, :at) WHERE id = :id") + suspend fun rename(id: String, title: String, at: Long) @Query("UPDATE sessions SET deletedAt = :at, updatedAt = :at WHERE id = :id") suspend fun tombstone(id: String, at: Long) diff --git a/apps/android/data/src/main/kotlin/com/hopa/data/store/DbConversationStore.kt b/apps/android/data/src/main/kotlin/com/hopa/data/store/DbConversationStore.kt index 94764f6a8..77a7de150 100644 --- a/apps/android/data/src/main/kotlin/com/hopa/data/store/DbConversationStore.kt +++ b/apps/android/data/src/main/kotlin/com/hopa/data/store/DbConversationStore.kt @@ -102,7 +102,9 @@ class DbConversationStore( } override suspend fun rename(id: String, title: String) { - sessions.rename(id, title) + // A rename is a newer revision: the sync op id is keyed by updatedAt, + // and `max` keeps two renames in one millisecond distinct. + sessions.rename(id, title, System.currentTimeMillis()) } override suspend fun delete(id: String) { diff --git a/apps/android/stores/src/main/kotlin/com/hopa/stores/InMemoryConversationStore.kt b/apps/android/stores/src/main/kotlin/com/hopa/stores/InMemoryConversationStore.kt index 8ed08746d..c9d8a7657 100644 --- a/apps/android/stores/src/main/kotlin/com/hopa/stores/InMemoryConversationStore.kt +++ b/apps/android/stores/src/main/kotlin/com/hopa/stores/InMemoryConversationStore.kt @@ -24,7 +24,7 @@ class InMemoryConversationStore : ConversationStore { override suspend fun adopt(session: Conversation) { val existing = rows[session.id] rows[session.id] = if (existing == null) { - session + session.copy(title = session.title.ifBlank { NEW_CHAT }) } else { existing.copy( title = session.title.ifBlank { existing.title }, @@ -74,7 +74,13 @@ class InMemoryConversationStore : ConversationStore { } override suspend fun rename(id: String, title: String) { - rows[id]?.let { rows[id] = it.copy(title = title) } + rows[id]?.let { + // A rename is a newer revision: the sync op id is keyed by it. + rows[id] = it.copy( + title = title, + updatedAt = maxOf(it.updatedAt + 1, System.currentTimeMillis()), + ) + } } override suspend fun delete(id: String) { @@ -96,4 +102,8 @@ class InMemoryConversationStore : ConversationStore { override suspend fun archive(id: String) { rows[id]?.let { rows[id] = it.copy(archivedAt = System.currentTimeMillis()) } } + + private companion object { + const val NEW_CHAT = "New chat" + } } From fc52e836686ca781f0b3b96267cac8f06c64035f Mon Sep 17 00:00:00 2001 From: aharonamir Date: Mon, 30 Nov 2026 00:42:08 +0200 Subject: [PATCH 14/58] Add the backend sync pass and its ownership rule BackendSync runs one pull-then-push pass on the shared engine off the main thread: the cursor comes from settings, the local backlog is every turn plus one revisioned title per thread, and a StoreTarget merges remote ops into the conversation store. A pass persists the cursor only when it finishes, emits the thread it changed, and serializes passes behind a mutex while coalescing triggers for 250 ms. An op older than the local revision is ignored, so an own last push cannot undo a newer rename, and a tombstone never takes a title. No identity, no token or no household key means SignedOut and no network. SyncOwnership decides which engine merges: a paired gateway with a household key wins over the PC bridge. Tests cover signed-out, local push dedupe, remote turns, title conflicts, tombstones, the cursor and a refused call. Part of #32. --- .../com/hopa/app/link/sync/BackendSync.kt | 369 ++++++++++++++++++ .../com/hopa/app/link/sync/SyncOutcome.kt | 16 + .../com/hopa/app/link/sync/SyncOwnership.kt | 39 ++ .../app/link/sync/SyncedConversationStore.kt | 33 ++ .../com/hopa/app/link/sync/BackendSyncTest.kt | 248 ++++++++++++ .../com/hopa/app/link/sync/SyncFixtures.kt | 224 +++++++++++ .../hopa/app/link/sync/SyncOwnershipTest.kt | 37 ++ 7 files changed, 966 insertions(+) create mode 100644 apps/android/app/src/main/kotlin/com/hopa/app/link/sync/BackendSync.kt create mode 100644 apps/android/app/src/main/kotlin/com/hopa/app/link/sync/SyncOutcome.kt create mode 100644 apps/android/app/src/main/kotlin/com/hopa/app/link/sync/SyncOwnership.kt create mode 100644 apps/android/app/src/main/kotlin/com/hopa/app/link/sync/SyncedConversationStore.kt create mode 100644 apps/android/app/src/test/kotlin/com/hopa/app/link/sync/BackendSyncTest.kt create mode 100644 apps/android/app/src/test/kotlin/com/hopa/app/link/sync/SyncFixtures.kt create mode 100644 apps/android/app/src/test/kotlin/com/hopa/app/link/sync/SyncOwnershipTest.kt diff --git a/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/BackendSync.kt b/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/BackendSync.kt new file mode 100644 index 000000000..bb10d770b --- /dev/null +++ b/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/BackendSync.kt @@ -0,0 +1,369 @@ +package com.hopa.app.link.sync + +import com.hopa.backend.pairing.BackendUrls +import com.hopa.backend.sync.client.SyncBacklog +import com.hopa.backend.sync.client.SyncCodec +import com.hopa.backend.sync.client.SyncCursor +import com.hopa.backend.sync.client.SyncDraft +import com.hopa.backend.sync.client.SyncEngine +import com.hopa.backend.sync.client.SyncHttp +import com.hopa.backend.sync.client.SyncHttpException +import com.hopa.backend.sync.client.SyncKind +import com.hopa.backend.sync.client.SyncTarget +import com.hopa.contracts.chat.ChatMessage +import com.hopa.contracts.chat.Conversation +import com.hopa.stores.AppSettings +import com.hopa.stores.ConversationStore +import com.hopa.stores.SettingsRepository +import java.util.Base64 +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.asSharedFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put + +/** + * The app's half of sync v0: one pull-then-push pass against the household op + * log, on the same store the chat already uses. + * + * A pass is built from the stored identity each time, so a sign-out or a token + * rotation takes effect on the next pass without a restart. The engine owns + * the wire rules; this class only maps [ConversationStore] rows to its target, + * builds the local backlog and serializes passes. + */ +internal class BackendSync( + private val settings: SettingsRepository, + private val store: ConversationStore, + private val http: SyncHttp, + private val scope: CoroutineScope, + private val now: () -> Long = System::currentTimeMillis, +) { + /** Serializes passes: a trigger that lands mid-pass waits instead of racing. */ + private val pass = Mutex() + private val triggers = Any() + + private val _changes = MutableSharedFlow(extraBufferCapacity = CHANGES_BUFFER) + /** Thread ids a pass changed, or `""` when more than one did. */ + val changes: SharedFlow = _changes.asSharedFlow() + + @Volatile + private var running = false + private var pending: Job? = null + + /** One pull-then-push pass; waits for a pass already in flight. */ + suspend fun syncNow(): SyncOutcome = withContext(Dispatchers.IO) { + pass.withLock { runPass() } + } + + /** Begin coalescing local and remote triggers into passes. */ + fun start() { + running = true + } + + /** Stop triggering passes. One already in flight is allowed to finish. */ + fun stop() { + running = false + synchronized(triggers) { + pending?.cancel() + pending = null + } + } + + /** A turn was appended locally. */ + fun onLocalTurn(threadId: String) = schedule() + + /** A thread was renamed locally. */ + fun onLocalRename(threadId: String) = schedule() + + /** A thread was deleted locally. */ + fun onLocalDelete(threadId: String) = schedule() + + /** The gateway said a peer wrote up to some seq. */ + fun onRemoteChanged() = schedule() + + /** + * Coalesces triggers into one pass: a trigger inside the window replaces + * the pending one, so a burst of writes costs one pull. + */ + private fun schedule() { + if (!running) { + return + } + synchronized(triggers) { + pending?.cancel() + pending = scope.launch { + delay(DEBOUNCE_MS) + try { + syncNow() + } catch (cancelled: CancellationException) { + throw cancelled + } catch (_: Exception) { + // A pass reports its own failures; a trigger never crashes the scope. + } + } + } + } + + private suspend fun runPass(): SyncOutcome { + val current = settings.settings.first() + val token = settings.backendAccessToken() + if (current.backendDeviceId.isBlank() || current.backendUrl.isBlank() || token.isBlank()) { + return SyncOutcome.SignedOut + } + val storedKey = settings.backendContentKey() + if (storedKey.isBlank()) { + return SyncOutcome.SignedOut + } + val key = decodeKey(storedKey) ?: return SyncOutcome.Failed("E_KEY") + + val startedAt = current.backendSyncSeq + val cursor = PassCursor(startedAt) + val target = StoreTarget(store) + val baseUrl = BackendUrls.httpBase(current.backendUrl) + val engine = SyncEngine( + http = http, + codec = SyncCodec(key), + target = target, + cursor = cursor, + token = { token }, + baseUrl = { baseUrl }, + ) + + return try { + val report = engine.pull() + val pushed = push(engine, current, target) + // Only a finished pass may move the cursor: a refused call must be + // retried from the same seq, and replaying is idempotent. + if (cursor.read() != startedAt) { + settings.setBackendSyncSeq(cursor.read()) + } + publish(target.changed) + SyncOutcome.Done(report.applied, pushed) + } catch (cancelled: CancellationException) { + throw cancelled + } catch (refused: SyncHttpException) { + SyncOutcome.Failed( + refused.code?.takeIf { it.isNotBlank() } + ?: if (refused.status == UNAUTHORIZED) "E_AUTH" else "E_SYNC", + ) + } catch (_: Exception) { + // A bad tag, a transport reset or an unparsable body: the code is all + // the caller gets, because a message could quote plaintext. + SyncOutcome.Failed("E_SYNC") + } + } + + /** + * Sends the whole local set. Ids are deterministic, so the server dedupes a + * turn this phone received from a peer and a title it already holds. + */ + private suspend fun push(engine: SyncEngine, current: AppSettings, target: StoreTarget): Int { + val drafts = backlog(current) + if (drafts.isEmpty()) { + return 0 + } + val answer = engine.push(drafts) + val threads = drafts.associate { it.opId to it.threadId } + for (ack in answer.accepted) { + if (!ack.duplicate) { + threads[ack.opId]?.let(target::markChanged) + } + } + return answer.accepted.count { !it.duplicate } + } + + private suspend fun backlog(current: AppSettings): List { + val device = current.backendDeviceId + val turns = mutableListOf() + val threads = mutableListOf() + for (thread in store.allWithDeleted()) { + for (message in thread.messages) { + if (message.role !in ROLES || message.text.isBlank()) { + continue + } + val at = message.timestamp.takeIf { it > 0 } ?: now() + turns += SyncDraft( + opId = message.id, + kind = SyncKind.TURN_APPEND, + threadId = thread.id, + turnId = message.id, + payload = buildJsonObject { + put("role", message.role) + put("text", message.text) + put("at", at) + }, + clientAt = at, + ) + } + // The title id is keyed by the local revision: a rename or a delete + // writes a newer `updatedAt`, so the next pass is a new op. + val at = thread.updatedAt + threads += SyncDraft( + opId = SyncBacklog.titleOpId(thread.id, at, device), + kind = SyncKind.THREAD_UPSERT, + threadId = thread.id, + turnId = null, + payload = buildJsonObject { + if (thread.deletedAt == 0L) { + put("title", thread.title) + } + put("deletedAt", thread.deletedAt) + put("clientAt", at) + }, + clientAt = at, + ) + } + return threads + SyncBacklog.orderTurns(turns) + } + + private fun publish(changed: Set) { + val id = when { + changed.isEmpty() -> return + changed.size == 1 -> changed.single() + else -> ALL_THREADS + } + _changes.tryEmit(id) + } + + private fun decodeKey(stored: String): ByteArray? = runCatching { + Base64.getDecoder().decode(stored) + }.getOrNull()?.takeIf { it.size == CONTENT_KEY_BYTES } + + /** The cursor for one pass, persisted to settings only after it succeeds. */ + private class PassCursor(initial: Long) : SyncCursor { + private var seq = initial + + override fun read(): Long = seq + + override fun write(seq: Long) { + this.seq = seq + } + } + + /** + * [ConversationStore] as [SyncTarget]. One snapshot serves every `hasTurn` + * in a pass, so a long thread list is not re-read per op; each applied op + * updates the snapshot so a later op in the same pass sees it. + */ + private class StoreTarget(private val store: ConversationStore) : SyncTarget { + private var rows: Map? = null + private val changedIds = linkedSetOf() + + val changed: Set get() = changedIds + + fun markChanged(threadId: String) { + changedIds += threadId + } + + private suspend fun rows(): Map = + rows ?: store.allWithDeleted().associateBy { it.id }.also { rows = it } + + private suspend fun remember(row: Conversation) { + rows = rows() + (row.id to row) + } + + override suspend fun hasTurn(threadId: String, turnId: String): Boolean = + rows()[threadId]?.messages?.any { it.id == turnId } == true + + override suspend fun appendTurn( + threadId: String, + turnId: String, + role: String, + text: String, + at: Long, + ) { + val existing = rows()[threadId] + val message = ChatMessage(turnId, role, text, at) + // A blank title keeps the stored one (and "New chat" for a fresh row). + store.adopt( + Conversation( + id = threadId, + title = "", + messages = listOf(message), + updatedAt = at, + ), + ) + remember( + existing?.copy( + messages = (existing.messages + message).distinctBy { it.id }, + updatedAt = maxOf(existing.updatedAt, at), + ) ?: Conversation( + id = threadId, + title = NEW_CHAT, + messages = listOf(message), + updatedAt = at, + ), + ) + markChanged(threadId) + } + + override suspend fun applyThread( + threadId: String, + title: String?, + deletedAt: Long, + clientAt: Long, + ) { + val existing = rows()[threadId] + val gone = maxOf(existing?.deletedAt ?: 0, deletedAt) > 0 + // A rename is a revision: an op older than what this phone already + // has must not undo a newer local title (our own last push is such + // an op when it comes back on the next pull). + val stale = existing != null && clientAt < existing.updatedAt + // A tombstone is final: a later title must not resurrect the thread, + // and a deleted thread never takes a title. + val nextTitle = if (gone || stale) "" else title.orEmpty() + store.adopt( + Conversation( + id = threadId, + title = nextTitle, + updatedAt = clientAt, + deletedAt = deletedAt, + ), + ) + val row = Conversation( + id = threadId, + title = nextTitle.ifBlank { existing?.title ?: NEW_CHAT }, + messages = existing?.messages.orEmpty(), + updatedAt = maxOf(existing?.updatedAt ?: 0, clientAt), + deletedAt = maxOf(existing?.deletedAt ?: 0, deletedAt), + pinned = existing?.pinned ?: false, + archivedAt = existing?.archivedAt ?: 0, + ) + remember(row) + val changed = existing == null || + row.deletedAt != existing.deletedAt || + (!gone && !stale && title != null && title != existing.title) || + clientAt > existing.updatedAt + if (changed) { + markChanged(threadId) + } + } + } + + private companion object { + /** Wait this long for the rest of a burst before one pass. */ + const val DEBOUNCE_MS = 250L + + /** Room for a UI collector that is briefly busy. */ + const val CHANGES_BUFFER = 32 + + /** `""` asks a collector to reload everything, not one thread. */ + const val ALL_THREADS = "" + + const val CONTENT_KEY_BYTES = 32 + const val UNAUTHORIZED = 401 + const val NEW_CHAT = "New chat" + + val ROLES = setOf("user", "assistant") + } +} diff --git a/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/SyncOutcome.kt b/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/SyncOutcome.kt new file mode 100644 index 000000000..76b0f4413 --- /dev/null +++ b/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/SyncOutcome.kt @@ -0,0 +1,16 @@ +package com.hopa.app.link.sync + +/** What one [BackendSync] pass did, in terms the sync sheet can show. */ +sealed interface SyncOutcome { + /** No gateway identity or no household key: nothing was sent. */ + data object SignedOut : SyncOutcome + + /** [applied] remote ops reached the store; [pushed] local ops were new to the server. */ + data class Done(val applied: Int, val pushed: Int) : SyncOutcome + + /** + * The pass stopped. [code] is the server's safe error code (`E_AUTH`, ...) + * or a local one (`E_KEY`, `E_SYNC`); it never carries payload text. + */ + data class Failed(val code: String) : SyncOutcome +} diff --git a/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/SyncOwnership.kt b/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/SyncOwnership.kt new file mode 100644 index 000000000..e1dc87242 --- /dev/null +++ b/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/SyncOwnership.kt @@ -0,0 +1,39 @@ +package com.hopa.app.link.sync + +import com.hopa.stores.SettingsRepository +import kotlinx.coroutines.flow.first + +/** Which engine merges this phone's chats. */ +internal enum class SyncOwner { + /** The backend op log; the bridge must not also merge. */ + BACKEND, + + /** The paired PC's bridge snapshot. */ + BRIDGE, + + /** No sync is configured. */ + NONE, +} + +/** + * The one rule that decides who merges chats. A paired gateway with a + * household key wins: its op log carries every member's writes, while the + * bridge is one PC's view. Without those credentials the bridge keeps the + * path it had, and with neither nothing runs. + */ +internal object SyncOwnership { + suspend fun owner(settings: SettingsRepository): SyncOwner { + val current = settings.settings.first() + val identified = current.backendDeviceId.isNotBlank() && current.backendUrl.isNotBlank() + val backend = identified && + settings.backendAccessToken().isNotBlank() && + settings.backendContentKey().isNotBlank() + if (backend) { + return SyncOwner.BACKEND + } + val bridge = current.useBridge && + current.bridgeUrl.isNotBlank() && + settings.bridgeToken().isNotBlank() + return if (bridge) SyncOwner.BRIDGE else SyncOwner.NONE + } +} diff --git a/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/SyncedConversationStore.kt b/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/SyncedConversationStore.kt new file mode 100644 index 000000000..ccdb4754c --- /dev/null +++ b/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/SyncedConversationStore.kt @@ -0,0 +1,33 @@ +package com.hopa.app.link.sync + +import com.hopa.contracts.chat.ChatMessage +import com.hopa.contracts.chat.Conversation +import com.hopa.stores.ConversationStore + +/** + * A [ConversationStore] that tells [BackendSync] after each local write, so a + * turn, rename or delete reaches the PC without waiting for the next launch. + * Remote merges arrive through [ConversationStore.adopt], which does not + * notify; a synced thread therefore cannot re-trigger a push on its own. + */ +internal class SyncedConversationStore( + private val inner: ConversationStore, + private val onTurn: (String) -> Unit, + private val onRename: (String) -> Unit, + private val onDelete: (String) -> Unit, +) : ConversationStore by inner { + override suspend fun append(id: String, message: ChatMessage) { + inner.append(id, message) + onTurn(id) + } + + override suspend fun rename(id: String, title: String) { + inner.rename(id, title) + onRename(id) + } + + override suspend fun delete(id: String) { + inner.delete(id) + onDelete(id) + } +} diff --git a/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/BackendSyncTest.kt b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/BackendSyncTest.kt new file mode 100644 index 000000000..9d1839ab8 --- /dev/null +++ b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/BackendSyncTest.kt @@ -0,0 +1,248 @@ +package com.hopa.app.link.sync + +import com.hopa.backend.sync.client.SyncHttpException +import com.hopa.backend.sync.client.SyncKind +import com.hopa.contracts.chat.ChatMessage +import com.hopa.contracts.chat.Conversation +import com.hopa.stores.InMemoryConversationStore +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test + +class BackendSyncTest { + @Test + fun `a signed-out phone takes no pass and makes no call`() = runBlocking { + val store = InMemoryConversationStore() + val server = FakeSyncServer() + val sync = BackendSync( + settings = FakeSyncSettings(device = "", access = "", contentKey = ""), + store = store, + http = server, + scope = this, + ) + + assertEquals(SyncOutcome.SignedOut, sync.syncNow()) + assertEquals(0, server.pulls) + assertTrue(server.pushBatches.isEmpty()) + } + + @Test + fun `a paired phone with no household key makes no call`() = runBlocking { + val store = InMemoryConversationStore() + val server = FakeSyncServer() + val sync = BackendSync( + settings = FakeSyncSettings(device = "d1", access = "a1", contentKey = ""), + store = store, + http = server, + scope = this, + ) + + assertEquals(SyncOutcome.SignedOut, sync.syncNow()) + assertEquals(0, server.pulls) + assertTrue(server.pushBatches.isEmpty()) + } + + @Test + fun `a local turn is pushed every pass and the server dedupes it`() = runBlocking { + val store = InMemoryConversationStore() + val chat = store.create() + store.append(chat.id, ChatMessage("m-1", "user", "hello", 10)) + val server = FakeSyncServer() + val sync = BackendSync( + settings = signedIn(), + store = store, + http = server, + scope = this, + ) + + val first = sync.syncNow() as SyncOutcome.Done + // The thread upsert travels with the turn. + assertEquals(2, first.pushed) + assertEquals(1, server.pushBatches.size) + assertTrue(server.pushBatches.single().any { it.opId == "m-1" && it.turnId == "m-1" }) + assertEquals(1, server.opCount("m-1")) + assertEquals("https://hopa.test", server.baseUrls.first()) + + val second = sync.syncNow() as SyncOutcome.Done + assertEquals(2, server.pushBatches.size) + assertTrue(server.pushBatches[1].any { it.opId == "m-1" }) + assertEquals(1, server.opCount("m-1")) + assertEquals(0, second.pushed) + assertEquals(1, store.allWithDeleted().single { it.id == chat.id }.messages.size) + } + + @Test + fun `a remote turn is applied once with its id and timestamp`() = runBlocking { + val store = InMemoryConversationStore() + val server = FakeSyncServer() + server.seed( + kind = SyncKind.TURN_APPEND, + threadId = "c-remote", + turnId = "m-remote", + payload = turnPayload("user", "from the pc", 42), + opId = "m-remote", + clientAt = 42, + ) + val sync = BackendSync(settings = signedIn(), store = store, http = server, scope = this) + + val report = sync.syncNow() as SyncOutcome.Done + + assertEquals(1, report.applied) + val thread = store.allWithDeleted().single { it.id == "c-remote" } + val message = thread.messages.single() + assertEquals("m-remote", message.id) + assertEquals("user", message.role) + assertEquals("from the pc", message.text) + assertEquals(42, message.timestamp) + + sync.syncNow() + assertEquals(1, store.allWithDeleted().single { it.id == "c-remote" }.messages.size) + } + + @Test + fun `a remote title renames and a later local rename wins`() = runBlocking { + val store = InMemoryConversationStore() + store.adopt( + Conversation( + id = "c-1", + title = "Old", + messages = listOf(ChatMessage("m-1", "user", "hi", 5)), + updatedAt = 5, + ), + ) + val server = FakeSyncServer() + server.seed( + kind = SyncKind.THREAD_UPSERT, + threadId = "c-1", + turnId = null, + payload = threadPayload("Remote", deletedAt = 0, clientAt = 10), + opId = "remote-title", + clientAt = 10, + ) + val sync = BackendSync(settings = signedIn(), store = store, http = server, scope = this) + + sync.syncNow() + assertEquals("Remote", store.allWithDeleted().single { it.id == "c-1" }.title) + + store.rename("c-1", "Mine") + sync.syncNow() + assertEquals("Mine", server.titleOf("c-1")) + } + + @Test + fun `a tombstone hides the thread and a later title does not revive it`() = runBlocking { + val store = InMemoryConversationStore() + store.adopt( + Conversation( + id = "c-1", + title = "Live", + messages = listOf(ChatMessage("m-1", "user", "hi", 5)), + updatedAt = 5, + ), + ) + val server = FakeSyncServer() + server.seed( + kind = SyncKind.THREAD_UPSERT, + threadId = "c-1", + turnId = null, + payload = threadPayload(null, deletedAt = 99, clientAt = 20), + opId = "tombstone", + clientAt = 20, + ) + server.seed( + kind = SyncKind.THREAD_UPSERT, + threadId = "c-1", + turnId = null, + payload = threadPayload("Back", deletedAt = 0, clientAt = 30), + opId = "title-after-delete", + clientAt = 30, + ) + val sync = BackendSync(settings = signedIn(), store = store, http = server, scope = this) + + sync.syncNow() + + val thread = store.allWithDeleted().single { it.id == "c-1" } + assertTrue(thread.deletedAt > 0) + assertFalse(store.all().any { it.id == "c-1" }) + assertEquals("Live", thread.title) + } + + @Test + fun `the cursor advances so the next pull asks after the last applied seq`() = runBlocking { + val store = InMemoryConversationStore() + val server = FakeSyncServer() + server.seed( + SyncKind.TURN_APPEND, + "c-1", + "m-1", + turnPayload("user", "one", 10), + opId = "m-1", + clientAt = 10, + ) + server.seed( + SyncKind.TURN_APPEND, + "c-1", + "m-2", + turnPayload("assistant", "two", 11), + opId = "m-2", + clientAt = 11, + ) + val settings = signedIn() + val sync = BackendSync(settings = settings, store = store, http = server, scope = this) + + val first = sync.syncNow() as SyncOutcome.Done + assertEquals(2, first.applied) + assertEquals(2, settings.current.backendSyncSeq) + + sync.syncNow() + assertEquals(listOf(0L, 2L), server.pullAfters) + assertEquals(2, store.allWithDeleted().single { it.id == "c-1" }.messages.size) + } + + @Test + fun `a pass announces the thread it changed`() = runBlocking { + val store = InMemoryConversationStore() + val server = FakeSyncServer() + server.seed( + SyncKind.TURN_APPEND, + "c-remote", + "m-remote", + turnPayload("assistant", "hello", 42), + opId = "m-remote", + clientAt = 42, + ) + val sync = BackendSync(settings = signedIn(), store = store, http = server, scope = this) + val seen = mutableListOf() + val collector = launch(Dispatchers.Unconfined) { sync.changes.collect { seen += it } } + + sync.syncNow() + collector.cancel() + + assertEquals(listOf("c-remote"), seen) + } + + @Test + fun `a refused call fails without moving the cursor`() = runBlocking { + val store = InMemoryConversationStore() + val server = FakeSyncServer().apply { + failure = SyncHttpException("E_AUTH", "unauthorized", 401) + } + val settings = signedIn() + settings.update { it.copy(backendSyncSeq = 5) } + val sync = BackendSync(settings = settings, store = store, http = server, scope = this) + + assertEquals(SyncOutcome.Failed("E_AUTH"), sync.syncNow()) + assertEquals(5, settings.current.backendSyncSeq) + assertTrue(server.pushBatches.isEmpty()) + } + + private fun signedIn(): FakeSyncSettings = FakeSyncSettings( + device = "d1", + access = "a1", + contentKey = TEST_CONTENT_KEY_BASE64, + ) +} diff --git a/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/SyncFixtures.kt b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/SyncFixtures.kt new file mode 100644 index 000000000..85056268f --- /dev/null +++ b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/SyncFixtures.kt @@ -0,0 +1,224 @@ +package com.hopa.app.link.sync + +import com.hopa.backend.sync.client.PullAnswer +import com.hopa.backend.sync.client.PushAck +import com.hopa.backend.sync.client.PushAnswer +import com.hopa.backend.sync.client.RemoteSyncOp +import com.hopa.backend.sync.client.SealedOp +import com.hopa.backend.sync.client.SyncCodec +import com.hopa.backend.sync.client.SyncDraft +import com.hopa.backend.sync.client.SyncHttp +import com.hopa.backend.sync.client.SyncHttpException +import com.hopa.backend.sync.client.SyncKind +import com.hopa.contracts.json.HopaJson +import com.hopa.stores.AppSettings +import com.hopa.stores.SettingsRepository +import java.util.Base64 +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive + +/** The 32-byte household key both ends of these tests share. */ +internal val TEST_CONTENT_KEY: ByteArray = ByteArray(32) { index -> index.toByte() } + +internal val TEST_CONTENT_KEY_BASE64: String = + Base64.getEncoder().encodeToString(TEST_CONTENT_KEY) + +/** + * Settings in memory. Unlike the session fixture it keeps the bridge token too, + * because the ownership rule reads both sides. + */ +internal class FakeSyncSettings( + url: String = "wss://hopa.test/v1/gateway", + device: String = "", + access: String = "", + contentKey: String = "", +) : SettingsRepository { + private val state = MutableStateFlow( + AppSettings(backendUrl = url, backendDeviceId = device), + ) + + override val settings: StateFlow = state + val current: AppSettings get() = state.value + + private var accessToken = access + private var refreshToken = "" + private var privateKey = "" + private var content = contentKey + private var bridge = "" + private var bridgeRefreshToken = "" + private var model = "" + + fun withBridge(): FakeSyncSettings = apply { + state.value = state.value.copy(useBridge = true, bridgeUrl = "http://pc.test:8123") + bridge = "bridge-token" + } + + override suspend fun update(transform: (AppSettings) -> AppSettings) { + state.value = transform(state.value) + } + + override suspend fun modelKey(): String = model + override suspend fun hasModelKey(): Boolean = model.isNotBlank() + override suspend fun setModelKey(value: String) { + model = value + } + + override suspend fun bridgeToken(): String = bridge + override suspend fun setBridgeToken(value: String) { + bridge = value + } + + override suspend fun bridgeRefresh(): String = bridgeRefreshToken + override suspend fun setBridgeRefresh(value: String) { + bridgeRefreshToken = value + } + + override suspend fun backendAccessToken(): String = accessToken + override suspend fun setBackendAccessToken(value: String) { + accessToken = value + } + + override suspend fun backendRefreshToken(): String = refreshToken + override suspend fun setBackendRefreshToken(value: String) { + refreshToken = value + } + + override suspend fun backendPrivateKey(): String = privateKey + override suspend fun setBackendPrivateKey(value: String) { + privateKey = value + } + + override suspend fun backendContentKey(): String = content + override suspend fun setBackendContentKey(value: String) { + content = value + } + + override suspend fun clearBackend() { + accessToken = "" + refreshToken = "" + privateKey = "" + content = "" + state.value = state.value.copy(backendDeviceId = "", backendSyncSeq = 0) + } +} + +/** + * The sync routes in memory: it stores ops by op id, assigns seqs in push order + * and dedupes a repeated id the way the server does. Seeded ops stand in for a + * peer's writes. + */ +internal class FakeSyncServer(key: ByteArray = TEST_CONTENT_KEY) : SyncHttp { + private val codec = SyncCodec(key) + private val stored = mutableListOf() + private val byId = mutableMapOf() + + /** Every push body, in call order. */ + val pushBatches = mutableListOf>() + + /** The `after` of every pull, in call order. */ + val pullAfters = mutableListOf() + + /** The base URL every call carried. */ + val baseUrls = mutableListOf() + + var pulls = 0 + private set + + var failure: SyncHttpException? = null + + override suspend fun push(token: String, baseUrl: String, ops: List): PushAnswer { + failure?.let { throw it } + baseUrls += baseUrl + pushBatches += ops + val accepted = ops.map { op -> + val duplicate = byId[op.opId] + if (duplicate != null) { + PushAck(op.opId, duplicate.seq, duplicate = true) + } else { + val row = store(op.opId, op.kind, op.threadId, op.turnId, op.clientAt, op.ct, "phone") + PushAck(op.opId, row.seq, duplicate = false) + } + } + return PushAnswer(head = stored.size.toLong(), accepted = accepted) + } + + override suspend fun pull(token: String, baseUrl: String, after: Long, limit: Int): PullAnswer { + failure?.let { throw it } + pulls += 1 + baseUrls += baseUrl + pullAfters += after + val page = stored.filter { it.seq > after }.sortedBy { it.seq }.take(limit) + val last = page.lastOrNull()?.seq ?: after + return PullAnswer( + ops = page, + hasMore = stored.any { it.seq > last }, + head = stored.size.toLong(), + ) + } + + fun seed( + kind: SyncKind, + threadId: String, + turnId: String?, + payload: JsonObject, + opId: String, + clientAt: Long, + fromDevice: String = "pc", + ): RemoteSyncOp { + val sealed = codec.seal(SyncDraft(opId, kind, threadId, turnId, payload, clientAt)) + return store(opId, kind, threadId, turnId, clientAt, sealed.ct, fromDevice) + } + + fun opCount(opId: String): Int = stored.count { it.opId == opId } + + /** The title the last accepted thread upsert left for [threadId]. */ + fun titleOf(threadId: String): String? = stored.asReversed() + .firstOrNull { it.kind == SyncKind.THREAD_UPSERT && it.threadId == threadId } + ?.let { op -> codec.open(op)["title"]?.jsonPrimitive?.content } + + private fun store( + opId: String, + kind: SyncKind, + threadId: String, + turnId: String?, + clientAt: Long, + ct: String, + fromDevice: String, + ): RemoteSyncOp { + val seq = (stored.maxOfOrNull { it.seq } ?: 0L) + 1 + val row = RemoteSyncOp( + seq = seq, + opId = opId, + kind = kind, + threadId = threadId, + turnId = turnId, + fromDevice = fromDevice, + memberId = "member-1", + clientAt = clientAt, + at = "2026-11-20T00:00:00Z", + ciphertext = Base64.getDecoder().decode(ct), + ) + stored += row + byId[opId] = row + return row + } +} + +/** The `turn.append` payload the engine expects. */ +internal fun turnPayload(role: String, text: String, at: Long): JsonObject = + HopaJson.element.parseToJsonElement( + """{"role":"$role","text":"$text","at":$at}""", + ).jsonObject + +/** A `thread.upsert` payload; an absent title means "no title change". */ +internal fun threadPayload(title: String?, deletedAt: Long, clientAt: Long): JsonObject = + HopaJson.element.parseToJsonElement( + buildString { + append("{") + if (title != null) append("\"title\":\"$title\",") + append("\"deletedAt\":$deletedAt,\"clientAt\":$clientAt}") + }, + ).jsonObject diff --git a/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/SyncOwnershipTest.kt b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/SyncOwnershipTest.kt new file mode 100644 index 000000000..4d957724c --- /dev/null +++ b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/SyncOwnershipTest.kt @@ -0,0 +1,37 @@ +package com.hopa.app.link.sync + +import kotlinx.coroutines.runBlocking +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +class SyncOwnershipTest { + @Test + fun `backend credentials own the merge even when a bridge is configured`() = runBlocking { + val settings = FakeSyncSettings( + device = "d1", + access = "a1", + contentKey = TEST_CONTENT_KEY_BASE64, + ).withBridge() + + assertEquals(SyncOwner.BACKEND, SyncOwnership.owner(settings)) + } + + @Test + fun `without backend credentials the bridge owns the merge`() = runBlocking { + assertEquals(SyncOwner.BRIDGE, SyncOwnership.owner(FakeSyncSettings().withBridge())) + } + + @Test + fun `without a content key the bridge still owns the merge`() = runBlocking { + // The engine cannot open a payload without the household key, so the + // bridge keeps the path instead of a backend that would always fail. + val settings = FakeSyncSettings(device = "d1", access = "a1").withBridge() + + assertEquals(SyncOwner.BRIDGE, SyncOwnership.owner(settings)) + } + + @Test + fun `no credentials and no bridge means no chat sync`() = runBlocking { + assertEquals(SyncOwner.NONE, SyncOwnership.owner(FakeSyncSettings())) + } +} From 23336f1fb021a8def0f602034e9cb38e32d3ba66 Mon Sep 17 00:00:00 2001 From: aharonamir Date: Mon, 30 Nov 2026 00:42:15 +0200 Subject: [PATCH 15/58] Route chat sync through the paired backend With a gateway identity and a household key, the backend op log owns chat merge and the PC bridge is not even built; without those credentials the bridge keeps the path it had. Local appends, renames and deletes notify the sync through a ConversationStore decorator, a peer's sync.changed pulls, and a foreground pass catches up after the app was away. The chat and chats-sheet view models reload from the store when a pass reports a changed thread, through a defaulted dependency property so other fakes are untouched. Part of #32. --- .../main/kotlin/com/hopa/app/MainActivity.kt | 3 + .../kotlin/com/hopa/app/di/AppContainer.kt | 71 ++++++++++++++++++- .../hopa/app/link/session/BackendSession.kt | 7 ++ .../app/link/session/BackendSessionTest.kt | 24 +++++++ .../hopa/app/link/session/SessionFixtures.kt | 1 + .../com/hopa/feature/chat/ChatDependencies.kt | 8 +++ .../com/hopa/feature/chat/ChatViewModel.kt | 16 +++++ .../ConversationsDependencies.kt | 8 +++ .../conversations/ConversationsViewModel.kt | 5 ++ 9 files changed, 140 insertions(+), 3 deletions(-) diff --git a/apps/android/app/src/main/kotlin/com/hopa/app/MainActivity.kt b/apps/android/app/src/main/kotlin/com/hopa/app/MainActivity.kt index 535680a2e..c1c0933a6 100644 --- a/apps/android/app/src/main/kotlin/com/hopa/app/MainActivity.kt +++ b/apps/android/app/src/main/kotlin/com/hopa/app/MainActivity.kt @@ -40,6 +40,9 @@ class MainActivity : ComponentActivity() { com.hopa.app.service.AppVisibility.foreground = true val container = (application as HopaApplication).container container.backend.onForeground() + // Catch up on whatever a peer wrote while the app was away; a pass is + // cheap and a no-op when signed out. + container.requestSync() // Quietly, in the background: a newer catalog, if the backend has one. lifecycleScope.launch { container.knowledgeUpdater.refresh() } ScreenCaptureRequester.launch = { diff --git a/apps/android/app/src/main/kotlin/com/hopa/app/di/AppContainer.kt b/apps/android/app/src/main/kotlin/com/hopa/app/di/AppContainer.kt index 4732d1edb..61d874679 100644 --- a/apps/android/app/src/main/kotlin/com/hopa/app/di/AppContainer.kt +++ b/apps/android/app/src/main/kotlin/com/hopa/app/di/AppContainer.kt @@ -13,6 +13,11 @@ import com.hopa.app.BuildConfig import com.hopa.app.link.push.PushTokenFetch import com.hopa.app.link.push.FirebaseToken import com.hopa.app.link.session.BackendLaunchName +import com.hopa.app.link.sync.BackendSync +import com.hopa.app.link.sync.SyncOutcome +import com.hopa.app.link.sync.SyncOwner +import com.hopa.app.link.sync.SyncOwnership +import com.hopa.app.link.sync.SyncedConversationStore import com.hopa.app.link.remote.ProcessedTaskStore import com.hopa.app.link.remote.RemoteRunRequest import com.hopa.app.link.remote.RemoteTaskRunner @@ -77,6 +82,7 @@ import com.hopa.stores.ConversationStore import com.hopa.stores.SettingsRepository import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch @@ -158,7 +164,34 @@ class AppContainer @Inject constructor(@ApplicationContext context: Context) : C } private val database = HopaDatabase.build(context) - override val conversations: ConversationStore = DbConversationStore(database) + private val chatRows: ConversationStore = DbConversationStore(database) + + /** + * Local writes notify the backend sync so a turn, rename or delete reaches + * the PC promptly. Remote merges land through [ConversationStore.adopt], + * which does not notify, so applying an op cannot trigger another push. + */ + override val conversations: ConversationStore = SyncedConversationStore( + inner = chatRows, + onTurn = { sync.onLocalTurn(it) }, + onRename = { sync.onLocalRename(it) }, + onDelete = { sync.onLocalDelete(it) }, + ) + + /** The backend engine; each pass builds its client from the stored identity. */ + private val sync: BackendSync by lazy { + BackendSync( + settings = settings, + store = conversations, + http = com.hopa.backend.sync.client.OkHttpSyncHttp(), + scope = appScope, + ) + } + + /** Thread ids a backend pass changed, or `""` for all of them. */ + override val conversationChanges: Flow + get() = sync.changes + /** * The tables this client uses. A stored bundle wins over the bundled * snapshot; the file store falls back to it on any problem. `knowledge` is a @@ -408,6 +441,15 @@ class AppContainer @Inject constructor(@ApplicationContext context: Context) : C // A diagnostic is plaintext and not goal-bearing; the session acks it // regardless. Nothing here reads or logs the body (trace/id only). backend.onDiagnostic = { } + // A peer's write is a hint to pull; the pass itself decides what is new. + backend.onSyncChanged = { sync.onRemoteChanged() } + // Local writes are only pushed while a household identity is stored; + // signed out, a debounced trigger would only read settings and stop. + appScope.launch { + settings.settings.collect { current -> + if (current.backendDeviceId.isNotBlank()) sync.start() else sync.stop() + } + } } private fun startRunServiceInternal() { @@ -634,11 +676,34 @@ class AppContainer @Inject constructor(@ApplicationContext context: Context) : C } override suspend fun syncChats(): ChatSyncOutcome? { - val sync = chatSync() ?: return null - val report = sync.run() + // One owner: with backend credentials the op log merges and the bridge + // is never built; the bridge must not run beside it or two writers + // would fight over the same tombstones. + val engine = backendSync() + if (engine != null) { + return when (val outcome = engine.syncNow()) { + is SyncOutcome.Done -> ChatSyncOutcome(adopted = outcome.applied, tombstoned = 0) + SyncOutcome.SignedOut -> null + is SyncOutcome.Failed -> throw IllegalStateException(outcome.code) + } + } + val bridge = chatSync() ?: return null + val report = bridge.run() return ChatSyncOutcome(adopted = report.adopted, tombstoned = report.tombstoned) } + /** + * The backend engine when it owns merge: a pairing plus a household key. + * The check reads the secret store, so it is suspend. + */ + internal suspend fun backendSync(): BackendSync? = + if (SyncOwnership.owner(settings) == SyncOwner.BACKEND) sync else null + + /** One pass off the main thread, e.g. when the app comes to the front. */ + fun requestSync() { + appScope.launch { sync.syncNow() } + } + override val backendState: StateFlow get() = backend.state diff --git a/apps/android/app/src/main/kotlin/com/hopa/app/link/session/BackendSession.kt b/apps/android/app/src/main/kotlin/com/hopa/app/link/session/BackendSession.kt index d041339ca..8491b431f 100644 --- a/apps/android/app/src/main/kotlin/com/hopa/app/link/session/BackendSession.kt +++ b/apps/android/app/src/main/kotlin/com/hopa/app/link/session/BackendSession.kt @@ -70,6 +70,10 @@ class BackendSession( @Volatile var onDiagnostic: (suspend (BackendEnvelope) -> Unit)? = null + /** A peer wrote up to this seq; the app pulls after its own cursor. */ + @Volatile + var onSyncChanged: (suspend (Long) -> Unit)? = null + /** The live socket, for the runner that answers a delivery on it. */ fun currentLink(): BackendLink? = link @@ -282,6 +286,9 @@ class BackendSession( onTask?.invoke(envelope) } created.onApproval = { envelope -> onApproval?.invoke(envelope) } + // A sync notification is a seq only. The link delivers it off the reader, + // so a slow pull cannot stall the socket. + created.onSyncChanged = { seq -> onSyncChanged?.invoke(seq) } created.onDiagnostic = { envelope -> // A diagnostic is plaintext and never goal-bearing; always ack it on // the link it arrived on, even when the handler throws, and never let diff --git a/apps/android/app/src/test/kotlin/com/hopa/app/link/session/BackendSessionTest.kt b/apps/android/app/src/test/kotlin/com/hopa/app/link/session/BackendSessionTest.kt index 9f9ab0e01..1bda31c5b 100644 --- a/apps/android/app/src/test/kotlin/com/hopa/app/link/session/BackendSessionTest.kt +++ b/apps/android/app/src/test/kotlin/com/hopa/app/link/session/BackendSessionTest.kt @@ -297,6 +297,30 @@ class BackendSessionTest { } } + @Test + fun `a sync changed seq reaches the app handler once and carries no text`() = runBlocking { + val settings = FakeSettings().paired("wss://x/v1/gateway") + val created = CompletableDeferred() + val session = session(settings, linkFactory = { credentials, _, _, pushToken, refresh -> + FakeLink(credentials, pushToken, refresh).also { created.complete(it) } + }) + val seen = CopyOnWriteArrayList() + session.onSyncChanged = { seq -> seen += seq } + try { + session.onForeground() + val link = withTimeout(WAIT_MS) { created.await() } + withTimeout(WAIT_MS) { while (link.onSyncChanged == null) delay(10) } + + requireNotNull(link.onSyncChanged).invoke(5L) + + withTimeout(WAIT_MS) { while (seen.isEmpty()) delay(10) } + // Only the seq crosses the boundary: nothing about a payload can leak. + assertEquals(listOf(5L), seen) + } finally { + session.disconnect() + } + } + @Test fun `a refresh keeps the v1 gateway socket, not the HTTP origin`() = runBlocking { val server = pairingServer(MockResponse().setResponseCode(201).setBody(claimResponse())) diff --git a/apps/android/app/src/test/kotlin/com/hopa/app/link/session/SessionFixtures.kt b/apps/android/app/src/test/kotlin/com/hopa/app/link/session/SessionFixtures.kt index f59e3afb4..1b6764eb5 100644 --- a/apps/android/app/src/test/kotlin/com/hopa/app/link/session/SessionFixtures.kt +++ b/apps/android/app/src/test/kotlin/com/hopa/app/link/session/SessionFixtures.kt @@ -64,6 +64,7 @@ internal object SessionFixtures { override var onTask: (suspend (BackendEnvelope) -> Unit)? = null override var onApproval: (suspend (BackendEnvelope) -> Unit)? = null override var onDiagnostic: (suspend (BackendEnvelope) -> Unit)? = null + override var onSyncChanged: (suspend (Long) -> Unit)? = null @Volatile var started = false diff --git a/apps/android/feature/chat/src/main/kotlin/com/hopa/feature/chat/ChatDependencies.kt b/apps/android/feature/chat/src/main/kotlin/com/hopa/feature/chat/ChatDependencies.kt index cbb0360e2..2a678e675 100644 --- a/apps/android/feature/chat/src/main/kotlin/com/hopa/feature/chat/ChatDependencies.kt +++ b/apps/android/feature/chat/src/main/kotlin/com/hopa/feature/chat/ChatDependencies.kt @@ -15,8 +15,10 @@ import com.hopa.stores.ConversationStore import com.hopa.stores.SettingsRepository import com.hopa.stores.SkillStore import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.emptyFlow /** What the chat screen needs: one turn, the tasks beside it, and the prompt gate. */ interface ChatDependencies { @@ -39,6 +41,12 @@ interface ChatDependencies { /** Pieces of an on-device answer as they are produced; empty for cloud. */ val localTokens: kotlinx.coroutines.flow.Flow + /** + * Thread ids a backend sync changed, or `""` for all. Empty when no + * backend sync is wired, so a build or test without one is unchanged. + */ + val conversationChanges: Flow get() = emptyFlow() + /** Where a graph would go before any screen is read, or null. */ fun graphTarget(goal: String): com.hopa.decision.graph.GraphTarget? diff --git a/apps/android/feature/chat/src/main/kotlin/com/hopa/feature/chat/ChatViewModel.kt b/apps/android/feature/chat/src/main/kotlin/com/hopa/feature/chat/ChatViewModel.kt index 9c1e2c167..18bddddb6 100644 --- a/apps/android/feature/chat/src/main/kotlin/com/hopa/feature/chat/ChatViewModel.kt +++ b/apps/android/feature/chat/src/main/kotlin/com/hopa/feature/chat/ChatViewModel.kt @@ -87,6 +87,22 @@ class ChatViewModel @Inject constructor( } } } + // A pass elsewhere changed the store. Refresh the open thread and the + // list, but never touch `busy`: a sync must not clear a running turn. + viewModelScope.launch { + container.conversationChanges.collect { threadId -> + val currentId = _state.value.current?.id + val all = container.conversations.all() + val refreshed = if (threadId.isBlank() || threadId == currentId) { + all.firstOrNull { it.id == currentId } + } else { + null + } + _state.update { state -> + state.copy(conversations = all, current = refreshed ?: state.current) + } + } + } } fun onInput(value: String) { diff --git a/apps/android/feature/conversations/src/main/kotlin/com/hopa/feature/conversations/ConversationsDependencies.kt b/apps/android/feature/conversations/src/main/kotlin/com/hopa/feature/conversations/ConversationsDependencies.kt index c8e2e3d1e..4781dcec9 100644 --- a/apps/android/feature/conversations/src/main/kotlin/com/hopa/feature/conversations/ConversationsDependencies.kt +++ b/apps/android/feature/conversations/src/main/kotlin/com/hopa/feature/conversations/ConversationsDependencies.kt @@ -2,7 +2,9 @@ package com.hopa.feature.conversations import com.hopa.stores.ConversationStore import com.hopa.stores.SettingsRepository +import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.emptyFlow /** What the chats sheet and its ViewModel read and write. */ interface ConversationsDependencies { @@ -12,4 +14,10 @@ interface ConversationsDependencies { /** Null when no bridge is configured; throws when the sync itself fails. */ suspend fun syncChats(): ChatSyncOutcome? + + /** + * Thread ids a backend sync changed, or `""` for all. Empty when no + * backend sync is wired, so a test double is unchanged. + */ + val conversationChanges: Flow get() = emptyFlow() } diff --git a/apps/android/feature/conversations/src/main/kotlin/com/hopa/feature/conversations/ConversationsViewModel.kt b/apps/android/feature/conversations/src/main/kotlin/com/hopa/feature/conversations/ConversationsViewModel.kt index cde5b2eb0..57540bfa5 100644 --- a/apps/android/feature/conversations/src/main/kotlin/com/hopa/feature/conversations/ConversationsViewModel.kt +++ b/apps/android/feature/conversations/src/main/kotlin/com/hopa/feature/conversations/ConversationsViewModel.kt @@ -22,6 +22,11 @@ class ConversationsViewModel @Inject constructor( init { load() + // A backend pass changed some thread; the sheet's next open must not + // show the copy it loaded at launch. + viewModelScope.launch { + container.conversationChanges.collect { load() } + } } fun onQuery(value: String) { From 60dd0eb321834bfedf81573ff85027a090344470 Mon Sep 17 00:00:00 2001 From: aharonamir Date: Mon, 30 Nov 2026 01:17:24 +0200 Subject: [PATCH 16/58] Bound the sync backlog and key titles by content One turn larger than the 64 KiB op cap used to make every pass fail, because the engine seals the whole backlog up front and the thread stays in allWithDeleted() after a delete. The backlog now measures each payload against the codec cap minus PayloadCipher's 12-byte IV and 16-byte tag, skips the turns that cannot fit, keeps them local and reports them as Done.skippedTurns. A title op id now hashes the title content instead of the thread timestamp, so a message on one device cannot republish a stale title as a new op, and a tombstone id is keyed by the deletion time. Title merge follows server seq order; an op this device wrote is inert when it comes back on the next pull, so its own echo cannot undo a newer rename, and a title this phone has not pushed yet is held until it is. The cursor and the change announcement now happen as soon as the pull finishes, so a failed push no longer hides applied turns. Part of #32. --- .../com/hopa/app/link/sync/BackendSync.kt | 267 +++++++++++++----- .../com/hopa/app/link/sync/SyncOutcome.kt | 8 +- .../com/hopa/app/link/sync/BackendSyncTest.kt | 149 +++++++++- .../com/hopa/app/link/sync/SyncFixtures.kt | 122 +++++--- .../hopa/backend/sync/client/SyncBacklog.kt | 40 ++- .../backend/sync/client/SyncBacklogTest.kt | 43 ++- 6 files changed, 499 insertions(+), 130 deletions(-) diff --git a/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/BackendSync.kt b/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/BackendSync.kt index bb10d770b..38093cd8d 100644 --- a/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/BackendSync.kt +++ b/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/BackendSync.kt @@ -1,6 +1,10 @@ package com.hopa.app.link.sync import com.hopa.backend.pairing.BackendUrls +import com.hopa.backend.sync.client.PullAnswer +import com.hopa.backend.sync.client.PushAnswer +import com.hopa.backend.sync.client.RemoteSyncOp +import com.hopa.backend.sync.client.SealedOp import com.hopa.backend.sync.client.SyncBacklog import com.hopa.backend.sync.client.SyncCodec import com.hopa.backend.sync.client.SyncCursor @@ -29,6 +33,7 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext +import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put @@ -40,6 +45,13 @@ import kotlinx.serialization.json.put * rotation takes effect on the next pass without a restart. The engine owns * the wire rules; this class only maps [ConversationStore] rows to its target, * builds the local backlog and serializes passes. + * + * Two local rules matter here: + * - A title this phone changed since the last finished pass is *pending*: a + * pulled title for that thread is ignored until our own op is pushed, so a + * peer's older op cannot silently undo a rename this phone has not sent yet. + * - An op this device wrote is inert when it comes back on a later pull (see + * [OwnOpsIgnored]); the cursor still moves past it. */ internal class BackendSync( private val settings: SettingsRepository, @@ -60,9 +72,20 @@ internal class BackendSync( private var running = false private var pending: Job? = null + /** Titles in the store when the last pass finished; a difference is a local rename. */ + private var syncedTitles: Map? = null + /** One pull-then-push pass; waits for a pass already in flight. */ suspend fun syncNow(): SyncOutcome = withContext(Dispatchers.IO) { - pass.withLock { runPass() } + try { + pass.withLock { runPass() } + } catch (cancelled: CancellationException) { + throw cancelled + } catch (_: Exception) { + // A store read, a bad tag or a transport reset: the code is all the + // caller gets, because a message could quote plaintext. + SyncOutcome.Failed("E_SYNC") + } } /** Begin coalescing local and remote triggers into passes. */ @@ -128,10 +151,11 @@ internal class BackendSync( val startedAt = current.backendSyncSeq val cursor = PassCursor(startedAt) - val target = StoreTarget(store) + val pendingTitles = pendingTitles(store.allWithDeleted().associate { it.id to it.title }) + val target = StoreTarget(store, pendingTitles) val baseUrl = BackendUrls.httpBase(current.backendUrl) val engine = SyncEngine( - http = http, + http = OwnOpsIgnored(http, current.backendDeviceId), codec = SyncCodec(key), target = target, cursor = cursor, @@ -139,93 +163,136 @@ internal class BackendSync( baseUrl = { baseUrl }, ) - return try { - val report = engine.pull() - val pushed = push(engine, current, target) - // Only a finished pass may move the cursor: a refused call must be - // retried from the same seq, and replaying is idempotent. - if (cursor.read() != startedAt) { - settings.setBackendSyncSeq(cursor.read()) - } - publish(target.changed) - SyncOutcome.Done(report.applied, pushed) + val report = try { + engine.pull() } catch (cancelled: CancellationException) { throw cancelled } catch (refused: SyncHttpException) { - SyncOutcome.Failed( - refused.code?.takeIf { it.isNotBlank() } - ?: if (refused.status == UNAUTHORIZED) "E_AUTH" else "E_SYNC", - ) + return SyncOutcome.Failed(failureCode(refused)) } catch (_: Exception) { - // A bad tag, a transport reset or an unparsable body: the code is all - // the caller gets, because a message could quote plaintext. - SyncOutcome.Failed("E_SYNC") + return SyncOutcome.Failed("E_SYNC") } - } - /** - * Sends the whole local set. Ids are deterministic, so the server dedupes a - * turn this phone received from a peer and a title it already holds. - */ - private suspend fun push(engine: SyncEngine, current: AppSettings, target: StoreTarget): Int { - val drafts = backlog(current) - if (drafts.isEmpty()) { - return 0 + // The pull is done: persist its cursor and announce what it applied even + // when the push below fails, or the next pass would see duplicates and + // never announce those turns. + if (cursor.read() != startedAt) { + settings.setBackendSyncSeq(cursor.read()) } - val answer = engine.push(drafts) - val threads = drafts.associate { it.opId to it.threadId } - for (ack in answer.accepted) { - if (!ack.duplicate) { - threads[ack.opId]?.let(target::markChanged) + publish(target.changed) + + val backlog = try { + backlog(current) + } catch (cancelled: CancellationException) { + throw cancelled + } catch (_: Exception) { + return SyncOutcome.Failed("E_SYNC") + } + var pushed = 0 + if (backlog.drafts.isNotEmpty()) { + val answer = try { + engine.push(backlog.drafts) + } catch (cancelled: CancellationException) { + throw cancelled + } catch (refused: SyncHttpException) { + return SyncOutcome.Failed(failureCode(refused)) + } catch (_: Exception) { + return SyncOutcome.Failed("E_SYNC") } + pushed = answer.accepted.count { !it.duplicate } } - return answer.accepted.count { !it.duplicate } + // Only a finished pass knows the server holds these titles. + syncedTitles = backlog.titles + return SyncOutcome.Done(report.applied, pushed, backlog.skippedTurns) + } + + /** + * Threads whose title differs from the one the last finished pass saw. A + * brand-new process has no baseline, so nothing is pending: a rename made + * while the app was closed cannot be told from a peer's. + */ + private fun pendingTitles(local: Map): Set { + val seen = syncedTitles ?: return emptySet() + return local.filter { (threadId, title) -> seen[threadId] != title }.keys } - private suspend fun backlog(current: AppSettings): List { + /** + * Sends the whole local set. Ids are deterministic, so the server dedupes a + * turn this phone received from a peer and a title it already holds. + */ + private suspend fun backlog(current: AppSettings): Backlog { val device = current.backendDeviceId val turns = mutableListOf() val threads = mutableListOf() + val titles = mutableMapOf() + var skippedTurns = 0 for (thread in store.allWithDeleted()) { + titles[thread.id] = thread.title for (message in thread.messages) { if (message.role !in ROLES || message.text.isBlank()) { continue } val at = message.timestamp.takeIf { it > 0 } ?: now() + val payload = buildJsonObject { + put("role", message.role) + put("text", message.text) + put("at", at) + } + // One op the codec refuses would fail the whole pass, and the + // thread stays in allWithDeleted() even when deleted. Keep this + // turn local and let the rest of the log through. + if (!fits(payload)) { + skippedTurns += 1 + continue + } turns += SyncDraft( opId = message.id, kind = SyncKind.TURN_APPEND, threadId = thread.id, turnId = message.id, - payload = buildJsonObject { - put("role", message.role) - put("text", message.text) - put("at", at) - }, + payload = payload, clientAt = at, ) } - // The title id is keyed by the local revision: a rename or a delete - // writes a newer `updatedAt`, so the next pass is a new op. - val at = thread.updatedAt - threads += SyncDraft( - opId = SyncBacklog.titleOpId(thread.id, at, device), - kind = SyncKind.THREAD_UPSERT, - threadId = thread.id, - turnId = null, - payload = buildJsonObject { - if (thread.deletedAt == 0L) { - put("title", thread.title) - } - put("deletedAt", thread.deletedAt) - put("clientAt", at) - }, - clientAt = at, - ) + // A tombstone is keyed by its deletion time; a live title by its + // content, so a message cannot republish a stale one. + val opId = if (thread.deletedAt > 0L) { + SyncBacklog.tombstoneOpId(thread.id, thread.deletedAt, device) + } else { + SyncBacklog.titleOpId(thread.id, thread.title, device) + } + val payload = buildJsonObject { + if (thread.deletedAt == 0L) { + put("title", thread.title) + } + put("deletedAt", thread.deletedAt) + put("clientAt", thread.updatedAt) + } + if (fits(payload)) { + threads += SyncDraft( + opId = opId, + kind = SyncKind.THREAD_UPSERT, + threadId = thread.id, + turnId = null, + payload = payload, + clientAt = thread.updatedAt, + ) + } } - return threads + SyncBacklog.orderTurns(turns) + return Backlog( + drafts = threads + SyncBacklog.orderTurns(turns), + skippedTurns = skippedTurns, + titles = titles, + ) } + private fun fits(payload: JsonObject): Boolean = + payload.toString().toByteArray(Charsets.UTF_8).size <= MAX_PLAINTEXT_BYTES + + private fun failureCode(refused: SyncHttpException): String = + refused.code?.takeIf { it.isNotBlank() } + ?: if (refused.status == UNAUTHORIZED) "E_AUTH" else "E_SYNC" + private fun publish(changed: Set) { val id = when { changed.isEmpty() -> return @@ -239,7 +306,13 @@ internal class BackendSync( Base64.getDecoder().decode(stored) }.getOrNull()?.takeIf { it.size == CONTENT_KEY_BYTES } - /** The cursor for one pass, persisted to settings only after it succeeds. */ + private class Backlog( + val drafts: List, + val skippedTurns: Int, + val titles: Map, + ) + + /** The cursor for one pass, persisted to settings only after it finishes. */ private class PassCursor(initial: Long) : SyncCursor { private var seq = initial @@ -255,16 +328,15 @@ internal class BackendSync( * in a pass, so a long thread list is not re-read per op; each applied op * updates the snapshot so a later op in the same pass sees it. */ - private class StoreTarget(private val store: ConversationStore) : SyncTarget { + private class StoreTarget( + private val store: ConversationStore, + private val pendingTitles: Set, + ) : SyncTarget { private var rows: Map? = null private val changedIds = linkedSetOf() val changed: Set get() = changedIds - fun markChanged(threadId: String) { - changedIds += threadId - } - private suspend fun rows(): Map = rows ?: store.allWithDeleted().associateBy { it.id }.also { rows = it } @@ -304,7 +376,7 @@ internal class BackendSync( updatedAt = at, ), ) - markChanged(threadId) + changedIds += threadId } override suspend fun applyThread( @@ -315,13 +387,12 @@ internal class BackendSync( ) { val existing = rows()[threadId] val gone = maxOf(existing?.deletedAt ?: 0, deletedAt) > 0 - // A rename is a revision: an op older than what this phone already - // has must not undo a newer local title (our own last push is such - // an op when it comes back on the next pull). - val stale = existing != null && clientAt < existing.updatedAt + // Server seq order decides a title, except for a rename this phone + // has not pushed yet: that local title stays until our op is sent. + val localPending = threadId in pendingTitles // A tombstone is final: a later title must not resurrect the thread, // and a deleted thread never takes a title. - val nextTitle = if (gone || stale) "" else title.orEmpty() + val nextTitle = if (gone || localPending) "" else title.orEmpty() store.adopt( Conversation( id = threadId, @@ -342,10 +413,10 @@ internal class BackendSync( remember(row) val changed = existing == null || row.deletedAt != existing.deletedAt || - (!gone && !stale && title != null && title != existing.title) || + (!gone && !localPending && title != null && title != existing.title) || clientAt > existing.updatedAt if (changed) { - markChanged(threadId) + changedIds += threadId } } } @@ -360,6 +431,15 @@ internal class BackendSync( /** `""` asks a collector to reload everything, not one thread. */ const val ALL_THREADS = "" + /** + * PayloadCipher's blob is `IV(12) || ciphertext || tag(16)`, so a + * plaintext may be this much smaller than the codec's ciphertext cap. + */ + const val SEAL_OVERHEAD_BYTES = 12 + 16 + + /** The most plaintext one op may seal; one byte more makes seal() throw. */ + const val MAX_PLAINTEXT_BYTES = SyncCodec.MAX_CIPHERTEXT_BYTES - SEAL_OVERHEAD_BYTES + const val CONTENT_KEY_BYTES = 32 const val UNAUTHORIZED = 401 const val NEW_CHAT = "New chat" @@ -367,3 +447,44 @@ internal class BackendSync( val ROLES = setOf("user", "assistant") } } + +/** + * Hides this device's own ops from the engine: their seq is still applied to the + * cursor (kind `null` is a recorded skip), but their content is never merged + * again. Re-applying our own older title on the next pull was how a rename could + * be undone by its own echo. + */ +private class OwnOpsIgnored( + private val inner: SyncHttp, + private val device: String, +) : SyncHttp { + override suspend fun push(token: String, baseUrl: String, ops: List): PushAnswer = + inner.push(token, baseUrl, ops) + + override suspend fun pull(token: String, baseUrl: String, after: Long, limit: Int): PullAnswer { + val page = inner.pull(token, baseUrl, after, limit) + if (page.ops.none { it.fromDevice == device }) { + return page + } + return page.copy( + ops = page.ops.map { op -> + if (op.fromDevice != device) { + op + } else { + RemoteSyncOp( + seq = op.seq, + opId = op.opId, + kind = null, + threadId = op.threadId, + turnId = op.turnId, + fromDevice = op.fromDevice, + memberId = op.memberId, + clientAt = op.clientAt, + at = op.at, + ciphertext = op.ciphertext, + ) + } + }, + ) + } +} diff --git a/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/SyncOutcome.kt b/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/SyncOutcome.kt index 76b0f4413..0a2c646e4 100644 --- a/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/SyncOutcome.kt +++ b/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/SyncOutcome.kt @@ -5,8 +5,12 @@ sealed interface SyncOutcome { /** No gateway identity or no household key: nothing was sent. */ data object SignedOut : SyncOutcome - /** [applied] remote ops reached the store; [pushed] local ops were new to the server. */ - data class Done(val applied: Int, val pushed: Int) : SyncOutcome + /** + * [applied] remote ops reached the store; [pushed] local ops were new to the + * server; [skippedTurns] local turns were too large for one op and stayed + * on this phone. + */ + data class Done(val applied: Int, val pushed: Int, val skippedTurns: Int = 0) : SyncOutcome /** * The pass stopped. [code] is the server's safe error code (`E_AUTH`, ...) diff --git a/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/BackendSyncTest.kt b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/BackendSyncTest.kt index 9d1839ab8..54827d072 100644 --- a/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/BackendSyncTest.kt +++ b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/BackendSyncTest.kt @@ -240,8 +240,153 @@ class BackendSyncTest { assertTrue(server.pushBatches.isEmpty()) } - private fun signedIn(): FakeSyncSettings = FakeSyncSettings( - device = "d1", + @Test + fun `an oversize turn is skipped and the rest of the backlog still syncs`() = runBlocking { + val store = InMemoryConversationStore() + val chat = store.create() + store.append(chat.id, ChatMessage("m-short-1", "user", "one", 10)) + store.append(chat.id, ChatMessage("m-big", "user", "x".repeat(70_000), 11)) + store.append(chat.id, ChatMessage("m-short-2", "assistant", "two", 12)) + val server = FakeSyncServer() + val sync = BackendSync(settings = signedIn(), store = store, http = server, scope = this) + + val first = sync.syncNow() as SyncOutcome.Done + + assertEquals(1, first.skippedTurns) + assertTrue(server.pushBatches.single().any { it.opId == "m-short-1" }) + assertTrue(server.pushBatches.single().any { it.opId == "m-short-2" }) + assertFalse(server.pushBatches.single().any { it.opId == "m-big" }) + assertEquals(1, server.opCount("m-short-1")) + assertEquals(0, server.opCount("m-big")) + // The oversized turn stays local instead of failing every pass. + assertEquals(3, store.allWithDeleted().single { it.id == chat.id }.messages.size) + + val second = sync.syncNow() as SyncOutcome.Done + assertEquals(1, second.skippedTurns) + assertEquals(2, server.pushBatches.size) + assertEquals(0, server.opCount("m-big")) + } + + @Test + fun `a message on another device does not revert a rename`() = runBlocking { + val server = FakeSyncServer() + server.seed( + SyncKind.THREAD_UPSERT, + "c-1", + null, + threadPayload("Trip", deletedAt = 0, clientAt = 500), + opId = "t-0", + clientAt = 500, + ) + server.seed( + SyncKind.TURN_APPEND, + "c-1", + "m-1", + turnPayload("user", "hello", 1_000), + opId = "m-1", + clientAt = 1_000, + ) + val storeA = InMemoryConversationStore() + val storeB = InMemoryConversationStore() + val syncA = BackendSync( + settings = signedIn("dA"), + store = storeA, + http = server.forDevice("dA"), + scope = this, + ) + val syncB = BackendSync( + settings = signedIn("dB"), + store = storeB, + http = server.forDevice("dB"), + scope = this, + ) + // Both start caught up, so the rename below has no older op in flight. + syncA.syncNow() + syncB.syncNow() + + // A renames during a quiet log. + storeA.rename("c-1", "Mine") + syncA.syncNow() + // B appends a message; its clock is well ahead of the rename. + storeB.append("c-1", ChatMessage("m-2", "user", "more", 9_000)) + syncB.syncNow() + + syncA.syncNow() + syncA.syncNow() + + assertEquals("Mine", storeA.allWithDeleted().single { it.id == "c-1" }.title) + assertEquals("Mine", server.titleOf("c-1")) + } + + @Test + fun `two devices renaming concurrently converge on the later op`() = runBlocking { + val server = FakeSyncServer() + server.seed( + SyncKind.TURN_APPEND, + "c-1", + "m-1", + turnPayload("user", "hello", 500), + opId = "m-1", + clientAt = 500, + ) + val storeA = InMemoryConversationStore() + val storeB = InMemoryConversationStore() + val syncA = BackendSync( + settings = signedIn("dA"), + store = storeA, + http = server.forDevice("dA"), + scope = this, + ) + val syncB = BackendSync( + settings = signedIn("dB"), + store = storeB, + http = server.forDevice("dB"), + scope = this, + ) + syncA.syncNow() + syncB.syncNow() + + storeA.rename("c-1", "Alpha") + syncA.syncNow() + storeB.rename("c-1", "Beta") + syncB.syncNow() + + syncA.syncNow() + // B's rename was pushed after A's, so the last op wins on both sides. + assertEquals("Beta", server.titleOf("c-1")) + assertEquals("Beta", storeA.allWithDeleted().single { it.id == "c-1" }.title) + assertEquals("Beta", storeB.allWithDeleted().single { it.id == "c-1" }.title) + } + + @Test + fun `a failed push still announces what the pull applied`() = runBlocking { + val store = InMemoryConversationStore() + val server = FakeSyncServer() + server.seed( + SyncKind.TURN_APPEND, + "c-1", + "m-1", + turnPayload("user", "hello", 10), + opId = "m-1", + clientAt = 10, + ) + server.pushFailure = SyncHttpException("E_NET", "offline", 503) + val settings = signedIn() + val sync = BackendSync(settings = settings, store = store, http = server, scope = this) + val seen = mutableListOf() + val collector = launch(Dispatchers.Unconfined) { sync.changes.collect { seen += it } } + + val outcome = sync.syncNow() + collector.cancel() + + assertEquals(SyncOutcome.Failed("E_NET"), outcome) + assertEquals(listOf("c-1"), seen) + assertEquals(1, settings.current.backendSyncSeq) + assertEquals("hello", store.allWithDeleted().single { it.id == "c-1" }.messages.single().text) + } + + private fun signedIn(device: String = "d1"): FakeSyncSettings = FakeSyncSettings( + device = device, access = "a1", contentKey = TEST_CONTENT_KEY_BASE64, ) diff --git a/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/SyncFixtures.kt b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/SyncFixtures.kt index 85056268f..a18af5d0a 100644 --- a/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/SyncFixtures.kt +++ b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/SyncFixtures.kt @@ -105,15 +105,63 @@ internal class FakeSyncSettings( } } +/** The op log one household shares; a view per device stamps who pushed. */ +internal class SharedSyncLog(key: ByteArray = TEST_CONTENT_KEY) { + private val codec = SyncCodec(key) + val stored = mutableListOf() + private val byId = mutableMapOf() + + fun seal(draft: SyncDraft): String = codec.seal(draft).ct + + fun open(op: RemoteSyncOp): JsonObject = codec.open(op) + + fun append( + opId: String, + kind: SyncKind, + threadId: String, + turnId: String?, + clientAt: Long, + ct: String, + fromDevice: String, + ): RemoteSyncOp { + val seq = (stored.maxOfOrNull { it.seq } ?: 0L) + 1 + val row = RemoteSyncOp( + seq = seq, + opId = opId, + kind = kind, + threadId = threadId, + turnId = turnId, + fromDevice = fromDevice, + memberId = "member-1", + clientAt = clientAt, + at = "2026-11-20T00:00:00Z", + ciphertext = Base64.getDecoder().decode(ct), + ) + stored += row + byId[opId] = row + return row + } + + fun find(opId: String): RemoteSyncOp? = byId[opId] +} + /** * The sync routes in memory: it stores ops by op id, assigns seqs in push order * and dedupes a repeated id the way the server does. Seeded ops stand in for a - * peer's writes. + * peer's writes. [forDevice] makes a second phone or PC view over the same log. */ -internal class FakeSyncServer(key: ByteArray = TEST_CONTENT_KEY) : SyncHttp { - private val codec = SyncCodec(key) - private val stored = mutableListOf() - private val byId = mutableMapOf() +internal class FakeSyncServer private constructor( + private val log: SharedSyncLog, + private val device: String, +) : SyncHttp { + constructor( + key: ByteArray = TEST_CONTENT_KEY, + device: String = "d1", + log: SharedSyncLog = SharedSyncLog(key), + ) : this(log, device) + + /** A view of the same log that stamps pushes with another device's id. */ + fun forDevice(device: String): FakeSyncServer = FakeSyncServer(log, device) /** Every push body, in call order. */ val pushBatches = mutableListOf>() @@ -127,22 +175,26 @@ internal class FakeSyncServer(key: ByteArray = TEST_CONTENT_KEY) : SyncHttp { var pulls = 0 private set + /** Fails both routes, as a refused session would. */ var failure: SyncHttpException? = null + /** Fails only the push, so the pull's work is still visible. */ + var pushFailure: SyncHttpException? = null + override suspend fun push(token: String, baseUrl: String, ops: List): PushAnswer { - failure?.let { throw it } + (pushFailure ?: failure)?.let { throw it } baseUrls += baseUrl pushBatches += ops val accepted = ops.map { op -> - val duplicate = byId[op.opId] + val duplicate = log.find(op.opId) if (duplicate != null) { PushAck(op.opId, duplicate.seq, duplicate = true) } else { - val row = store(op.opId, op.kind, op.threadId, op.turnId, op.clientAt, op.ct, "phone") + val row = log.append(op.opId, op.kind, op.threadId, op.turnId, op.clientAt, op.ct, device) PushAck(op.opId, row.seq, duplicate = false) } } - return PushAnswer(head = stored.size.toLong(), accepted = accepted) + return PushAnswer(head = log.stored.size.toLong(), accepted = accepted) } override suspend fun pull(token: String, baseUrl: String, after: Long, limit: Int): PullAnswer { @@ -150,12 +202,12 @@ internal class FakeSyncServer(key: ByteArray = TEST_CONTENT_KEY) : SyncHttp { pulls += 1 baseUrls += baseUrl pullAfters += after - val page = stored.filter { it.seq > after }.sortedBy { it.seq }.take(limit) + val page = log.stored.filter { it.seq > after }.sortedBy { it.seq }.take(limit) val last = page.lastOrNull()?.seq ?: after return PullAnswer( ops = page, - hasMore = stored.any { it.seq > last }, - head = stored.size.toLong(), + hasMore = log.stored.any { it.seq > last }, + head = log.stored.size.toLong(), ) } @@ -167,44 +219,22 @@ internal class FakeSyncServer(key: ByteArray = TEST_CONTENT_KEY) : SyncHttp { opId: String, clientAt: Long, fromDevice: String = "pc", - ): RemoteSyncOp { - val sealed = codec.seal(SyncDraft(opId, kind, threadId, turnId, payload, clientAt)) - return store(opId, kind, threadId, turnId, clientAt, sealed.ct, fromDevice) - } + ): RemoteSyncOp = log.append( + opId, + kind, + threadId, + turnId, + clientAt, + log.seal(SyncDraft(opId, kind, threadId, turnId, payload, clientAt)), + fromDevice, + ) - fun opCount(opId: String): Int = stored.count { it.opId == opId } + fun opCount(opId: String): Int = log.stored.count { it.opId == opId } /** The title the last accepted thread upsert left for [threadId]. */ - fun titleOf(threadId: String): String? = stored.asReversed() + fun titleOf(threadId: String): String? = log.stored.asReversed() .firstOrNull { it.kind == SyncKind.THREAD_UPSERT && it.threadId == threadId } - ?.let { op -> codec.open(op)["title"]?.jsonPrimitive?.content } - - private fun store( - opId: String, - kind: SyncKind, - threadId: String, - turnId: String?, - clientAt: Long, - ct: String, - fromDevice: String, - ): RemoteSyncOp { - val seq = (stored.maxOfOrNull { it.seq } ?: 0L) + 1 - val row = RemoteSyncOp( - seq = seq, - opId = opId, - kind = kind, - threadId = threadId, - turnId = turnId, - fromDevice = fromDevice, - memberId = "member-1", - clientAt = clientAt, - at = "2026-11-20T00:00:00Z", - ciphertext = Base64.getDecoder().decode(ct), - ) - stored += row - byId[opId] = row - return row - } + ?.let { op -> log.open(op)["title"]?.jsonPrimitive?.content } } /** The `turn.append` payload the engine expects. */ diff --git a/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncBacklog.kt b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncBacklog.kt index 45587dcea..6635f5209 100644 --- a/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncBacklog.kt +++ b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncBacklog.kt @@ -1,5 +1,6 @@ package com.hopa.backend.sync.client +import java.security.MessageDigest import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.longOrNull @@ -10,8 +11,43 @@ object SyncBacklog { compareBy({ it.threadId }, { atOf(it) }, { it.turnId.orEmpty() }), ) - /** Deterministic id for a title push: `"::"`. */ - fun titleOpId(threadId: String, updatedAt: Long, deviceId: String): String = "$threadId:$updatedAt:$deviceId" + /** + * Deterministic id for a title push: `":title::"`, + * where `` is the first 8 bytes of SHA-256 over the UTF-8 title, as 16 + * lowercase hex characters. + * + * The thread's timestamp is deliberately not part of the id. A message bumps + * `updatedAt` on every device that sees it, so a timestamp-keyed id would let + * a device republish its stale title as a new op after someone else renamed. + * With this id the same title stays one op per device, and only a rename + * produces a new one. Two devices renaming to the same title still get two + * ids (the device id differs); the later seq wins harmlessly. + */ + fun titleOpId(threadId: String, title: String, deviceId: String): String = + "$threadId:$TITLE:${hash(title)}:$deviceId" + + /** + * Deterministic id for a tombstone: `":deleted::"`. + * A deletion is final in v0, so the deletion time is what identifies it; a + * thread deleted again (were restore ever added) would need a newer time. + */ + fun tombstoneOpId(threadId: String, deletedAt: Long, deviceId: String): String = + "$threadId:$DELETED:$deletedAt:$deviceId" + + private fun hash(value: String): String { + val digest = MessageDigest.getInstance("SHA-256").digest(value.toByteArray(Charsets.UTF_8)) + val out = StringBuilder(HASH_CHARS) + for (index in 0 until HASH_CHARS / 2) { + val byte = digest[index].toInt() and 0xFF + out.append(HEX[byte ushr 4]).append(HEX[byte and 0x0F]) + } + return out.toString() + } private fun atOf(draft: SyncDraft): Long = draft.payload["at"]?.jsonPrimitive?.longOrNull ?: draft.clientAt + + private const val TITLE = "title" + private const val DELETED = "deleted" + private const val HASH_CHARS = 16 + private const val HEX = "0123456789abcdef" } diff --git a/core/backend/src/test/kotlin/com/hopa/backend/sync/client/SyncBacklogTest.kt b/core/backend/src/test/kotlin/com/hopa/backend/sync/client/SyncBacklogTest.kt index f5c99a892..20c4ffac0 100644 --- a/core/backend/src/test/kotlin/com/hopa/backend/sync/client/SyncBacklogTest.kt +++ b/core/backend/src/test/kotlin/com/hopa/backend/sync/client/SyncBacklogTest.kt @@ -4,6 +4,7 @@ import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotEquals +import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test class SyncBacklogTest { @@ -46,15 +47,47 @@ class SyncBacklogTest { } @Test - fun `a title op id names the thread, its update time and the device`() { - assertEquals("c-1:1733000000000:phone", SyncBacklog.titleOpId("c-1", 1733000000000, "phone")) + fun `a title op id names the thread, a content hash and the device`() { + val id = SyncBacklog.titleOpId("c-1", "Groceries", "phone") + + assertTrue(id.startsWith("c-1:title:")) + assertTrue(id.endsWith(":phone")) + val hash = id.removePrefix("c-1:title:").removeSuffix(":phone") + assertEquals(16, hash.length) + assertTrue(hash.all { it in "0123456789abcdef" }, "hash was $hash") + } + + @Test + fun `the same title keeps the same id however the thread changes`() { + // A message bumps the thread's timestamp; the title op must not change. + assertEquals( + SyncBacklog.titleOpId("c-1", "Groceries", "phone"), + SyncBacklog.titleOpId("c-1", "Groceries", "phone"), + ) + } + + @Test + fun `a rename produces a new id`() { + assertNotEquals( + SyncBacklog.titleOpId("c-1", "Groceries", "phone"), + SyncBacklog.titleOpId("c-1", "Groceries 2", "phone"), + ) + } + + @Test + fun `two devices pushing the same title get different ids`() { + assertNotEquals( + SyncBacklog.titleOpId("c-1", "Groceries", "phone"), + SyncBacklog.titleOpId("c-1", "Groceries", "laptop"), + ) } @Test - fun `two devices renaming in the same millisecond get different ids`() { + fun `a tombstone id is keyed by the deletion time`() { + assertEquals("c-1:deleted:99:phone", SyncBacklog.tombstoneOpId("c-1", 99, "phone")) assertNotEquals( - SyncBacklog.titleOpId("c-1", 1733000000000, "phone"), - SyncBacklog.titleOpId("c-1", 1733000000000, "laptop"), + SyncBacklog.tombstoneOpId("c-1", 99, "phone"), + SyncBacklog.tombstoneOpId("c-1", 100, "phone"), ) } } From b2d3aeb1ffc0f0f66d6a4d2891c7038780679b64 Mon Sep 17 00:00:00 2001 From: aharonamir Date: Mon, 30 Nov 2026 01:17:33 +0200 Subject: [PATCH 17/58] Close and guard chat actions the backend cannot sync A remote tombstone removes the thread from all(), so the open chat used to stay on screen and writable; the view model now clears state.current when the thread it shows is gone, and appending returns early. Undo-turn and undo-delete have no wire op in v0 and could not reach the other devices (restore reuses the tombstone's id), so both are refused in backend mode with a short explanation, through the same SyncOwnership rule the merge uses. The manual sync message now also reports turns that were too large to push. Tests cover the closed chat, both guards (and both controls), and the skip message. Part of #32. --- .../kotlin/com/hopa/app/di/AppContainer.kt | 13 +- .../app/feature/chat/ChatSyncViewModelTest.kt | 182 ++++++++++++++++++ .../ConversationsSyncViewModelTest.kt | 105 ++++++++++ .../com/hopa/feature/chat/ChatDependencies.kt | 6 + .../com/hopa/feature/chat/ChatViewModel.kt | 22 ++- .../feature/conversations/ChatSyncOutcome.kt | 4 +- .../ConversationsDependencies.kt | 6 + .../conversations/ConversationsViewModel.kt | 20 +- 8 files changed, 353 insertions(+), 5 deletions(-) create mode 100644 apps/android/app/src/test/kotlin/com/hopa/app/feature/chat/ChatSyncViewModelTest.kt create mode 100644 apps/android/app/src/test/kotlin/com/hopa/feature/conversations/ConversationsSyncViewModelTest.kt diff --git a/apps/android/app/src/main/kotlin/com/hopa/app/di/AppContainer.kt b/apps/android/app/src/main/kotlin/com/hopa/app/di/AppContainer.kt index 61d874679..29a607d7f 100644 --- a/apps/android/app/src/main/kotlin/com/hopa/app/di/AppContainer.kt +++ b/apps/android/app/src/main/kotlin/com/hopa/app/di/AppContainer.kt @@ -682,7 +682,11 @@ class AppContainer @Inject constructor(@ApplicationContext context: Context) : C val engine = backendSync() if (engine != null) { return when (val outcome = engine.syncNow()) { - is SyncOutcome.Done -> ChatSyncOutcome(adopted = outcome.applied, tombstoned = 0) + is SyncOutcome.Done -> ChatSyncOutcome( + adopted = outcome.applied, + tombstoned = 0, + skipped = outcome.skippedTurns, + ) SyncOutcome.SignedOut -> null is SyncOutcome.Failed -> throw IllegalStateException(outcome.code) } @@ -699,6 +703,13 @@ class AppContainer @Inject constructor(@ApplicationContext context: Context) : C internal suspend fun backendSync(): BackendSync? = if (SyncOwnership.owner(settings) == SyncOwner.BACKEND) sync else null + /** + * True while the backend op log owns chat merge: a local undo or restore + * could not reach the other devices, so the screens refuse that action. + */ + override suspend fun backendOwnsChats(): Boolean = + SyncOwnership.owner(settings) == SyncOwner.BACKEND + /** One pass off the main thread, e.g. when the app comes to the front. */ fun requestSync() { appScope.launch { sync.syncNow() } diff --git a/apps/android/app/src/test/kotlin/com/hopa/app/feature/chat/ChatSyncViewModelTest.kt b/apps/android/app/src/test/kotlin/com/hopa/app/feature/chat/ChatSyncViewModelTest.kt new file mode 100644 index 000000000..ee8eaa1c7 --- /dev/null +++ b/apps/android/app/src/test/kotlin/com/hopa/app/feature/chat/ChatSyncViewModelTest.kt @@ -0,0 +1,182 @@ +package com.hopa.app.feature.chat + +import android.content.Context +import com.hopa.agent.turn.TurnOutcome +import com.hopa.agent.turn.TurnRequest +import com.hopa.capabilities.voice.VoiceRecorder +import com.hopa.contracts.approval.ApprovalRequest +import com.hopa.contracts.chat.Attachment +import com.hopa.contracts.chat.ChatMessage +import com.hopa.contracts.chat.Conversation +import com.hopa.contracts.task.TaskItem +import com.hopa.data.store.DbRunHistory +import com.hopa.feature.chat.ChatDependencies +import com.hopa.feature.chat.ChatViewModel +import com.hopa.observation.source.ScreenSourceDevice +import com.hopa.runtime.RunGate +import com.hopa.stores.AppSettings +import com.hopa.stores.ConversationStore +import com.hopa.stores.InMemoryConversationStore +import com.hopa.stores.SettingsRepository +import com.hopa.stores.SkillStore +import com.hopa.app.link.sync.FakeSyncSettings +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.emptyFlow +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test + +@OptIn(ExperimentalCoroutinesApi::class) +class ChatSyncViewModelTest { + private val dispatcher = StandardTestDispatcher() + + @BeforeEach + fun setUp() { + Dispatchers.setMain(dispatcher) + } + + @AfterEach + fun tearDown() { + Dispatchers.resetMain() + } + + @Test + fun `a remote tombstone closes the open chat and blocks a new turn`() = runTest(dispatcher) { + val deps = FakeChatDependencies() + val thread = deps.conversations.create() + deps.conversations.append(thread.id, ChatMessage("m-1", "user", "hi", 1)) + deps.conversations.append(thread.id, ChatMessage("m-2", "assistant", "hello", 2)) + val viewModel = ChatViewModel(deps) + advanceUntilIdle() + assertEquals(thread.id, viewModel.state.value.current?.id) + + deps.conversations.adopt( + Conversation(id = thread.id, title = "", updatedAt = 5, deletedAt = 99), + ) + deps.changes.emit(thread.id) + advanceUntilIdle() + + assertNull(viewModel.state.value.current) + assertEquals(0, viewModel.state.value.conversations.size) + + viewModel.onInput("still there?") + viewModel.send() + advanceUntilIdle() + + // Nothing is appended into a thread a peer deleted. + assertEquals(2, deps.conversations.allWithDeleted().single { it.id == thread.id }.messages.size) + assertNull(viewModel.state.value.error) + } + + @Test + fun `undoing a turn is refused while the backend owns chats`() = runTest(dispatcher) { + val deps = FakeChatDependencies() + val thread = deps.conversations.create() + deps.conversations.append(thread.id, ChatMessage("m-1", "user", "hi", 1)) + deps.conversations.append(thread.id, ChatMessage("m-2", "assistant", "hello", 2)) + deps.backendOwns = true + val viewModel = ChatViewModel(deps) + advanceUntilIdle() + + viewModel.undoLast() + advanceUntilIdle() + + assertEquals(2, deps.conversations.allWithDeleted().single { it.id == thread.id }.messages.size) + assertEquals( + ChatViewModel.UNDO_TURN_WHILE_SYNCED, + viewModel.state.value.error, + ) + } + + @Test + fun `undoing a turn still works without a backend owner`() = runTest(dispatcher) { + val deps = FakeChatDependencies() + val thread = deps.conversations.create() + deps.conversations.append(thread.id, ChatMessage("m-1", "user", "hi", 1)) + deps.conversations.append(thread.id, ChatMessage("m-2", "assistant", "hello", 2)) + val viewModel = ChatViewModel(deps) + advanceUntilIdle() + + viewModel.undoLast() + advanceUntilIdle() + + assertEquals(0, deps.conversations.allWithDeleted().single { it.id == thread.id }.messages.size) + assertNull(viewModel.state.value.error) + } +} + +/** The chat screen's dependencies, with only the fields these tests touch. */ +private class FakeChatDependencies : ChatDependencies { + override val conversations: ConversationStore = InMemoryConversationStore() + override val settings: SettingsRepository = FakeSyncSettings(device = "d1") + override val selectedConversation = MutableStateFlow(null) + override val pendingAttachment = MutableStateFlow(null) + override val pendingNotice = MutableStateFlow(null) + override val pendingGoals = Channel(Channel.UNLIMITED) + override val pendingApproval: StateFlow = MutableStateFlow(null) + override val tasks: StateFlow> = MutableStateFlow(emptyList()) + override val localTokens: Flow = emptyFlow() + + val changes = MutableSharedFlow(extraBufferCapacity = 8) + override val conversationChanges: Flow = changes + + /** What SyncOwnership would answer for this phone. */ + var backendOwns = false + + override suspend fun backendOwnsChats(): Boolean = backendOwns + + override val context: Context get() = error("unused in this test") + override val runHistory: DbRunHistory get() = error("unused in this test") + override val skills: SkillStore get() = error("unused in this test") + override val runGate: RunGate get() = error("unused in this test") + override val voice: VoiceRecorder get() = error("unused in this test") + override val surfaces: suspend (AppSettings) -> ScreenSourceDevice + get() = error("unused in this test") + + override fun graphTarget(goal: String): com.hopa.decision.graph.GraphTarget? = null + override fun resolveApproval(allow: Boolean) = Unit + override fun canStartTask(): Boolean = false + override fun startTask(goal: String) = Unit + override fun dismissTask(id: String) = Unit + override suspend fun deleteAttachment(attachment: Attachment) = Unit + override fun planRequest(goal: String, runId: String, traceId: String): TurnRequest = + error("unused in this test") + + override suspend fun request( + goal: String, + device: ScreenSourceDevice, + settings: AppSettings, + runId: String, + traceId: String, + history: List, + ): TurnRequest = error("unused in this test") + + override suspend fun runTurn(request: TurnRequest, isCancelled: () -> Boolean): TurnOutcome = + error("unused in this test") + + override suspend fun speak(text: String): Boolean = false + override suspend fun transcribe(wav: ByteArray): String? = null + override fun useGate(trustedApps: Collection, autonomous: Boolean) = Unit + override fun useDecisions(mode: String, shadow: Boolean) = Unit + override fun stopTurn() = Unit + override suspend fun onDeviceModelName(): String = "" + override fun bringToFront() = Unit + override fun releaseSurfaces() = Unit + override fun isForeground(): Boolean = true + override fun postAnswer(text: String) = Unit + override fun startRunService() = Unit + override fun stopRunService() = Unit +} diff --git a/apps/android/app/src/test/kotlin/com/hopa/feature/conversations/ConversationsSyncViewModelTest.kt b/apps/android/app/src/test/kotlin/com/hopa/feature/conversations/ConversationsSyncViewModelTest.kt new file mode 100644 index 000000000..bfe849aae --- /dev/null +++ b/apps/android/app/src/test/kotlin/com/hopa/feature/conversations/ConversationsSyncViewModelTest.kt @@ -0,0 +1,105 @@ +package com.hopa.feature.conversations + +import com.hopa.contracts.chat.ChatMessage +import com.hopa.stores.ConversationStore +import com.hopa.stores.InMemoryConversationStore +import com.hopa.stores.SettingsRepository +import com.hopa.app.link.sync.FakeSyncSettings +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.emptyFlow +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.resetMain +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.test.setMain +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test + +@OptIn(ExperimentalCoroutinesApi::class) +class ConversationsSyncViewModelTest { + private val dispatcher = StandardTestDispatcher() + + @BeforeEach + fun setUp() { + Dispatchers.setMain(dispatcher) + } + + @AfterEach + fun tearDown() { + Dispatchers.resetMain() + } + + @Test + fun `undoing a delete is refused while the backend owns chats`() = runTest(dispatcher) { + val deps = FakeConversationsDependencies() + val thread = deps.conversations.create() + deps.conversations.append(thread.id, ChatMessage("m-1", "user", "hi", 1)) + deps.backendOwns = true + val viewModel = ConversationsViewModel(deps) + advanceUntilIdle() + + viewModel.delete(thread.id) + advanceUntilIdle() + assertTrue(viewModel.state.value.conversations.isEmpty()) + + viewModel.undoDelete() + advanceUntilIdle() + + // The tombstone is final: a v0 restore could not reach the other devices. + assertTrue(deps.conversations.allWithDeleted().single { it.id == thread.id }.deletedAt > 0) + assertEquals( + ConversationsViewModel.UNDO_DELETE_WHILE_SYNCED, + viewModel.state.value.message, + ) + } + + @Test + fun `a sync with an oversize turn says so`() = runTest(dispatcher) { + val deps = FakeConversationsDependencies() + deps.outcome = ChatSyncOutcome(adopted = 2, tombstoned = 0, skipped = 1) + val viewModel = ConversationsViewModel(deps) + advanceUntilIdle() + + viewModel.sync() + advanceUntilIdle() + + assertEquals("Synced: 2 chats, 1 too long to sync", viewModel.state.value.message) + } + + @Test + fun `undoing a delete still works without a backend owner`() = runTest(dispatcher) { + val deps = FakeConversationsDependencies() + val thread = deps.conversations.create() + deps.conversations.append(thread.id, ChatMessage("m-1", "user", "hi", 1)) + val viewModel = ConversationsViewModel(deps) + advanceUntilIdle() + + viewModel.delete(thread.id) + advanceUntilIdle() + viewModel.undoDelete() + advanceUntilIdle() + + assertEquals(0, deps.conversations.allWithDeleted().single { it.id == thread.id }.deletedAt) + } +} + +private class FakeConversationsDependencies : ConversationsDependencies { + override val conversations: ConversationStore = InMemoryConversationStore() + override val settings: SettingsRepository = FakeSyncSettings(device = "d1") + override val selectedConversation = MutableStateFlow(null) + override val conversationChanges: Flow = emptyFlow() + + var backendOwns = false + + override suspend fun backendOwnsChats(): Boolean = backendOwns + + var outcome: ChatSyncOutcome? = null + + override suspend fun syncChats(): ChatSyncOutcome? = outcome +} diff --git a/apps/android/feature/chat/src/main/kotlin/com/hopa/feature/chat/ChatDependencies.kt b/apps/android/feature/chat/src/main/kotlin/com/hopa/feature/chat/ChatDependencies.kt index 2a678e675..d9b51ea68 100644 --- a/apps/android/feature/chat/src/main/kotlin/com/hopa/feature/chat/ChatDependencies.kt +++ b/apps/android/feature/chat/src/main/kotlin/com/hopa/feature/chat/ChatDependencies.kt @@ -47,6 +47,12 @@ interface ChatDependencies { */ val conversationChanges: Flow get() = emptyFlow() + /** + * True while a backend op log owns chat merge. A local undo cannot reach + * the other devices then, so the action is refused with an explanation. + */ + suspend fun backendOwnsChats(): Boolean = false + /** Where a graph would go before any screen is read, or null. */ fun graphTarget(goal: String): com.hopa.decision.graph.GraphTarget? diff --git a/apps/android/feature/chat/src/main/kotlin/com/hopa/feature/chat/ChatViewModel.kt b/apps/android/feature/chat/src/main/kotlin/com/hopa/feature/chat/ChatViewModel.kt index 18bddddb6..48a22753b 100644 --- a/apps/android/feature/chat/src/main/kotlin/com/hopa/feature/chat/ChatViewModel.kt +++ b/apps/android/feature/chat/src/main/kotlin/com/hopa/feature/chat/ChatViewModel.kt @@ -93,13 +93,19 @@ class ChatViewModel @Inject constructor( container.conversationChanges.collect { threadId -> val currentId = _state.value.current?.id val all = container.conversations.all() - val refreshed = if (threadId.isBlank() || threadId == currentId) { + val touchesCurrent = threadId.isBlank() || threadId == currentId + val refreshed = if (touchesCurrent) { all.firstOrNull { it.id == currentId } } else { null } _state.update { state -> - state.copy(conversations = all, current = refreshed ?: state.current) + state.copy( + conversations = all, + // A remote tombstone removes the thread from `all()`; the + // open chat must close rather than stay writable. + current = if (touchesCurrent) refreshed else state.current, + ) } } } @@ -214,6 +220,12 @@ class ChatViewModel @Inject constructor( return } viewModelScope.launch { + // v0 has no turn.delete op: a local undo would be re-delivered by + // the next pull, so the action is refused while the log owns chats. + if (container.backendOwnsChats()) { + _state.update { it.copy(error = UNDO_TURN_WHILE_SYNCED) } + return@launch + } container.conversations.dropLastExchange(conversation.id) val all = container.conversations.all() _state.update { @@ -697,4 +709,10 @@ class ChatViewModel @Inject constructor( ) } } + + companion object { + /** Shown when undo-turn is refused because the backend log owns chats. */ + const val UNDO_TURN_WHILE_SYNCED = + "Undo is unavailable while chats sync across your devices" + } } diff --git a/apps/android/feature/conversations/src/main/kotlin/com/hopa/feature/conversations/ChatSyncOutcome.kt b/apps/android/feature/conversations/src/main/kotlin/com/hopa/feature/conversations/ChatSyncOutcome.kt index d79f96435..171cc4a4f 100644 --- a/apps/android/feature/conversations/src/main/kotlin/com/hopa/feature/conversations/ChatSyncOutcome.kt +++ b/apps/android/feature/conversations/src/main/kotlin/com/hopa/feature/conversations/ChatSyncOutcome.kt @@ -1,7 +1,9 @@ package com.hopa.feature.conversations -/** What a bridge chat sync moved, without the transport types. */ +/** What a chat sync moved, without the transport types. */ data class ChatSyncOutcome( val adopted: Int, val tombstoned: Int, + /** Turns too large for one op; they stay on this phone. */ + val skipped: Int = 0, ) diff --git a/apps/android/feature/conversations/src/main/kotlin/com/hopa/feature/conversations/ConversationsDependencies.kt b/apps/android/feature/conversations/src/main/kotlin/com/hopa/feature/conversations/ConversationsDependencies.kt index 4781dcec9..34dfc10f5 100644 --- a/apps/android/feature/conversations/src/main/kotlin/com/hopa/feature/conversations/ConversationsDependencies.kt +++ b/apps/android/feature/conversations/src/main/kotlin/com/hopa/feature/conversations/ConversationsDependencies.kt @@ -20,4 +20,10 @@ interface ConversationsDependencies { * backend sync is wired, so a test double is unchanged. */ val conversationChanges: Flow get() = emptyFlow() + + /** + * True while a backend op log owns chat merge. A restored tombstone could + * not reach the other devices then, so the action is refused. + */ + suspend fun backendOwnsChats(): Boolean = false } diff --git a/apps/android/feature/conversations/src/main/kotlin/com/hopa/feature/conversations/ConversationsViewModel.kt b/apps/android/feature/conversations/src/main/kotlin/com/hopa/feature/conversations/ConversationsViewModel.kt index 57540bfa5..3c3123d7d 100644 --- a/apps/android/feature/conversations/src/main/kotlin/com/hopa/feature/conversations/ConversationsViewModel.kt +++ b/apps/android/feature/conversations/src/main/kotlin/com/hopa/feature/conversations/ConversationsViewModel.kt @@ -72,6 +72,13 @@ class ConversationsViewModel @Inject constructor( fun undoDelete() { val id = lastDeleted ?: return viewModelScope.launch { + // v0 tombstones are final and restore reuses the tombstone's op id, + // which the server dedupes; a local undo would come back on the next + // pull. Refuse it while the backend log owns chats. + if (container.backendOwnsChats()) { + _state.update { it.copy(message = UNDO_DELETE_WHILE_SYNCED) } + return@launch + } container.conversations.restore(id) lastDeleted = null load() @@ -114,7 +121,12 @@ class ConversationsViewModel @Inject constructor( } else { "" } - "Synced: ${outcome.adopted} chats$deleted" + val skipped = if (outcome.skipped > 0) { + ", ${outcome.skipped} too long to sync" + } else { + "" + } + "Synced: ${outcome.adopted} chats$deleted$skipped" }.getOrElse { error -> "Sync failed: ${error.message}" } load() _state.update { it.copy(syncing = false, message = message) } @@ -141,4 +153,10 @@ class ConversationsViewModel @Inject constructor( } } } + + companion object { + /** Shown when undo-delete is refused because the backend log owns chats. */ + const val UNDO_DELETE_WHILE_SYNCED = + "Deleted chats stay deleted across your devices" + } } From 1a168d0cbe96743aa80f365e1909f8ae6d38f071 Mon Sep 17 00:00:00 2001 From: aharonamir Date: Mon, 30 Nov 2026 01:54:18 +0200 Subject: [PATCH 18/58] Record each thread's last synced title in settings The record is a JSON map threadId -> title next to the sync cursor. It lives in plain settings so it survives a restart: a title is pushed only when the local one differs, and a title the server already holds is never re-sent just because a message bumped the thread's timestamp. Part of #32. --- .../data/store/DataStoreSettingsRepository.kt | 4 ++++ .../hopa/data/store/SettingsDefaultsTest.kt | 18 ++++++++++++++++++ .../main/kotlin/com/hopa/stores/AppSettings.kt | 6 ++++++ .../com/hopa/stores/SettingsRepository.kt | 10 ++++++++++ 4 files changed, 38 insertions(+) diff --git a/apps/android/data/src/main/kotlin/com/hopa/data/store/DataStoreSettingsRepository.kt b/apps/android/data/src/main/kotlin/com/hopa/data/store/DataStoreSettingsRepository.kt index 59930a5ab..d92490d42 100644 --- a/apps/android/data/src/main/kotlin/com/hopa/data/store/DataStoreSettingsRepository.kt +++ b/apps/android/data/src/main/kotlin/com/hopa/data/store/DataStoreSettingsRepository.kt @@ -57,6 +57,7 @@ class DataStoreSettingsRepository( prefs[BACKEND_DEVICE_ID] = next.backendDeviceId prefs[BACKEND_HOUSEHOLD_ID] = next.backendHouseholdId prefs[BACKEND_SYNC_SEQ] = next.backendSyncSeq + prefs[BACKEND_SYNCED_TITLES] = next.backendSyncedTitles prefs[ACCOUNT_SKIPPED] = next.accountSkipped prefs[BACKEND_PHONE] = next.backendPhone } @@ -119,6 +120,7 @@ class DataStoreSettingsRepository( backendDeviceId = "", backendHouseholdId = "", backendSyncSeq = 0, + backendSyncedTitles = "", backendPhone = "", ) } @@ -159,6 +161,7 @@ class DataStoreSettingsRepository( backendDeviceId = prefs[BACKEND_DEVICE_ID] ?: "", backendHouseholdId = prefs[BACKEND_HOUSEHOLD_ID] ?: "", backendSyncSeq = prefs[BACKEND_SYNC_SEQ] ?: 0, + backendSyncedTitles = prefs[BACKEND_SYNCED_TITLES] ?: "", accountSkipped = prefs[ACCOUNT_SKIPPED] ?: false, backendPhone = prefs[BACKEND_PHONE] ?: "", ) @@ -193,6 +196,7 @@ class DataStoreSettingsRepository( val BACKEND_DEVICE_ID = stringPreferencesKey("backend_device_id") val BACKEND_HOUSEHOLD_ID = stringPreferencesKey("backend_household_id") val BACKEND_SYNC_SEQ = longPreferencesKey("backend_sync_seq") + val BACKEND_SYNCED_TITLES = stringPreferencesKey("backend_synced_titles") val ACCOUNT_SKIPPED = booleanPreferencesKey("account_skipped") val BACKEND_PHONE = stringPreferencesKey("backend_phone") const val MODEL_KEY = "model_key" diff --git a/apps/android/data/src/test/kotlin/com/hopa/data/store/SettingsDefaultsTest.kt b/apps/android/data/src/test/kotlin/com/hopa/data/store/SettingsDefaultsTest.kt index fd2c861cf..554166393 100644 --- a/apps/android/data/src/test/kotlin/com/hopa/data/store/SettingsDefaultsTest.kt +++ b/apps/android/data/src/test/kotlin/com/hopa/data/store/SettingsDefaultsTest.kt @@ -44,4 +44,22 @@ class SettingsDefaultsTest { assertEquals(42L, settings.backendSyncSeq) } + + @Test + fun `a fresh settings file knows no synced titles`() { + val settings = DataStoreSettingsRepository.settingsFrom(emptyPreferences()) + + assertEquals("", settings.backendSyncedTitles) + } + + @Test + fun `stored synced titles are read back`() { + val prefs = mutablePreferencesOf( + DataStoreSettingsRepository.BACKEND_SYNCED_TITLES to """{"c-1":"Trip"}""", + ) + + val settings = DataStoreSettingsRepository.settingsFrom(prefs) + + assertEquals("""{"c-1":"Trip"}""", settings.backendSyncedTitles) + } } diff --git a/apps/android/stores/src/main/kotlin/com/hopa/stores/AppSettings.kt b/apps/android/stores/src/main/kotlin/com/hopa/stores/AppSettings.kt index 01fde0d2a..3899bf0d6 100644 --- a/apps/android/stores/src/main/kotlin/com/hopa/stores/AppSettings.kt +++ b/apps/android/stores/src/main/kotlin/com/hopa/stores/AppSettings.kt @@ -77,6 +77,12 @@ data class AppSettings( * holds, which the store dedupes. */ val backendSyncSeq: Long = 0, + /** + * The titles the server is known to hold, as a JSON object + * `{"threadId":"title"}`. It survives a restart, so a title is only pushed + * when the local one differs from this record. + */ + val backendSyncedTitles: String = "", /** * The person chose "use this phone without an account". It wins over the * gateway until a real sign-in clears it, so a reachable gateway cannot diff --git a/apps/android/stores/src/main/kotlin/com/hopa/stores/SettingsRepository.kt b/apps/android/stores/src/main/kotlin/com/hopa/stores/SettingsRepository.kt index 85af3def9..6b64a9277 100644 --- a/apps/android/stores/src/main/kotlin/com/hopa/stores/SettingsRepository.kt +++ b/apps/android/stores/src/main/kotlin/com/hopa/stores/SettingsRepository.kt @@ -1,6 +1,7 @@ package com.hopa.stores import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.first interface SettingsRepository { val settings: Flow @@ -50,6 +51,15 @@ interface SettingsRepository { */ suspend fun setBackendSyncSeq(value: Long) = update { it.copy(backendSyncSeq = value) } + /** + * The titles the server is known to hold, as JSON `{"threadId":"title"}`. + * A title missing here, or different from the local one, is the only reason + * a `thread.upsert` is pushed; it survives a restart. + */ + suspend fun backendSyncedTitles(): String = settings.first().backendSyncedTitles + + suspend fun setBackendSyncedTitles(value: String) = update { it.copy(backendSyncedTitles = value) } + /** * The Ed25519 seed that signs this phone's approval answers (ADR-0032), * base64. Blank until the first answer creates it. A store that cannot From c0bb638461063acd9e60670405a13a58b586037d Mon Sep 17 00:00:00 2001 From: aharonamir Date: Mon, 30 Nov 2026 01:54:26 +0200 Subject: [PATCH 19/58] Push only titles that differ from the last synced record Replaces the content-hash title id and its in-memory pending set. A title op id is keyed by the thread's revision again, so A to B to A is three ops instead of a duplicate of the first; the push decision comes from the persisted record, not the id. A title is recorded when the server acks its op and when a pull applies a remote title, so a retry re-sends the same id, a failed push leaves the record for the retry, and an applied title is not echoed back. A message changes updatedAt but not the title, so it can no longer re-push a stale one. Tests cover A to B to A, a message-only push, a failed push losing to a peer rename, a restart, and the ahead-of-the-rename message case. Part of #32. --- .../com/hopa/app/link/sync/BackendSync.kt | 145 ++++++++----- .../com/hopa/app/link/sync/BackendSyncTest.kt | 198 ++++++++++++++---- .../com/hopa/app/link/sync/SyncFixtures.kt | 6 +- .../hopa/backend/sync/client/SyncBacklog.kt | 37 ++-- .../backend/sync/client/SyncBacklogTest.kt | 34 +-- 5 files changed, 285 insertions(+), 135 deletions(-) diff --git a/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/BackendSync.kt b/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/BackendSync.kt index 38093cd8d..780ea8f76 100644 --- a/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/BackendSync.kt +++ b/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/BackendSync.kt @@ -16,6 +16,7 @@ import com.hopa.backend.sync.client.SyncKind import com.hopa.backend.sync.client.SyncTarget import com.hopa.contracts.chat.ChatMessage import com.hopa.contracts.chat.Conversation +import com.hopa.contracts.json.HopaJson import com.hopa.stores.AppSettings import com.hopa.stores.ConversationStore import com.hopa.stores.SettingsRepository @@ -34,7 +35,10 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.put /** @@ -72,9 +76,6 @@ internal class BackendSync( private var running = false private var pending: Job? = null - /** Titles in the store when the last pass finished; a difference is a local rename. */ - private var syncedTitles: Map? = null - /** One pull-then-push pass; waits for a pass already in flight. */ suspend fun syncNow(): SyncOutcome = withContext(Dispatchers.IO) { try { @@ -151,8 +152,13 @@ internal class BackendSync( val startedAt = current.backendSyncSeq val cursor = PassCursor(startedAt) - val pendingTitles = pendingTitles(store.allWithDeleted().associate { it.id to it.title }) - val target = StoreTarget(store, pendingTitles) + val storedTitles = settings.backendSyncedTitles() + val recordedTitles = decodeTitles(storedTitles) + val target = StoreTarget(store) { threadId, title -> + // A pulled title is already on the server; record it so the next + // pass does not echo it back. + recordedTitles[threadId] = title + } val baseUrl = BackendUrls.httpBase(current.backendUrl) val engine = SyncEngine( http = OwnOpsIgnored(http, current.backendDeviceId), @@ -179,10 +185,11 @@ internal class BackendSync( if (cursor.read() != startedAt) { settings.setBackendSyncSeq(cursor.read()) } + var persistedTitles = persistTitles(recordedTitles, storedTitles) publish(target.changed) val backlog = try { - backlog(current) + backlog(current, recordedTitles) } catch (cancelled: CancellationException) { throw cancelled } catch (_: Exception) { @@ -200,34 +207,57 @@ internal class BackendSync( return SyncOutcome.Failed("E_SYNC") } pushed = answer.accepted.count { !it.duplicate } + // Only an acknowledged op proves the server holds the title. A + // duplicate ack means it already did. + for (ack in answer.accepted) { + backlog.titles[ack.opId]?.let { pushedTitle -> + recordedTitles[pushedTitle.threadId] = pushedTitle.title + } + } + persistedTitles = persistTitles(recordedTitles, persistedTitles) } - // Only a finished pass knows the server holds these titles. - syncedTitles = backlog.titles return SyncOutcome.Done(report.applied, pushed, backlog.skippedTurns) } /** - * Threads whose title differs from the one the last finished pass saw. A - * brand-new process has no baseline, so nothing is pending: a rename made - * while the app was closed cannot be told from a peer's. + * Writes the record only when it changed, so a quiet pass does not touch + * settings. A failed push leaves the pushed titles absent: the retry sends + * the same id and the server dedupes it. */ - private fun pendingTitles(local: Map): Set { - val seen = syncedTitles ?: return emptySet() - return local.filter { (threadId, title) -> seen[threadId] != title }.keys + private suspend fun persistTitles(titles: Map, persisted: String): String { + val encoded = encodeTitles(titles) + if (encoded != persisted) { + settings.setBackendSyncedTitles(encoded) + } + return encoded + } + + private fun decodeTitles(stored: String): MutableMap { + if (stored.isBlank()) { + return mutableMapOf() + } + return runCatching { + HopaJson.element.parseToJsonElement(stored).jsonObject + .mapValues { (_, value) -> value.jsonPrimitive.content } + .toMutableMap() + }.getOrDefault(mutableMapOf()) } + private fun encodeTitles(titles: Map): String = + JsonObject(titles.mapValues { (_, title) -> JsonPrimitive(title) }).toString() + /** - * Sends the whole local set. Ids are deterministic, so the server dedupes a - * turn this phone received from a peer and a title it already holds. + * Sends the local set. A title travels only when it differs from the record + * a finished pass or a pull established; a message bumps `updatedAt` but not + * the title, so it cannot re-push a stale one. */ - private suspend fun backlog(current: AppSettings): Backlog { + private suspend fun backlog(current: AppSettings, recordedTitles: Map): Backlog { val device = current.backendDeviceId val turns = mutableListOf() val threads = mutableListOf() - val titles = mutableMapOf() + val titlePushes = mutableMapOf() var skippedTurns = 0 for (thread in store.allWithDeleted()) { - titles[thread.id] = thread.title for (message in thread.messages) { if (message.role !in ROLES || message.text.isBlank()) { continue @@ -254,35 +284,49 @@ internal class BackendSync( clientAt = at, ) } - // A tombstone is keyed by its deletion time; a live title by its - // content, so a message cannot republish a stale one. - val opId = if (thread.deletedAt > 0L) { - SyncBacklog.tombstoneOpId(thread.id, thread.deletedAt, device) - } else { - SyncBacklog.titleOpId(thread.id, thread.title, device) - } - val payload = buildJsonObject { - if (thread.deletedAt == 0L) { + if (thread.deletedAt > 0L) { + // Tombstones stay keyed by the deletion time and travel every + // pass; the server dedupes them. + val payload = buildJsonObject { + put("deletedAt", thread.deletedAt) + put("clientAt", thread.updatedAt) + } + if (fits(payload)) { + threads += SyncDraft( + opId = SyncBacklog.tombstoneOpId(thread.id, thread.deletedAt, device), + kind = SyncKind.THREAD_UPSERT, + threadId = thread.id, + turnId = null, + payload = payload, + clientAt = thread.updatedAt, + ) + } + } else if (recordedTitles[thread.id] != thread.title) { + // Only a new or edited title travels; a message leaves the title + // record equal, so it cannot republish a stale one. + val payload = buildJsonObject { put("title", thread.title) + put("deletedAt", 0) + put("clientAt", thread.updatedAt) + } + if (fits(payload)) { + val opId = SyncBacklog.titleOpId(thread.id, thread.updatedAt, device) + threads += SyncDraft( + opId = opId, + kind = SyncKind.THREAD_UPSERT, + threadId = thread.id, + turnId = null, + payload = payload, + clientAt = thread.updatedAt, + ) + titlePushes[opId] = TitlePush(thread.id, thread.title) } - put("deletedAt", thread.deletedAt) - put("clientAt", thread.updatedAt) - } - if (fits(payload)) { - threads += SyncDraft( - opId = opId, - kind = SyncKind.THREAD_UPSERT, - threadId = thread.id, - turnId = null, - payload = payload, - clientAt = thread.updatedAt, - ) } } return Backlog( drafts = threads + SyncBacklog.orderTurns(turns), skippedTurns = skippedTurns, - titles = titles, + titles = titlePushes, ) } @@ -309,9 +353,12 @@ internal class BackendSync( private class Backlog( val drafts: List, val skippedTurns: Int, - val titles: Map, + /** Title pushes by op id, recorded once the server acks them. */ + val titles: Map, ) + private class TitlePush(val threadId: String, val title: String) + /** The cursor for one pass, persisted to settings only after it finishes. */ private class PassCursor(initial: Long) : SyncCursor { private var seq = initial @@ -330,7 +377,7 @@ internal class BackendSync( */ private class StoreTarget( private val store: ConversationStore, - private val pendingTitles: Set, + private val onRemoteTitle: (threadId: String, title: String) -> Unit, ) : SyncTarget { private var rows: Map? = null private val changedIds = linkedSetOf() @@ -387,12 +434,9 @@ internal class BackendSync( ) { val existing = rows()[threadId] val gone = maxOf(existing?.deletedAt ?: 0, deletedAt) > 0 - // Server seq order decides a title, except for a rename this phone - // has not pushed yet: that local title stays until our op is sent. - val localPending = threadId in pendingTitles // A tombstone is final: a later title must not resurrect the thread, // and a deleted thread never takes a title. - val nextTitle = if (gone || localPending) "" else title.orEmpty() + val nextTitle = if (gone) "" else title.orEmpty() store.adopt( Conversation( id = threadId, @@ -411,9 +455,14 @@ internal class BackendSync( archivedAt = existing?.archivedAt ?: 0, ) remember(row) + if (!gone && title != null) { + // The pull already applied it; record it so the next pass does + // not treat the local title as an unsent edit. + onRemoteTitle(threadId, row.title) + } val changed = existing == null || row.deletedAt != existing.deletedAt || - (!gone && !localPending && title != null && title != existing.title) || + (!gone && title != null && title != existing.title) || clientAt > existing.updatedAt if (changed) { changedIds += threadId diff --git a/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/BackendSyncTest.kt b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/BackendSyncTest.kt index 54827d072..85e6bdbce 100644 --- a/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/BackendSyncTest.kt +++ b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/BackendSyncTest.kt @@ -10,6 +10,7 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNotEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test @@ -269,57 +270,179 @@ class BackendSyncTest { @Test fun `a message on another device does not revert a rename`() = runBlocking { - val server = FakeSyncServer() + // B holds the old title and a message stamped ahead of the peer's + // rename; it appends before it pulls, as a device with a fast clock would. + val store = InMemoryConversationStore() + store.adopt( + Conversation( + id = "c-1", + title = "Trip", + messages = listOf(ChatMessage("m-1", "user", "hello", 1)), + updatedAt = 1, + ), + ) + val server = FakeSyncServer(device = "dB") + val settings = signedIn("dB") + val sync = BackendSync(settings = settings, store = store, http = server, scope = this) + sync.syncNow() + + val ahead = System.currentTimeMillis() + 86_400_000L + store.append("c-1", ChatMessage("m-2", "user", "later", ahead)) server.seed( SyncKind.THREAD_UPSERT, "c-1", null, - threadPayload("Trip", deletedAt = 0, clientAt = 500), - opId = "t-0", - clientAt = 500, + threadPayload("Mine", deletedAt = 0, clientAt = 1), + opId = "peer-title", + clientAt = 1, ) - server.seed( - SyncKind.TURN_APPEND, - "c-1", - "m-1", - turnPayload("user", "hello", 1_000), - opId = "m-1", - clientAt = 1_000, + + sync.syncNow() + + assertEquals("Mine", store.allWithDeleted().single { it.id == "c-1" }.title) + assertEquals("Mine", server.titleOf("c-1")) + } + + @Test + fun `renaming back to an earlier title still propagates`() = runBlocking { + val store = InMemoryConversationStore() + store.adopt( + Conversation( + id = "c-1", + title = "A", + messages = listOf(ChatMessage("m-1", "user", "hi", 1)), + updatedAt = 1, + ), ) - val storeA = InMemoryConversationStore() - val storeB = InMemoryConversationStore() - val syncA = BackendSync( - settings = signedIn("dA"), - store = storeA, - http = server.forDevice("dA"), + val server = FakeSyncServer(device = "dA") + val peerStore = InMemoryConversationStore() + val sync = BackendSync(settings = signedIn("dA"), store = store, http = server, scope = this) + val peer = BackendSync( + settings = signedIn("dPeer"), + store = peerStore, + http = server.forDevice("dPeer"), scope = this, ) - val syncB = BackendSync( - settings = signedIn("dB"), - store = storeB, - http = server.forDevice("dB"), - scope = this, + + sync.syncNow() + peer.syncNow() + store.rename("c-1", "B") + sync.syncNow() + peer.syncNow() + store.rename("c-1", "A") + sync.syncNow() + + assertEquals("A", server.titleOf("c-1")) + peer.syncNow() + assertEquals("A", peerStore.allWithDeleted().single { it.id == "c-1" }.title) + + // The third title push is a new op, not the first one deduped. + assertEquals(3, server.pushBatches.size) + val first = server.pushBatches[0].first { it.kind == SyncKind.THREAD_UPSERT } + val third = server.pushBatches[2].first { it.kind == SyncKind.THREAD_UPSERT } + assertNotEquals(first.opId, third.opId) + assertEquals(1, server.opCount(third.opId)) + } + + @Test + fun `a message does not push a title`() = runBlocking { + val store = InMemoryConversationStore() + store.adopt( + Conversation( + id = "c-1", + title = "Trip", + messages = listOf(ChatMessage("m-1", "user", "hi", 1)), + updatedAt = 1, + ), ) - // Both start caught up, so the rename below has no older op in flight. - syncA.syncNow() - syncB.syncNow() + val server = FakeSyncServer() + val sync = BackendSync(settings = signedIn(), store = store, http = server, scope = this) + sync.syncNow() - // A renames during a quiet log. - storeA.rename("c-1", "Mine") - syncA.syncNow() - // B appends a message; its clock is well ahead of the rename. - storeB.append("c-1", ChatMessage("m-2", "user", "more", 9_000)) - syncB.syncNow() + store.append("c-1", ChatMessage("m-2", "assistant", "hello", 2)) + val second = sync.syncNow() as SyncOutcome.Done - syncA.syncNow() - syncA.syncNow() + assertEquals(1, second.pushed) + assertEquals(2, server.pushBatches.size) + assertEquals(0, server.pushBatches[1].count { it.kind == SyncKind.THREAD_UPSERT }) + assertTrue(server.pushBatches[1].any { it.opId == "m-2" }) + } - assertEquals("Mine", storeA.allWithDeleted().single { it.id == "c-1" }.title) - assertEquals("Mine", server.titleOf("c-1")) + @Test + fun `a failed push does not revert a peer rename`() = runBlocking { + val store = InMemoryConversationStore() + store.adopt( + Conversation( + id = "c-1", + title = "Old", + messages = listOf(ChatMessage("m-1", "user", "hi", 1)), + updatedAt = 1, + ), + ) + val server = FakeSyncServer() + val sync = BackendSync(settings = signedIn(), store = store, http = server, scope = this) + sync.syncNow() + + // A local rename whose push never confirms. + store.rename("c-1", "Mine") + server.pushFailure = SyncHttpException("E_NET", "offline", 503) + assertEquals(SyncOutcome.Failed("E_NET"), sync.syncNow()) + server.pushFailure = null + + server.seed( + SyncKind.THREAD_UPSERT, + "c-1", + null, + threadPayload("Peer", deletedAt = 0, clientAt = 50), + opId = "peer-title", + clientAt = 50, + fromDevice = "peer", + ) + sync.syncNow() + + // The peer's rename wins; our unconfirmed title is not pushed back. + assertEquals("Peer", store.allWithDeleted().single { it.id == "c-1" }.title) + assertEquals("Peer", server.titleOf("c-1")) } @Test - fun `two devices renaming concurrently converge on the later op`() = runBlocking { + fun `a restart does not echo a peer rename back`() = runBlocking { + val store = InMemoryConversationStore() + store.adopt( + Conversation( + id = "c-1", + title = "Old", + messages = listOf(ChatMessage("m-1", "user", "hi", 1)), + updatedAt = 1, + ), + ) + val server = FakeSyncServer() + val settings = signedIn() + BackendSync(settings = settings, store = store, http = server, scope = this).syncNow() + + server.seed( + SyncKind.THREAD_UPSERT, + "c-1", + null, + threadPayload("Peer", deletedAt = 0, clientAt = 50), + opId = "peer-title", + clientAt = 50, + fromDevice = "peer", + ) + // A new process, same settings and store: the last-synced record must + // survive, so the applied title is not pushed back. + val restarted = BackendSync(settings = settings, store = store, http = server, scope = this) + restarted.syncNow() + + assertEquals("Peer", store.allWithDeleted().single { it.id == "c-1" }.title) + assertEquals( + 0, + server.pushBatches.last().count { it.kind == SyncKind.THREAD_UPSERT }, + ) + } + + @Test + fun `a rename pushed after a peer's rename wins`() = runBlocking { val server = FakeSyncServer() server.seed( SyncKind.TURN_APPEND, @@ -348,11 +471,12 @@ class BackendSyncTest { storeA.rename("c-1", "Alpha") syncA.syncNow() + // B sees Alpha, then renames on top of it. + syncB.syncNow() storeB.rename("c-1", "Beta") syncB.syncNow() syncA.syncNow() - // B's rename was pushed after A's, so the last op wins on both sides. assertEquals("Beta", server.titleOf("c-1")) assertEquals("Beta", storeA.allWithDeleted().single { it.id == "c-1" }.title) assertEquals("Beta", storeB.allWithDeleted().single { it.id == "c-1" }.title) diff --git a/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/SyncFixtures.kt b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/SyncFixtures.kt index a18af5d0a..5c11e7dfa 100644 --- a/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/SyncFixtures.kt +++ b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/SyncFixtures.kt @@ -101,7 +101,11 @@ internal class FakeSyncSettings( refreshToken = "" privateKey = "" content = "" - state.value = state.value.copy(backendDeviceId = "", backendSyncSeq = 0) + state.value = state.value.copy( + backendDeviceId = "", + backendSyncSeq = 0, + backendSyncedTitles = "", + ) } } diff --git a/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncBacklog.kt b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncBacklog.kt index 6635f5209..5d7c552d5 100644 --- a/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncBacklog.kt +++ b/core/backend/src/main/kotlin/com/hopa/backend/sync/client/SyncBacklog.kt @@ -1,6 +1,5 @@ package com.hopa.backend.sync.client -import java.security.MessageDigest import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.longOrNull @@ -12,19 +11,20 @@ object SyncBacklog { ) /** - * Deterministic id for a title push: `":title::"`, - * where `` is the first 8 bytes of SHA-256 over the UTF-8 title, as 16 - * lowercase hex characters. + * Deterministic id for a title push: `"::"`. * - * The thread's timestamp is deliberately not part of the id. A message bumps - * `updatedAt` on every device that sees it, so a timestamp-keyed id would let - * a device republish its stale title as a new op after someone else renamed. - * With this id the same title stays one op per device, and only a rename - * produces a new one. Two devices renaming to the same title still get two - * ids (the device id differs); the later seq wins harmlessly. + * [updatedAt] is the thread's revision, which a rename or a delete bumps, so + * renaming A→B→A produces three distinct ids: the server must not dedupe the + * third one against the first. It is deliberately not the title content, at + * the cost that two edits ending on the same string at the same revision + * (which the store prevents) would collide. + * + * The caller decides whether a title needs pushing at all: a title already + * recorded as synced must not be sent again just because a message bumped + * `updatedAt`. */ - fun titleOpId(threadId: String, title: String, deviceId: String): String = - "$threadId:$TITLE:${hash(title)}:$deviceId" + fun titleOpId(threadId: String, updatedAt: Long, deviceId: String): String = + "$threadId:$updatedAt:$deviceId" /** * Deterministic id for a tombstone: `":deleted::"`. @@ -34,20 +34,7 @@ object SyncBacklog { fun tombstoneOpId(threadId: String, deletedAt: Long, deviceId: String): String = "$threadId:$DELETED:$deletedAt:$deviceId" - private fun hash(value: String): String { - val digest = MessageDigest.getInstance("SHA-256").digest(value.toByteArray(Charsets.UTF_8)) - val out = StringBuilder(HASH_CHARS) - for (index in 0 until HASH_CHARS / 2) { - val byte = digest[index].toInt() and 0xFF - out.append(HEX[byte ushr 4]).append(HEX[byte and 0x0F]) - } - return out.toString() - } - private fun atOf(draft: SyncDraft): Long = draft.payload["at"]?.jsonPrimitive?.longOrNull ?: draft.clientAt - private const val TITLE = "title" private const val DELETED = "deleted" - private const val HASH_CHARS = 16 - private const val HEX = "0123456789abcdef" } diff --git a/core/backend/src/test/kotlin/com/hopa/backend/sync/client/SyncBacklogTest.kt b/core/backend/src/test/kotlin/com/hopa/backend/sync/client/SyncBacklogTest.kt index 20c4ffac0..1e21816fd 100644 --- a/core/backend/src/test/kotlin/com/hopa/backend/sync/client/SyncBacklogTest.kt +++ b/core/backend/src/test/kotlin/com/hopa/backend/sync/client/SyncBacklogTest.kt @@ -4,7 +4,6 @@ import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotEquals -import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test class SyncBacklogTest { @@ -47,38 +46,25 @@ class SyncBacklogTest { } @Test - fun `a title op id names the thread, a content hash and the device`() { - val id = SyncBacklog.titleOpId("c-1", "Groceries", "phone") - - assertTrue(id.startsWith("c-1:title:")) - assertTrue(id.endsWith(":phone")) - val hash = id.removePrefix("c-1:title:").removeSuffix(":phone") - assertEquals(16, hash.length) - assertTrue(hash.all { it in "0123456789abcdef" }, "hash was $hash") - } - - @Test - fun `the same title keeps the same id however the thread changes`() { - // A message bumps the thread's timestamp; the title op must not change. - assertEquals( - SyncBacklog.titleOpId("c-1", "Groceries", "phone"), - SyncBacklog.titleOpId("c-1", "Groceries", "phone"), - ) + fun `a title op id names the thread, its revision and the device`() { + assertEquals("c-1:1733000000000:phone", SyncBacklog.titleOpId("c-1", 1733000000000, "phone")) } @Test - fun `a rename produces a new id`() { + fun `a rename back to an earlier title gets a new id`() { + // A→B→A: the third edit has a newer revision, so the server cannot + // dedupe it against the first push. assertNotEquals( - SyncBacklog.titleOpId("c-1", "Groceries", "phone"), - SyncBacklog.titleOpId("c-1", "Groceries 2", "phone"), + SyncBacklog.titleOpId("c-1", 1733000000000, "phone"), + SyncBacklog.titleOpId("c-1", 1733000000002, "phone"), ) } @Test - fun `two devices pushing the same title get different ids`() { + fun `two devices renaming in the same millisecond get different ids`() { assertNotEquals( - SyncBacklog.titleOpId("c-1", "Groceries", "phone"), - SyncBacklog.titleOpId("c-1", "Groceries", "laptop"), + SyncBacklog.titleOpId("c-1", 1733000000000, "phone"), + SyncBacklog.titleOpId("c-1", 1733000000000, "laptop"), ) } From c372135b4489ba308b51fd4b71491cedea92c1f7 Mon Sep 17 00:00:00 2001 From: aharonamir Date: Mon, 30 Nov 2026 02:30:38 +0200 Subject: [PATCH 20/58] Merge remote chat ops into the Windows store ChatStore.mergeRemote creates an unknown thread, dedupes a message by id, keeps messages in timestamp order and applies a title only when it is non-blank, with a tombstone that is final. allWithDeleted exposes the rows sync needs, and every store method is synchronized now that a background pass and the stdin loop share it. Tests cover create, dedupe, out-of-order insert, last-writer-wins titles, the tombstone and the tombstone-aware listing. Part of #32. --- .../com/hopa/sidecar/store/ChatStore.kt | 72 ++++++++++++++++ .../com/hopa/sidecar/store/ChatStoreTest.kt | 85 +++++++++++++++++++ 2 files changed, 157 insertions(+) diff --git a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/store/ChatStore.kt b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/store/ChatStore.kt index d3cde0442..73ebd7bb5 100644 --- a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/store/ChatStore.kt +++ b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/store/ChatStore.kt @@ -19,6 +19,7 @@ class ChatStore(path: Path) { } private var conversations: MutableList = load() + @Synchronized fun list(includeArchived: Boolean = false): List = conversations .filter { it.deletedAt == 0L && (includeArchived || it.archivedAt == 0L) } @@ -27,8 +28,17 @@ class ChatStore(path: Path) { .thenByDescending { it.updatedAt }, ) + /** + * Every row, tombstones included. Sync needs them to dedupe a turn for a + * deleted thread and to push the tombstone itself. + */ + @Synchronized + fun allWithDeleted(): List = conversations.toList() + + @Synchronized fun get(id: String): Conversation? = conversations.firstOrNull { it.id == id } + @Synchronized fun create(): Conversation { val now = System.currentTimeMillis() val conversation = Conversation(id = "c-${UUID.randomUUID()}", title = "New chat", updatedAt = now) @@ -37,6 +47,7 @@ class ChatStore(path: Path) { return conversation } + @Synchronized fun append( conversationId: String, role: String, @@ -72,6 +83,7 @@ class ChatStore(path: Path) { return updated } + @Synchronized fun rename(conversationId: String, title: String): Conversation? { val index = conversations.indexOfFirst { it.id == conversationId } if (index < 0) { @@ -83,6 +95,7 @@ class ChatStore(path: Path) { return updated } + @Synchronized fun delete(conversationId: String): Boolean { val index = conversations.indexOfFirst { it.id == conversationId } if (index < 0) { @@ -96,6 +109,7 @@ class ChatStore(path: Path) { return true } + @Synchronized fun setPinned(conversationId: String, pinned: Boolean): Conversation? { val index = conversations.indexOfFirst { it.id == conversationId } if (index < 0) { @@ -107,6 +121,7 @@ class ChatStore(path: Path) { return updated } + @Synchronized fun setArchived(conversationId: String, archived: Boolean): Conversation? { val index = conversations.indexOfFirst { it.id == conversationId } if (index < 0) { @@ -121,6 +136,7 @@ class ChatStore(path: Path) { return updated } + @Synchronized fun search(query: String): List { val needle = query.trim() if (needle.isEmpty()) { @@ -132,6 +148,54 @@ class ChatStore(path: Path) { } } + /** + * Applies one remote thread or turn, in server `seq` order, so arrival is the + * last-writer-wins order for a title. + * + * The store owns the rules that need local state: a message is deduped by id + * and kept in `timestamp` order (a backfill or an out-of-order peer still + * lands chronologically), a blank or absent title keeps the stored one, and a + * tombstone is final — a later title never revives the row. + */ + @Synchronized + fun mergeRemote( + conversationId: String, + title: String?, + deletedAt: Long, + updatedAt: Long, + message: ChatMessage?, + ): Conversation? { + val index = conversations.indexOfFirst { it.id == conversationId } + val existing = conversations.getOrNull(index) + val tombstoned = maxOf(existing?.deletedAt ?: 0L, deletedAt) > 0L + val nextTitle = when { + tombstoned -> existing?.title ?: NEW_CHAT + !title.isNullOrBlank() -> title.trim().take(MAX_TITLE_LENGTH) + else -> existing?.title ?: NEW_CHAT + } + val messages = existing?.messages.orEmpty().toMutableList() + if (message != null && messages.none { it.id == message.id }) { + messages.add(message) + messages.sortWith(compareBy({ it.timestamp }, { it.id })) + } + val merged = Conversation( + id = conversationId, + title = nextTitle, + messages = messages, + updatedAt = maxOf(existing?.updatedAt ?: 0L, updatedAt), + deletedAt = maxOf(existing?.deletedAt ?: 0L, deletedAt), + pinned = existing?.pinned ?: false, + archivedAt = existing?.archivedAt ?: 0L, + ) + if (index < 0) { + conversations.add(merged) + } else { + conversations[index] = merged + } + save() + return merged + } + private fun load(): MutableList { if (!Files.exists(file)) { return mutableListOf() @@ -148,4 +212,12 @@ class ChatStore(path: Path) { Files.writeString(file, json.encodeToString(ListSerializer(Conversation.serializer()), conversations)) } } + + private companion object { + /** The placeholder title of a fresh chat; a blank remote title keeps it. */ + const val NEW_CHAT = "New chat" + + /** The same cap `rename` applies, so a remote title cannot grow a row. */ + const val MAX_TITLE_LENGTH = 80 + } } diff --git a/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/store/ChatStoreTest.kt b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/store/ChatStoreTest.kt index 6c9efdea0..5233f4bbe 100644 --- a/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/store/ChatStoreTest.kt +++ b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/store/ChatStoreTest.kt @@ -1,7 +1,11 @@ package com.hopa.sidecar.store +import com.hopa.contracts.chat.ChatMessage import java.nio.file.Files import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test class ChatStoreTest { @@ -76,4 +80,85 @@ class ChatStoreTest { assertEquals(true, store.delete(conversation.id)) assertEquals(0, ChatStore(path).list().size) } + + @Test + fun merge_remote_creates_an_unknown_thread() { + val directory = Files.createTempDirectory("hopa-chat-merge-create") + val path = directory.resolve("conversations.json") + val store = ChatStore(path) + + val created = store.mergeRemote("c-1", "Trip", deletedAt = 0, updatedAt = 42, message = null) + + assertEquals("c-1", created?.id) + assertEquals("Trip", created?.title) + assertEquals(42L, created?.updatedAt) + assertEquals(0, created?.messages?.size) + assertEquals("Trip", ChatStore(path).get("c-1")?.title) + + val untitled = store.mergeRemote("c-2", " ", deletedAt = 0, updatedAt = 7, message = null) + assertEquals("New chat", untitled?.title) + } + + @Test + fun merge_remote_dedupes_a_message_id() { + val directory = Files.createTempDirectory("hopa-chat-merge-dedupe") + val store = ChatStore(directory.resolve("conversations.json")) + val message = ChatMessage("m-1", "user", "hello", 10) + + store.mergeRemote("c-1", null, deletedAt = 0, updatedAt = 10, message = message) + val merged = store.mergeRemote("c-1", null, deletedAt = 0, updatedAt = 11, message = message) + + assertEquals(1, merged?.messages?.size) + assertEquals("hello", merged?.messages?.single()?.text) + } + + @Test + fun merge_remote_inserts_by_timestamp_with_id_as_the_tie_break() { + val directory = Files.createTempDirectory("hopa-chat-merge-order") + val path = directory.resolve("conversations.json") + val store = ChatStore(path) + + store.mergeRemote("c-1", null, 0, 30, ChatMessage("m-b", "user", "second", 20)) + store.mergeRemote("c-1", null, 0, 10, ChatMessage("m-a", "assistant", "third", 20)) + val merged = store.mergeRemote("c-1", null, 0, 5, ChatMessage("m-0", "user", "first", 3)) + + assertEquals( + listOf("m-0", "m-a", "m-b"), + merged?.messages?.map { it.id }, + ) + assertEquals(listOf("m-0", "m-a", "m-b"), ChatStore(path).get("c-1")?.messages?.map { it.id }) + } + + @Test + fun merge_remote_keeps_the_last_title_and_ignores_a_blank_one() { + val directory = Files.createTempDirectory("hopa-chat-merge-title") + val store = ChatStore(directory.resolve("conversations.json")) + + store.mergeRemote("c-1", "First", 0, 10, ChatMessage("m-1", "user", "hi", 1)) + assertEquals("First", store.mergeRemote("c-1", "", 0, 20, null)?.title) + assertEquals("Second", store.mergeRemote("c-1", "Second", 0, 30, null)?.title) + assertEquals("Second", store.mergeRemote("c-1", null, 0, 40, null)?.title) + } + + @Test + fun merge_remote_never_lifts_a_tombstone_or_lets_a_title_revive_it() { + val directory = Files.createTempDirectory("hopa-chat-merge-deleted") + val path = directory.resolve("conversations.json") + val store = ChatStore(path) + + store.mergeRemote("c-1", "Live", 0, 10, ChatMessage("m-1", "user", "hi", 1)) + val deleted = store.mergeRemote("c-1", null, deletedAt = 99, updatedAt = 20, message = null) + assertEquals(99L, deleted?.deletedAt) + assertEquals("Live", deleted?.title) + + val revived = store.mergeRemote("c-1", "Back", deletedAt = 0, updatedAt = 30, message = null) + assertEquals(99L, revived?.deletedAt) + assertEquals("Live", revived?.title) + assertEquals(30L, revived?.updatedAt) + + assertFalse(store.list().any { it.id == "c-1" }) + assertTrue(store.allWithDeleted().any { it.id == "c-1" }) + assertTrue(ChatStore(path).allWithDeleted().single { it.id == "c-1" }.deletedAt > 0) + assertNull(store.get("missing")) + } } From e6c4d084af3fa1ba62a4ad51a45f8f92962592fd Mon Sep 17 00:00:00 2001 From: aharonamir Date: Mon, 30 Nov 2026 02:30:45 +0200 Subject: [PATCH 21/58] Add the chat.changed frame to the host protocol One unsolicited frame names the thread a sync pass changed and carries no id and no message text. The schema, the golden frame and the family test treat it as a contract family, and the builder test pins the exact shape the window parses. Part of #32. --- .../kotlin/com/hopa/sidecar/protocol/Protocol.kt | 10 ++++++++++ .../hopa/sidecar/protocol/ProtocolFamilyTest.kt | 3 ++- .../hopa/sidecar/protocol/ProtocolGoldenTest.kt | 1 + .../com/hopa/sidecar/protocol/ProtocolTest.kt | 15 +++++++++++++++ spec/protocol/golden.ndjson | 1 + spec/protocol/schema.v1.json | 15 +++++++++++++++ 6 files changed, 44 insertions(+), 1 deletion(-) diff --git a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/protocol/Protocol.kt b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/protocol/Protocol.kt index 304fdeb36..2530cade6 100644 --- a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/protocol/Protocol.kt +++ b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/protocol/Protocol.kt @@ -483,6 +483,16 @@ object Protocol { if (phone != null) put("phone", phone) } + /** + * A sync pass changed one thread (a pulled turn, title or tombstone). An + * unsolicited event: the host reloads the row it is showing. The id is the + * only payload; message text never travels here. + */ + fun chatChanged(conversationId: String): JsonObject = buildJsonObject { + put("type", "chat.changed") + put("body", buildJsonObject { put("conversationId", conversationId) }) + } + fun deviceRequest(id: String, op: String, fields: JsonObjectBuilder.() -> Unit): JsonObject = buildJsonObject { put("type", "device.request") diff --git a/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/protocol/ProtocolFamilyTest.kt b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/protocol/ProtocolFamilyTest.kt index b436f468e..2ca51a725 100644 --- a/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/protocol/ProtocolFamilyTest.kt +++ b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/protocol/ProtocolFamilyTest.kt @@ -24,6 +24,7 @@ class ProtocolFamilyTest { "log" to Protocol.log("hello"), "session" to Protocol.session("token", "refresh"), "backend.pair" to Protocol.backendPair("pair-1", accepted = true), + "chat.changed" to Protocol.chatChanged("c-1"), "backend.status" to Protocol.backendStatus( id = "status-1", status = GatewayStatus( @@ -87,7 +88,7 @@ class ProtocolFamilyTest { "browser.request" to Protocol.browserRequest("b-1", "read") {}, ) - val withoutId = setOf("ready", "log", "session") + val withoutId = setOf("ready", "log", "session", "chat.changed") for ((type, message) in cases) { assertEquals(type, message.text("type"), "$type envelope changed") if (type !in withoutId) { diff --git a/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/protocol/ProtocolGoldenTest.kt b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/protocol/ProtocolGoldenTest.kt index b60681313..358a53fa1 100644 --- a/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/protocol/ProtocolGoldenTest.kt +++ b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/protocol/ProtocolGoldenTest.kt @@ -32,6 +32,7 @@ class ProtocolGoldenTest { Protocol.taskRefused("t-1", "task.start", "unsupported"), Protocol.backendPair("pair-1", accepted = true), Protocol.turnEnd("r-1", "c-1", "T", "A", emptyList(), chainOk = true), + Protocol.chatChanged("c-1"), ) assertEquals(golden.size, built.size, "the golden file has a different frame count") diff --git a/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/protocol/ProtocolTest.kt b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/protocol/ProtocolTest.kt index 316e2f2ea..365bbb65b 100644 --- a/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/protocol/ProtocolTest.kt +++ b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/protocol/ProtocolTest.kt @@ -4,7 +4,9 @@ import com.hopa.contracts.wire.Action import com.hopa.contracts.wire.Approver import com.hopa.contracts.wire.RunRecord import com.hopa.sidecar.protocol.Protocol.text +import kotlinx.serialization.json.JsonObject import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test @@ -108,6 +110,19 @@ class ProtocolTest { assertTrue(step["approver"].toString().contains("\"at\":1234")) } + @Test + fun chat_changed_names_only_the_conversation() { + val changed = Protocol.chatChanged("c-1") + + // An unsolicited event: no id, because the host is not waiting for it. + assertEquals("chat.changed", changed.text("type")) + assertNull(changed["id"]) + assertEquals(setOf("type", "body"), changed.keys) + val body = changed["body"] as JsonObject + assertEquals(setOf("conversationId"), body.keys) + assertEquals("c-1", body.text("conversationId")) + } + @Test fun an_unknown_cli_option_is_rejected() { assertThrows(IllegalArgumentException::class.java) { diff --git a/spec/protocol/golden.ndjson b/spec/protocol/golden.ndjson index 2fd3bbf3e..9e3b486fb 100644 --- a/spec/protocol/golden.ndjson +++ b/spec/protocol/golden.ndjson @@ -7,3 +7,4 @@ {"type":"task.error","id":"t-1","request":"task.start","ok":false,"code":"E_UNSUPPORTED","error":"unsupported"} {"type":"backend.pair","id":"pair-1","accepted":true} {"type":"turn.end","id":"r-1","conversationId":"c-1","title":"T","answer":"A","chainOk":true,"plan":[],"steps":[]} +{"type":"chat.changed","body":{"conversationId":"c-1"}} diff --git a/spec/protocol/schema.v1.json b/spec/protocol/schema.v1.json index f2f3e06bd..b609f9d39 100644 --- a/spec/protocol/schema.v1.json +++ b/spec/protocol/schema.v1.json @@ -34,6 +34,7 @@ { "$ref": "#/$defs/backendPairResult" }, { "$ref": "#/$defs/backendPairCancel" }, { "$ref": "#/$defs/backendStatus" }, + { "$ref": "#/$defs/chatChanged" }, { "$ref": "#/$defs/gatewayApprovalAsk" }, { "$ref": "#/$defs/deviceRequest" }, { "$ref": "#/$defs/browserRequest" } @@ -381,6 +382,20 @@ "phoneDeviceId": { "type": "string" } } }, + "chatChanged": { + "type": "object", + "required": ["type", "body"], + "properties": { + "type": { "const": "chat.changed" }, + "body": { + "type": "object", + "required": ["conversationId"], + "properties": { + "conversationId": { "type": "string" } + } + } + } + }, "gatewayApprovalAsk": { "type": "object", "required": ["type", "id", "allow"], From 251f732da32ae865bcceae74c680ee978c78ec09 Mon Sep 17 00:00:00 2001 From: aharonamir Date: Mon, 30 Nov 2026 02:30:52 +0200 Subject: [PATCH 22/58] Run a sync pass from the Windows sidecar BackendSyncHost builds the shared engine from the stored session on every pass and merges into ChatStore, so a sign-out, a token rotation or a re-pair takes effect without a restart. The cursor and the last-synced title map are small atomic JSON files in the data dir; a title is pushed only when it differs from that record, tombstones travel every pass, and this PC's own ops are inert on a pull so an older echo cannot undo a rename. GatewayHost starts a pass on the first Live state and on sync.changed, and a conversation write or a turn append asks for the debounced pass. Part of #32. --- .../hopa/sidecar/backend/BackendSyncHost.kt | 410 ++++++++++++++++++ .../com/hopa/sidecar/backend/GatewayHost.kt | 22 + .../hopa/sidecar/backend/SyncStateFiles.kt | 89 ++++ .../protocol/handler/ConversationHandler.kt | 34 +- .../com/hopa/sidecar/startup/ProtocolMode.kt | 15 +- .../com/hopa/sidecar/turn/TurnEngine.kt | 10 + .../sidecar/backend/BackendSyncHostTest.kt | 371 ++++++++++++++++ .../hopa/sidecar/backend/GatewayStateTest.kt | 28 ++ .../handler/ConversationHandlerTest.kt | 95 ++++ 9 files changed, 1059 insertions(+), 15 deletions(-) create mode 100644 apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/BackendSyncHost.kt create mode 100644 apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/SyncStateFiles.kt create mode 100644 apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/BackendSyncHostTest.kt create mode 100644 apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/protocol/handler/ConversationHandlerTest.kt diff --git a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/BackendSyncHost.kt b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/BackendSyncHost.kt new file mode 100644 index 000000000..fd6cd76a5 --- /dev/null +++ b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/BackendSyncHost.kt @@ -0,0 +1,410 @@ +package com.hopa.sidecar.backend + +import com.hopa.backend.pairing.BackendUrls +import com.hopa.backend.sync.client.OkHttpSyncHttp +import com.hopa.backend.sync.client.PullAnswer +import com.hopa.backend.sync.client.PushAnswer +import com.hopa.backend.sync.client.RemoteSyncOp +import com.hopa.backend.sync.client.SealedOp +import com.hopa.backend.sync.client.SyncBacklog +import com.hopa.backend.sync.client.SyncCodec +import com.hopa.backend.sync.client.SyncCursor +import com.hopa.backend.sync.client.SyncDraft +import com.hopa.backend.sync.client.SyncEngine +import com.hopa.backend.sync.client.SyncHttp +import com.hopa.backend.sync.client.SyncKind +import com.hopa.backend.sync.client.SyncTarget +import com.hopa.contracts.chat.ChatMessage +import com.hopa.contracts.chat.Conversation +import com.hopa.sidecar.store.ChatStore +import java.nio.file.Path +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put + +/** + * The PC's half of sync v0: one pull-then-push pass against the household op + * log, on the same [ChatStore] the chat already uses. + * + * A pass is built from the stored session each time, so a sign-out, a token + * rotation or a re-pair takes effect on the next pass without a restart. The + * shared engine owns the wire rules; this class only maps [ChatStore] rows to + * its target, builds the local backlog and serialises passes. + * + * Two local rules matter here, both mirrored from the phone: + * - A title already recorded as synced is not sent again just because a message + * bumped `updatedAt`, while a rename back to an earlier name still travels + * under a new op id. + * - An op this PC wrote is inert when it comes back on a later pull, so our own + * older title can never undo a rename that has not been pushed yet. + */ +class BackendSyncHost( + private val sessions: BackendSessionStore, + private val contentKey: () -> ByteArray?, + private val chats: ChatStore, + private val cursorFile: Path, + private val notify: (String) -> Unit, + private val http: SyncHttp = OkHttpSyncHttp(), + private val scope: CoroutineScope, +) { + /** Serialises passes: a trigger that lands mid-pass waits instead of racing. */ + private val pass = Mutex() + private val triggers = Any() + + @Volatile + private var running = false + private var pending: Job? = null + + private val titlesFile: Path = cursorFile.resolveSibling(TITLES_FILE) + + /** One pull-then-push pass; waits for a pass already in flight. */ + suspend fun syncNow(): Int = withContext(Dispatchers.IO) { + try { + pass.withLock { runPass() } + } catch (cancelled: CancellationException) { + throw cancelled + } catch (_: Exception) { + // A store read, a bad tag or a transport reset: the cursor and the + // applied rows are the only durable result. Nothing is logged, + // because a failure can quote plaintext. + 0 + } + } + + /** Begin coalescing local and remote triggers into passes; one runs now. */ + fun start() { + running = true + schedule() + } + + /** Stop triggering passes. One already in flight is allowed to finish. */ + fun stop() { + running = false + synchronized(triggers) { + pending?.cancel() + pending = null + } + } + + /** The gateway said a peer wrote up to some seq. */ + fun onRemoteChanged() = schedule() + + /** A local create, append, rename or delete; the next pass sends it. */ + fun onLocalChange(@Suppress("UNUSED_PARAMETER") conversationId: String) = schedule() + + /** + * Coalesces triggers into one pass: a trigger inside the window replaces the + * pending one, so a burst of writes costs one pull. + */ + private fun schedule() { + if (!running) { + return + } + synchronized(triggers) { + pending?.cancel() + pending = scope.launch { + delay(DEBOUNCE_MS) + try { + syncNow() + } catch (cancelled: CancellationException) { + throw cancelled + } catch (_: Exception) { + // A pass reports nothing; a trigger never crashes the scope. + } + } + } + } + + private suspend fun runPass(): Int { + val session = sessions.load() ?: return 0 + if (session.deviceId.isBlank() || session.accessToken.isBlank() || session.gatewayUrl.isBlank()) return 0 + val key = contentKey() ?: return 0 + if (key.size != CONTENT_KEY_BYTES) return 0 + + val cursorStore = SyncCursorFile(cursorFile) + val start = cursorStore.read() + val cursor = PassCursor(start) + val titlesStore = SyncedTitlesFile(titlesFile) + val storedTitles = titlesStore.read() + val recordedTitles = storedTitles.toMutableMap() + + val target = ChatTarget(chats) { threadId, title -> + // A pulled title is already on the server; record it so the next + // pass does not treat it as an unsent local edit. + recordedTitles[threadId] = title + } + val engine = SyncEngine( + http = OwnOpsIgnored(http, session.deviceId), + codec = SyncCodec(key), + target = target, + cursor = cursor, + token = { session.accessToken }, + baseUrl = { BackendUrls.httpBase(session.gatewayUrl) }, + ) + + val report = engine.pull() + + // The pull is done: persist its cursor and announce what it applied even + // if the push below fails, or the next pass would see duplicates and + // never announce those rows. + if (cursor.read() != start) { + cursorStore.write(cursor.read()) + } + if (recordedTitles != storedTitles) { + titlesStore.write(recordedTitles) + } + for (id in target.changed) { + runCatching { notify(id) } + } + + val backlog = backlog(session.deviceId, recordedTitles) + if (backlog.drafts.isEmpty()) { + return report.applied + } + val answer = engine.push(backlog.drafts) + // Only an acknowledged op proves the server holds the title. A duplicate + // ack means it already did. + var recorded = false + for (ack in answer.accepted) { + val pushed = backlog.titles[ack.opId] ?: continue + if (recordedTitles[pushed.threadId] != pushed.title) { + recordedTitles[pushed.threadId] = pushed.title + recorded = true + } + } + if (recorded) { + titlesStore.write(recordedTitles) + } + return report.applied + } + + /** + * Sends the local set: every turn, tombstones keyed by the deletion time, + * and a title only when it differs from the record a finished pass or a pull + * established. + */ + private fun backlog(device: String, recordedTitles: Map): Backlog { + val turns = mutableListOf() + val threads = mutableListOf() + val titlePushes = mutableMapOf() + for (thread in chats.allWithDeleted()) { + for (message in thread.messages) { + if (message.role !in ROLES || message.text.isBlank()) { + continue + } + val at = message.timestamp.takeIf { it > 0L } ?: System.currentTimeMillis() + val payload = buildJsonObject { + put("role", message.role) + put("text", message.text) + put("at", at) + } + // One op the codec refuses would fail the whole pass, and the + // thread stays in allWithDeleted() even when deleted. Keep this + // turn local and let the rest of the log through. + if (!fits(payload)) { + continue + } + turns += SyncDraft( + opId = message.id, + kind = SyncKind.TURN_APPEND, + threadId = thread.id, + turnId = message.id, + payload = payload, + clientAt = at, + ) + } + if (thread.deletedAt > 0L) { + // Tombstones stay keyed by the deletion time and travel every + // pass; the server dedupes them. + val payload = buildJsonObject { + put("deletedAt", thread.deletedAt) + put("clientAt", thread.updatedAt) + } + if (fits(payload)) { + threads += SyncDraft( + opId = SyncBacklog.tombstoneOpId(thread.id, thread.deletedAt, device), + kind = SyncKind.THREAD_UPSERT, + threadId = thread.id, + turnId = null, + payload = payload, + clientAt = thread.updatedAt, + ) + } + } else if (recordedTitles[thread.id] != thread.title) { + // Only a new or edited title travels; a message leaves the + // title record equal, so it cannot republish a stale one. + val payload = buildJsonObject { + put("title", thread.title) + put("deletedAt", 0) + put("clientAt", thread.updatedAt) + } + if (fits(payload)) { + val opId = SyncBacklog.titleOpId(thread.id, thread.updatedAt, device) + threads += SyncDraft( + opId = opId, + kind = SyncKind.THREAD_UPSERT, + threadId = thread.id, + turnId = null, + payload = payload, + clientAt = thread.updatedAt, + ) + titlePushes[opId] = TitlePush(thread.id, thread.title) + } + } + } + return Backlog(threads + SyncBacklog.orderTurns(turns), titlePushes) + } + + private fun fits(payload: JsonObject): Boolean = + payload.toString().toByteArray(Charsets.UTF_8).size <= MAX_PLAINTEXT_BYTES + + private class Backlog( + val drafts: List, + /** Title pushes by op id, recorded once the server acks them. */ + val titles: Map, + ) + + private class TitlePush(val threadId: String, val title: String) + + /** The cursor for one pass, written to disk only after it finishes. */ + private class PassCursor(initial: Long) : SyncCursor { + private var seq = initial + + override fun read(): Long = seq + + override fun write(seq: Long) { + this.seq = seq + } + } + + /** + * [ChatStore] as [SyncTarget]. One snapshot serves every `hasTurn` in a + * pass, so a long thread list is not re-read per op; each applied op updates + * the snapshot so a later op in the same pass sees it. + */ + private class ChatTarget( + private val chats: ChatStore, + private val onRemoteTitle: (threadId: String, title: String) -> Unit, + ) : SyncTarget { + private var rows: Map? = null + private val changedIds = linkedSetOf() + + val changed: Set get() = changedIds + + private fun rows(): Map = + rows ?: chats.allWithDeleted().associateBy { it.id }.also { rows = it } + + override suspend fun hasTurn(threadId: String, turnId: String): Boolean = + rows()[threadId]?.messages?.any { it.id == turnId } == true + + override suspend fun appendTurn( + threadId: String, + turnId: String, + role: String, + text: String, + at: Long, + ) { + val message = ChatMessage(id = turnId, role = role, text = text, timestamp = at) + val row = chats.mergeRemote(threadId, null, deletedAt = 0, updatedAt = at, message = message) + ?: return + rows = rows() + (threadId to row) + changedIds += threadId + } + + override suspend fun applyThread( + threadId: String, + title: String?, + deletedAt: Long, + clientAt: Long, + ) { + val existing = rows()[threadId] + val row = chats.mergeRemote(threadId, title, deletedAt, clientAt, message = null) ?: return + rows = rows() + (threadId to row) + val gone = row.deletedAt > 0L + if (!gone && !title.isNullOrBlank()) { + onRemoteTitle(threadId, row.title) + } + // A tombstone is final: a later title must not resurrect the thread, + // and a deleted thread never takes a title. + val changed = existing == null || + row.deletedAt != existing.deletedAt || + (!gone && !title.isNullOrBlank() && row.title != existing.title) || + clientAt > existing.updatedAt + if (changed) { + changedIds += threadId + } + } + } + + private companion object { + /** Wait this long for the rest of a burst before one pass. */ + const val DEBOUNCE_MS = 250L + + /** The household key size; anything else is a broken session. */ + const val CONTENT_KEY_BYTES = 32 + + /** The last-synced title per thread, beside the cursor. */ + const val TITLES_FILE = "synced-titles.json" + + /** + * PayloadCipher's blob is `IV(12) || ciphertext || tag(16)`, so a + * plaintext may be this much smaller than the codec's ciphertext cap. + */ + const val SEAL_OVERHEAD_BYTES = 12 + 16 + + /** The most plaintext one op may seal; one byte more makes seal() throw. */ + const val MAX_PLAINTEXT_BYTES = SyncCodec.MAX_CIPHERTEXT_BYTES - SEAL_OVERHEAD_BYTES + + val ROLES = setOf("user", "assistant") + } +} + +/** + * Hides this PC's own ops from the engine: their seq is still applied to the + * cursor (kind `null` is a recorded skip), but their content is never merged + * again. Re-applying our own older title on the next pull was how a rename could + * be undone by its own echo. + */ +private class OwnOpsIgnored( + private val inner: SyncHttp, + private val device: String, +) : SyncHttp { + override suspend fun push(token: String, baseUrl: String, ops: List): PushAnswer = + inner.push(token, baseUrl, ops) + + override suspend fun pull(token: String, baseUrl: String, after: Long, limit: Int): PullAnswer { + val page = inner.pull(token, baseUrl, after, limit) + if (page.ops.none { it.fromDevice == device }) { + return page + } + return page.copy( + ops = page.ops.map { op -> + if (op.fromDevice != device) { + op + } else { + RemoteSyncOp( + seq = op.seq, + opId = op.opId, + kind = null, + threadId = op.threadId, + turnId = op.turnId, + fromDevice = op.fromDevice, + memberId = op.memberId, + clientAt = op.clientAt, + at = op.at, + ciphertext = op.ciphertext, + ) + } + }, + ) + } +} diff --git a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/GatewayHost.kt b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/GatewayHost.kt index 83e8c0de7..947315b7c 100644 --- a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/GatewayHost.kt +++ b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/GatewayHost.kt @@ -64,6 +64,9 @@ internal fun interface GatewayStarter { * also owns the gateway flags: a collector on the link's [BackendLink.state] * resolves the phone and writes [RuntimeConfig.setGatewayState] on every change, * so the engine — not the window — reports pairing and phone presence. + * + * It also owns the sync triggers: the first `Live` starts one pull-then-push + * pass, and every `sync.changed` frame from a peer asks for another. */ internal class GatewayHost( private val io: Stdio, @@ -74,10 +77,15 @@ internal class GatewayHost( private val scope: CoroutineScope, private val config: RuntimeConfig, private val phones: PhoneDirectory, + private val sync: BackendSyncHost? = null, private val onStatus: (JsonObject) -> Unit = {}, ) : GatewayStarter { private var current: CoroutineScope? = null + /** True once this start's link reached `Live` and the sync host was started. */ + @Volatile + private var syncStarted = false + /** The session [start] was given; null until then, so `paired` stays false. */ @Volatile private var activeSession: BackendSession? = null @@ -102,6 +110,8 @@ internal class GatewayHost( override fun start(session: BackendSession, contentKey: ByteArray) { require(contentKey.size == CONTENT_KEY_BYTES) { "content key must be $CONTENT_KEY_BYTES bytes" } current?.cancel() + sync?.stop() + syncStarted = false activeSession = session activePhoneId = null var credentials = BackendCredentials( @@ -149,6 +159,7 @@ internal class GatewayHost( appVersion = Protocol.VERSION.toString(), ) activeLink = link + link.onSyncChanged = { sync?.onRemoteChanged() } val gateway = BackendGateway( link = link, contentKey = contentKey, @@ -181,6 +192,15 @@ internal class GatewayHost( }, config = config, onStatus = onStatus, + onState = { state -> + // One pass per connection: the pull reconciles everything a + // peer wrote while this PC was away. Later frames arrive as + // `sync.changed` and ask for their own pass. + if (state is BackendState.Live && !syncStarted) { + syncStarted = true + sync?.start() + } + }, ) } live.launch { gateway.runForever(live) } @@ -256,8 +276,10 @@ internal suspend fun collectGatewayState( resolvePhone: suspend (peers: List) -> String?, config: RuntimeConfig, onStatus: (JsonObject) -> Unit, + onState: (BackendState) -> Unit = {}, ) { states.collect { state -> + onState(state) val phoneId = if (state is BackendState.Live) resolvePhone(state.peers) else null config.setGatewayState(paired = true, phoneOnline = phoneId != null) onStatus(Protocol.backendStatus(status = gatewayStatus(session, state, phoneId))) diff --git a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/SyncStateFiles.kt b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/SyncStateFiles.kt new file mode 100644 index 000000000..006987a58 --- /dev/null +++ b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/SyncStateFiles.kt @@ -0,0 +1,89 @@ +package com.hopa.sidecar.backend + +import com.hopa.backend.sync.client.SyncCursor +import java.nio.file.AtomicMoveNotSupportedException +import java.nio.file.Files +import java.nio.file.Path +import java.nio.file.StandardCopyOption +import java.nio.file.attribute.PosixFileAttributeView +import java.nio.file.attribute.PosixFilePermissions +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive + +/** The one number the household op log needs: `{"seq":N}`. */ +@Serializable +private data class CursorState(val seq: Long = 0) + +private val json = Json { + ignoreUnknownKeys = true +} + +/** + * The seq this PC applied up to, written atomically like the session file. It + * holds no title, message or key, only the position. + */ +internal class SyncCursorFile(private val file: Path) : SyncCursor { + override fun read(): Long { + if (!Files.exists(file)) return 0 + return runCatching { + json.decodeFromString(CursorState.serializer(), Files.readString(file)).seq.coerceAtLeast(0) + }.getOrDefault(0) + } + + override fun write(seq: Long) { + writeAtomically(file, json.encodeToString(CursorState.serializer(), CursorState(seq)), ownerOnly = false) + } +} + +/** + * The title this PC last synced per thread. A title that differs from its entry + * is an unsent local edit; a title applied from the log is recorded here so the + * next pass does not echo it back. + */ +internal class SyncedTitlesFile(private val file: Path) { + fun read(): Map { + if (!Files.exists(file)) return emptyMap() + return runCatching { + json.parseToJsonElement(Files.readString(file)).jsonObject + .mapValues { (_, value) -> value.jsonPrimitive.contentOrNull.orEmpty() } + .filterValues { it.isNotBlank() } + }.getOrDefault(emptyMap()) + } + + fun write(titles: Map) { + val jsonObject = JsonObject(titles.mapValues { (_, title) -> JsonPrimitive(title) }) + writeAtomically(file, jsonObject.toString(), ownerOnly = true) + } +} + +/** + * Temp file then rename, so a crash leaves the previous version intact rather + * than half a document. Title text is private, so that file stays owner-only + * where the filesystem supports it. + */ +private fun writeAtomically(file: Path, text: String, ownerOnly: Boolean) { + val directory = file.toAbsolutePath().parent + Files.createDirectories(directory) + val temp = Files.createTempFile(directory, file.fileName.toString(), ".tmp") + try { + Files.writeString(temp, text) + if (ownerOnly) { + runCatching { + Files.getFileAttributeView(temp, PosixFileAttributeView::class.java) + ?.setPermissions(PosixFilePermissions.fromString("rw-------")) + } + } + try { + Files.move(temp, file, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) + } catch (_: AtomicMoveNotSupportedException) { + Files.move(temp, file, StandardCopyOption.REPLACE_EXISTING) + } + } finally { + runCatching { Files.deleteIfExists(temp) } + } +} diff --git a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/protocol/handler/ConversationHandler.kt b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/protocol/handler/ConversationHandler.kt index 08b2c0bf3..01d98021b 100644 --- a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/protocol/handler/ConversationHandler.kt +++ b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/protocol/handler/ConversationHandler.kt @@ -10,6 +10,8 @@ import kotlinx.serialization.json.JsonObject internal class ConversationHandler( private val io: Stdio, private val store: ChatStore, + /** A create, rename or delete is a local change the sync pass must send. */ + private val onLocalChange: (String) -> Unit = {}, ) : MessageHandler { override fun handle(type: String, message: JsonObject): Boolean { when (type) { @@ -34,8 +36,11 @@ internal class ConversationHandler( ), ) - "conversation.create" -> - io.send(Protocol.conversationOpened(message.text("id"), store.create())) + "conversation.create" -> { + val created = store.create() + io.send(Protocol.conversationOpened(message.text("id"), created)) + onLocalChange(created.id) + } "conversation.open" -> io.send(Protocol.conversationOpened(message.text("id"), store.get(message.text("conversationId")))) @@ -43,19 +48,20 @@ internal class ConversationHandler( "conversation.search" -> io.send(Protocol.conversationList(message.text("id"), store.search(message.text("query")))) - "conversation.rename" -> io.send( - Protocol.conversationOpened( - message.text("id"), - store.rename(message.text("conversationId"), message.text("title")), - ), - ) + "conversation.rename" -> { + val renamed = store.rename(message.text("conversationId"), message.text("title")) + io.send(Protocol.conversationOpened(message.text("id"), renamed)) + renamed?.let { onLocalChange(it.id) } + } - "conversation.delete" -> io.send( - Protocol.conversationDeleted( - message.text("id"), - store.delete(message.text("conversationId")), - ), - ) + "conversation.delete" -> { + val conversationId = message.text("conversationId") + val deleted = store.delete(conversationId) + io.send(Protocol.conversationDeleted(message.text("id"), deleted)) + if (deleted) { + onLocalChange(conversationId) + } + } "conversation.export" -> io.send( Protocol.conversationExported( diff --git a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/startup/ProtocolMode.kt b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/startup/ProtocolMode.kt index ead90f0b7..47b1bee20 100644 --- a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/startup/ProtocolMode.kt +++ b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/startup/ProtocolMode.kt @@ -5,6 +5,7 @@ import com.hopa.sidecar.backend.BackendAdmission import com.hopa.sidecar.browser.HostBrowser import com.hopa.sidecar.backend.BackendSession import com.hopa.sidecar.backend.BackendSessionStore +import com.hopa.sidecar.backend.BackendSyncHost import com.hopa.sidecar.backend.EngineTaskRunner import com.hopa.sidecar.backend.GatewayHost import com.hopa.sidecar.backend.PhoneDirectory @@ -87,11 +88,22 @@ internal fun runProtocol(options: CliOptions) { val backendScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) val sessionPath = dataDir.resolve("backend-session.json") val sessionStore = BackendSessionStore(sessionPath) + val sync = BackendSyncHost( + sessions = sessionStore, + // Read per pass, like the token: a re-pair with a new household key + // takes effect on the next pass without a restart. + contentKey = { sessionStore.load()?.let(::backendContentKey) }, + chats = store, + cursorFile = dataDir.resolve("sync-cursor.json"), + notify = { conversationId -> io.send(Protocol.chatChanged(conversationId)) }, + scope = backendScope, + ) val runner = EngineTaskRunner( startTurn = { id, goal -> engine.startTurn(id, goal, conversationId = null) }, cancelTurn = engine::cancel, ) engine.onTurnEnd = runner::complete + engine.onLocalChange = sync::onLocalChange val phones = PhoneDirectory() val gateways = GatewayHost( io = io, @@ -102,6 +114,7 @@ internal fun runProtocol(options: CliOptions) { scope = backendScope, config = config, phones = phones, + sync = sync, onStatus = io::send, ) @@ -157,7 +170,7 @@ internal fun runProtocol(options: CliOptions) { val dispatcher = Dispatcher( io = io, handlers = listOf( - ConversationHandler(io, store), + ConversationHandler(io, store, sync::onLocalChange), TurnHandler(io, engine), FileHandler(io, attachments), MemoryHandler(io, memory), diff --git a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/turn/TurnEngine.kt b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/turn/TurnEngine.kt index 75deaae43..e4cf99b22 100644 --- a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/turn/TurnEngine.kt +++ b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/turn/TurnEngine.kt @@ -101,6 +101,14 @@ class TurnEngine( @Volatile var onTurnEnd: ((id: String, answer: String) -> Unit)? = null + /** + * Invoked after the turn appends a local message (and the title its first + * message sets), so the sync pass can send it. One turn at a time is this + * engine's contract; the hook must not block. + */ + @Volatile + var onLocalChange: ((conversationId: String) -> Unit)? = null + /** Shutdown/no-id cancel: stops whatever turn is running. */ @Synchronized fun cancel() { @@ -278,6 +286,7 @@ class TurnEngine( val conversation = existing ?: store.create() val history = conversation.messages.map { ModelMessage(it.role, it.text) } store.append(conversation.id, "user", goal, attachment) + onLocalChange?.invoke(conversation.id) // The goal may be private; it is persisted in the chat store, never logged. io.log("turn $id in ${conversation.id}") io.log("turn $id vision=${config.vision}") @@ -397,6 +406,7 @@ class TurnEngine( recordStore.append(conversation.id, "run-$id", records) val chainOk = records.isEmpty() || RunChain.verify(records) store.append(conversation.id, "assistant", answer) + onLocalChange?.invoke(conversation.id) val updated = store.get(conversation.id) TurnOutcome( conversationId = conversation.id, diff --git a/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/BackendSyncHostTest.kt b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/BackendSyncHostTest.kt new file mode 100644 index 000000000..00657a68a --- /dev/null +++ b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/BackendSyncHostTest.kt @@ -0,0 +1,371 @@ +package com.hopa.sidecar.backend + +import com.hopa.backend.sync.client.PullAnswer +import com.hopa.backend.sync.client.PushAck +import com.hopa.backend.sync.client.PushAnswer +import com.hopa.backend.sync.client.RemoteSyncOp +import com.hopa.backend.sync.client.SealedOp +import com.hopa.backend.sync.client.SyncCodec +import com.hopa.backend.sync.client.SyncDraft +import com.hopa.backend.sync.client.SyncHttp +import com.hopa.backend.sync.client.SyncKind +import com.hopa.contracts.chat.ChatMessage +import com.hopa.sidecar.store.ChatStore +import java.nio.file.Files +import java.nio.file.Path +import java.util.Base64 +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.put +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNotEquals +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test + +/** + * One pull-then-push pass against a fake op log: the store rules live in + * [ChatStore], the wire rules in the shared engine, and this class only maps + * the two and decides when a pass runs. + */ +class BackendSyncHostTest { + @Test + fun `a signed-out pc makes no call`() = runBlocking { + Harness(signedIn = false).use { harness -> + assertEquals(0, harness.host().syncNow()) + assertEquals(0, harness.server.pulls) + assertTrue(harness.server.pushBatches.isEmpty()) + } + } + + @Test + fun `a remote turn is applied once and the pass announces its thread`() = runBlocking { + Harness().use { harness -> + harness.server.seed( + kind = SyncKind.TURN_APPEND, + threadId = "c-remote", + turnId = "m-remote", + payload = turnPayload("user", "from the pc", 42), + opId = "m-remote", + clientAt = 42, + ) + val host = harness.host() + + assertEquals(1, host.syncNow()) + + val thread = harness.chats.allWithDeleted().single { it.id == "c-remote" } + assertEquals(listOf("m-remote"), thread.messages.map { it.id }) + assertEquals("from the pc", thread.messages.single().text) + assertEquals(42L, thread.messages.single().timestamp) + assertEquals(listOf("c-remote"), harness.notified) + + // A second pass pulls nothing new and does not touch the store. + assertEquals(0, host.syncNow()) + assertEquals(1, harness.chats.allWithDeleted().single { it.id == "c-remote" }.messages.size) + assertEquals(listOf("c-remote"), harness.notified) + } + } + + @Test + fun `a local turn is pushed under the turn's own id`() = runBlocking { + Harness().use { harness -> + val conversation = harness.chats.create() + val message = harness.chats.append(conversation.id, "user", "hello")!!.messages.single() + + assertEquals(0, harness.host().syncNow()) + + val batch = harness.server.pushBatches.single() + val turn = batch.single { it.kind == SyncKind.TURN_APPEND && it.opId == message.id } + assertEquals(message.id, turn.turnId) + assertEquals(1, harness.server.opCount(message.id)) + } + } + + @Test + fun `the cursor survives a new host instance`() = runBlocking { + Harness().use { harness -> + harness.server.seed( + SyncKind.TURN_APPEND, + "c-1", + "m-1", + turnPayload("user", "hello", 10), + opId = "m-1", + clientAt = 10, + ) + + assertEquals(1, harness.host().syncNow()) + val cursorText = Files.readString(harness.dataDir.resolve(CURSOR_FILE)) + assertEquals("{\"seq\":1}", cursorText.trim()) + + // A new process over the same files asks after the applied seq. + harness.host().syncNow() + assertEquals(listOf(0L, 1L), harness.server.pullAfters) + assertEquals(1, harness.chats.allWithDeleted().single { it.id == "c-1" }.messages.size) + } + } + + @Test + fun `a duplicate push is a no-op`() = runBlocking { + Harness().use { harness -> + val conversation = harness.chats.create() + val message = harness.chats.append(conversation.id, "user", "hello")!!.messages.single() + val host = harness.host() + + host.syncNow() + host.syncNow() + + assertEquals(2, harness.server.pushBatches.size) + assertEquals(1, harness.server.opCount(message.id)) + assertEquals(1, harness.chats.allWithDeleted().single { it.id == conversation.id }.messages.size) + } + } + + @Test + fun `a pulled title is recorded and never echoed back`() = runBlocking { + Harness().use { harness -> + harness.server.seed( + SyncKind.THREAD_UPSERT, + "c-1", + null, + threadPayload("Peer", deletedAt = 0, clientAt = 10), + opId = "peer-title", + clientAt = 10, + ) + val host = harness.host() + + host.syncNow() + assertEquals("Peer", harness.chats.get("c-1")?.title) + assertTrue(harness.server.pushBatches.isEmpty()) + + host.syncNow() + assertTrue(harness.server.pushBatches.isEmpty()) + } + } + + @Test + fun `a message does not push a stale title`() = runBlocking { + Harness().use { harness -> + harness.chats.mergeRemote("c-1", "Trip", 0, 1, ChatMessage("m-1", "user", "hi", 1)) + val host = harness.host() + host.syncNow() + assertEquals("Trip", harness.server.titleOf("c-1")) + + harness.chats.append("c-1", "assistant", "hello") + host.syncNow() + + val last = harness.server.pushBatches.last() + assertTrue(last.any { it.kind == SyncKind.TURN_APPEND }) + assertEquals(0, last.count { it.kind == SyncKind.THREAD_UPSERT }) + assertEquals("Trip", harness.server.titleOf("c-1")) + } + } + + @Test + fun `a rename back to an earlier title still lands as a new op`() = runBlocking { + Harness().use { harness -> + harness.chats.mergeRemote("c-1", "A", 0, 1, ChatMessage("m-1", "user", "hi", 1)) + val host = harness.host() + + host.syncNow() + harness.chats.rename("c-1", "B") + host.syncNow() + harness.chats.rename("c-1", "A") + host.syncNow() + + val titles = harness.server.pushBatches.map { batch -> + batch.single { it.kind == SyncKind.THREAD_UPSERT } + } + assertEquals(3, titles.size) + assertNotEquals(titles[0].opId, titles[2].opId) + assertEquals("A", harness.server.titleOf("c-1")) + } + } + + @Test + fun `a tombstone is pushed with the deletion time`() = runBlocking { + Harness().use { harness -> + harness.chats.mergeRemote("c-1", "Trip", 0, 1, ChatMessage("m-1", "user", "hi", 1)) + val host = harness.host() + host.syncNow() + harness.chats.delete("c-1") + + host.syncNow() + + val tombstone = harness.server.pushBatches.last().single { + it.kind == SyncKind.THREAD_UPSERT && it.opId.contains(":deleted:") + } + assertEquals("c-1", tombstone.threadId) + assertNull(tombstone.turnId) + assertEquals(0, harness.server.pushBatches.last().count { + it.kind == SyncKind.THREAD_UPSERT && !it.opId.contains(":deleted:") + }) + assertTrue(harness.chats.get("c-1")!!.deletedAt > 0) + } + } + + private class Harness(signedIn: Boolean = true) : AutoCloseable { + val dataDir: Path = Files.createTempDirectory("hopa-sync") + val chats = ChatStore(dataDir.resolve("conversations.json")) + val server = FakeSyncServer() + val notified = mutableListOf() + private val sessions = BackendSessionStore(dataDir.resolve("backend-session.json")) + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + init { + if (signedIn) { + sessions.save( + BackendSession( + deviceId = DEVICE, + householdId = "h1", + accessToken = "a1", + refreshToken = "r1", + expiresAt = "2026-11-30T00:15:00Z", + gatewayUrl = "wss://hopa.test/v1/gateway", + contentKeyBase64 = Base64.getEncoder().encodeToString(KEY), + privateKeyBase64 = "cA==", + ), + ) + } + } + + fun host(): BackendSyncHost = BackendSyncHost( + sessions = sessions, + contentKey = { KEY }, + chats = chats, + cursorFile = dataDir.resolve(CURSOR_FILE), + notify = { id -> notified += id }, + http = server, + scope = scope, + ) + + override fun close() = scope.cancel() + } + + /** Plays the household op log; it seals and opens only for its own checks. */ + private class FakeSyncServer( + private val device: String = DEVICE, + private val key: ByteArray = KEY, + ) : SyncHttp { + private val log = mutableListOf() + private val seqByOpId = mutableMapOf() + private val threadOps = mutableListOf() + val pullAfters = mutableListOf() + val pushBatches = mutableListOf>() + var pulls = 0 + + private val head: Long get() = log.maxOfOrNull { it.seq } ?: 0L + + override suspend fun pull(token: String, baseUrl: String, after: Long, limit: Int): PullAnswer { + pulls += 1 + pullAfters += after + val page = log.filter { it.seq > after }.sortedBy { it.seq }.take(limit) + return PullAnswer( + ops = page, + hasMore = page.isNotEmpty() && log.any { it.seq > page.last().seq }, + head = head, + ) + } + + override suspend fun push(token: String, baseUrl: String, ops: List): PushAnswer { + pushBatches += ops + return PushAnswer(head = head, accepted = ops.map(::accept)) + } + + fun seed( + kind: SyncKind, + threadId: String, + turnId: String?, + payload: JsonObject, + opId: String, + clientAt: Long, + fromDevice: String = "peer", + ) { + val sealed = SyncCodec(key).seal(SyncDraft(opId, kind, threadId, turnId, payload, clientAt)) + val seq = head + 1 + seqByOpId[opId] = seq + log += RemoteSyncOp( + seq = seq, + opId = opId, + kind = kind, + threadId = threadId, + turnId = turnId, + fromDevice = fromDevice, + memberId = "member-1", + clientAt = clientAt, + at = "2026-11-30T00:00:00Z", + ciphertext = Base64.getDecoder().decode(sealed.ct), + ) + } + + fun opCount(opId: String): Int = log.count { it.opId == opId } + + /** The newest accepted title for [threadId], opened from the sealed op. */ + fun titleOf(threadId: String): String? = threadOps + .lastOrNull { it.threadId == threadId && it.turnId == null } + ?.let { op -> + open(op)["title"]?.jsonPrimitive?.contentOrNull + } + + private fun accept(op: SealedOp): PushAck { + seqByOpId[op.opId]?.let { known -> return PushAck(op.opId, known, duplicate = true) } + val seq = head + 1 + seqByOpId[op.opId] = seq + log += RemoteSyncOp( + seq = seq, + opId = op.opId, + kind = op.kind, + threadId = op.threadId, + turnId = op.turnId, + fromDevice = device, + memberId = "member-1", + clientAt = op.clientAt, + at = "2026-11-30T00:00:00Z", + ciphertext = Base64.getDecoder().decode(op.ct), + ) + if (op.kind == SyncKind.THREAD_UPSERT) { + threadOps += op + } + return PushAck(op.opId, seq, duplicate = false) + } + + private fun open(op: SealedOp): JsonObject = SyncCodec(key).open( + RemoteSyncOp( + seq = 0, + opId = op.opId, + kind = op.kind, + threadId = op.threadId, + turnId = op.turnId, + fromDevice = device, + memberId = "member-1", + clientAt = op.clientAt, + at = "", + ciphertext = Base64.getDecoder().decode(op.ct), + ), + ) + } + + private companion object { + const val DEVICE = "d-1" + const val CURSOR_FILE = "sync-cursor.json" + val KEY = ByteArray(32) { index -> index.toByte() } + + fun turnPayload(role: String, text: String, at: Long): JsonObject = buildJsonObject { + put("role", role) + put("text", text) + put("at", at) + } + + fun threadPayload(title: String?, deletedAt: Long, clientAt: Long): JsonObject = buildJsonObject { + if (title != null) put("title", title) + put("deletedAt", deletedAt) + put("clientAt", clientAt) + } + } +} diff --git a/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/GatewayStateTest.kt b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/GatewayStateTest.kt index d66ddc126..9dc79e4ad 100644 --- a/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/GatewayStateTest.kt +++ b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/GatewayStateTest.kt @@ -75,4 +75,32 @@ class GatewayStateTest { job.cancel() runCurrent() } + + @Test + fun `the collector reports the live state to the sync trigger`() = runTest { + val states = MutableStateFlow(BackendState.Disconnected) + val config = RuntimeConfig() + val seen = mutableListOf() + + val job = launch { + collectGatewayState( + states = states, + session = session, + resolvePhone = { null }, + config = config, + onStatus = {}, + onState = { state -> seen += state }, + ) + } + runCurrent() + assertEquals(BackendState.Disconnected, seen.single()) + + states.value = BackendState.Live("pc-1", 0, emptyList()) + runCurrent() + assertEquals(2, seen.size) + assertEquals(true, seen.last() is BackendState.Live) + + job.cancel() + runCurrent() + } } diff --git a/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/protocol/handler/ConversationHandlerTest.kt b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/protocol/handler/ConversationHandlerTest.kt new file mode 100644 index 000000000..91a565143 --- /dev/null +++ b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/protocol/handler/ConversationHandlerTest.kt @@ -0,0 +1,95 @@ +package com.hopa.sidecar.protocol.handler + +import com.hopa.sidecar.protocol.Stdio +import com.hopa.sidecar.store.ChatStore +import java.io.ByteArrayOutputStream +import java.io.PrintStream +import java.nio.file.Files +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +/** A local write asks the sync host for a pass; a read does not. */ +class ConversationHandlerTest { + @Test + fun creating_renaming_and_deleting_announce_a_local_change() { + val store = ChatStore(Files.createTempDirectory("hopa-conversation").resolve("conversations.json")) + val changed = mutableListOf() + val handler = ConversationHandler(Stdio(), store) { id -> changed += id } + + capture { handler.handle("conversation.create", message("conversation.create", "id" to "r-1")) } + val created = store.list().single() + capture { + handler.handle( + "conversation.rename", + message( + "conversation.rename", + "id" to "r-2", + "conversationId" to created.id, + "title" to "Bills", + ), + ) + } + capture { + handler.handle( + "conversation.delete", + message("conversation.delete", "id" to "r-3", "conversationId" to created.id), + ) + } + + assertEquals(listOf(created.id, created.id, created.id), changed) + } + + @Test + fun opening_a_conversation_is_not_a_local_change() { + val store = ChatStore(Files.createTempDirectory("hopa-conversation-read").resolve("conversations.json")) + val changed = mutableListOf() + val handler = ConversationHandler(Stdio(), store) { id -> changed += id } + + capture { handler.handle("conversation.create", message("conversation.create", "id" to "r-1")) } + changed.clear() + val id = store.list().single().id + + val read = listOf( + "conversations.list", + "conversation.open", + "conversation.search", + "conversation.export", + ) + for (type in read) { + capture { + handler.handle( + type, + message(type, "id" to "r-2", "conversationId" to id, "query" to "x"), + ) + } + } + + assertEquals(emptyList(), changed) + } + + private fun message(type: String, vararg pairs: Pair): JsonObject = + buildJsonObject { + put("type", type) + pairs.forEach { (key, value) -> put(key, value) } + } + + private fun capture(block: () -> Unit) { + val original = System.out + val buffer = ByteArrayOutputStream() + System.setOut(PrintStream(buffer, true, "UTF-8")) + try { + block() + } finally { + System.setOut(original) + } + // Parse so a malformed reply fails here rather than in the window. + buffer.toString(Charsets.UTF_8) + .lineSequence() + .filter { it.isNotBlank() } + .forEach { Json.parseToJsonElement(it) } + } +} From 65db6b3abacd8956f652433ee9cbe3efc08d42cb Mon Sep 17 00:00:00 2001 From: aharonamir Date: Mon, 30 Nov 2026 02:30:59 +0200 Subject: [PATCH 23/58] Reload the open Windows chat when a sync pass changes it EngineHostClient raises ChatChanged from the chat.changed line, EngineSession forwards the conversation id, and the window re-reads the sidebar and the open conversation through the select path. A turn running locally is authoritative, so it is not reloaded underneath the person. Tests cover the frame and the reload of a conversation that is already current. Part of #32. --- .../Hopa.Windows.Tests/ChatControllerTests.cs | 24 +++++++++++ .../EngineHostClientBackendTests.cs | 13 ++++++ .../Hopa.Windows/Host/ChatController.cs | 11 +++++ .../Hopa.Windows/Host/EngineSession.cs | 4 ++ .../Engine/ChatChangedEventArgs.cs | 16 +++++++ .../Integrations/Engine/EngineHostClient.cs | 10 +++++ .../Integrations/Engine/EngineTransport.cs | 2 +- .../Hopa.Windows/Ui/Shell/MainWindow.Chat.cs | 42 +++++++++++++++++++ .../Ui/Shell/MainWindow.Connection.cs | 1 + 9 files changed, 122 insertions(+), 1 deletion(-) create mode 100644 apps/windows/Hopa.Windows/Integrations/Engine/ChatChangedEventArgs.cs diff --git a/apps/windows/Hopa.Windows.Tests/ChatControllerTests.cs b/apps/windows/Hopa.Windows.Tests/ChatControllerTests.cs index c7c42bbf2..0756ada9c 100644 --- a/apps/windows/Hopa.Windows.Tests/ChatControllerTests.cs +++ b/apps/windows/Hopa.Windows.Tests/ChatControllerTests.cs @@ -72,6 +72,30 @@ public async Task SelectKeepsTheComposerDraftPerConversation() Assert.Equal("draft", chat.ComposerText); } + [Fact] + public async Task ReloadRereadsTheConversationTheEngineChangedElsewhere() + { + var version = 1; + var engine = new FakeEngine + { + Open = id => new JsonObject + { + ["title"] = $"T{version}", + ["messages"] = new JsonArray(new JsonObject { ["role"] = "user", ["text"] = $"v{version}" }), + }, + }; + var chat = new ChatViewModel(); + var controller = new ChatController(engine, chat, new ConversationsViewModel()); + + Assert.Equal("T1", await controller.SelectAsync("a")); + Assert.Null(await controller.SelectAsync("a")); + + version = 2; + Assert.Equal("T2", await controller.ReloadAsync("a")); + Assert.Equal("a", controller.CurrentId); + Assert.Equal("v2", chat.Messages.Single().Text); + } + [Fact] public async Task CreateAddsTheRowTheEngineReturned() { diff --git a/apps/windows/Hopa.Windows.Tests/EngineHostClientBackendTests.cs b/apps/windows/Hopa.Windows.Tests/EngineHostClientBackendTests.cs index 2c5ec33ad..8d9295648 100644 --- a/apps/windows/Hopa.Windows.Tests/EngineHostClientBackendTests.cs +++ b/apps/windows/Hopa.Windows.Tests/EngineHostClientBackendTests.cs @@ -38,6 +38,19 @@ public async Task BackendPairResultIsDeliveredAsAnEvent() Assert.Equal("d", result["deviceId"]!.GetValue()); } + [Fact] + public async Task ChatChangedIsDeliveredWithTheConversationId() + { + var reader = new QueueReader(); + var client = new EngineHostClient(new EngineTransport(new LineWriter(), reader)); + var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + client.ChatChanged += (_, args) => received.TrySetResult(args.ConversationId); + + reader.Push("{\"type\":\"chat.changed\",\"body\":{\"conversationId\":\"c-1\"}}"); + + Assert.Equal("c-1", await received.Task.WaitAsync(TimeSpan.FromSeconds(1))); + } + [Fact] public async Task BackendStatusEventIsDeliveredAsAnEvent() { diff --git a/apps/windows/Hopa.Windows/Host/ChatController.cs b/apps/windows/Hopa.Windows/Host/ChatController.cs index 7176b322e..3fb13362c 100644 --- a/apps/windows/Hopa.Windows/Host/ChatController.cs +++ b/apps/windows/Hopa.Windows/Host/ChatController.cs @@ -110,6 +110,17 @@ public async Task SendAsync( return null; } + return await OpenAsync(id); + } + + /// + /// Re-reads a conversation the engine changed elsewhere (a peer's sync + /// pass). Same data path as a select; the open chat keeps its draft. + /// + public async Task ReloadAsync(string id) => await OpenAsync(id); + + private async Task OpenAsync(string id) + { if (CurrentId != null) { chat.Drafts[CurrentId] = chat.ComposerText; diff --git a/apps/windows/Hopa.Windows/Host/EngineSession.cs b/apps/windows/Hopa.Windows/Host/EngineSession.cs index 009173a81..60bb01c56 100644 --- a/apps/windows/Hopa.Windows/Host/EngineSession.cs +++ b/apps/windows/Hopa.Windows/Host/EngineSession.cs @@ -19,6 +19,7 @@ public EngineSession() Client.ApprovalRequested += message => ApprovalRequested?.Invoke(message); Client.SessionUpdated += message => SessionUpdated?.Invoke(message); Client.StepReceived += message => StepReceived?.Invoke(message); + Client.ChatChanged += (_, args) => ChatChanged?.Invoke(args.ConversationId); } public EngineHostClient Client { get; } @@ -35,6 +36,9 @@ public EngineSession() public event Action? StepReceived; + /// A conversation changed on the engine (a sync pass); only its id. + public event Action? ChatChanged; + public async ValueTask DisposeAsync() { await Client.DisposeAsync(); diff --git a/apps/windows/Hopa.Windows/Integrations/Engine/ChatChangedEventArgs.cs b/apps/windows/Hopa.Windows/Integrations/Engine/ChatChangedEventArgs.cs new file mode 100644 index 000000000..7f5e4cbde --- /dev/null +++ b/apps/windows/Hopa.Windows/Integrations/Engine/ChatChangedEventArgs.cs @@ -0,0 +1,16 @@ +namespace Hopa.Windows.Integrations.Engine; + +/// +/// A sync pass changed one conversation on this PC (a turn, a title or a +/// tombstone arrived from a peer). Only the id travels; message text never does. +/// +public sealed class ChatChangedEventArgs : EventArgs +{ + public ChatChangedEventArgs(string conversationId) + { + ConversationId = conversationId; + } + + /// The thread the engine changed; the window reloads the row it shows. + public string ConversationId { get; } +} diff --git a/apps/windows/Hopa.Windows/Integrations/Engine/EngineHostClient.cs b/apps/windows/Hopa.Windows/Integrations/Engine/EngineHostClient.cs index c43236dd0..f2c4d2535 100644 --- a/apps/windows/Hopa.Windows/Integrations/Engine/EngineHostClient.cs +++ b/apps/windows/Hopa.Windows/Integrations/Engine/EngineHostClient.cs @@ -39,6 +39,9 @@ public sealed partial class EngineHostClient : IAsyncDisposable, IChatEngine /// The engine's gateway status changed (paired, online, phone). public event Action? BackendStatusChanged; + /// A sync pass changed one conversation; only its id is carried. + public event EventHandler? ChatChanged; + public EngineHostClient() { var host = EngineHostProcess.Start(); @@ -462,6 +465,13 @@ private void OnMessage(JsonObject message) break; case "backend.status": BackendStatusChanged?.Invoke(message); + break; + case "chat.changed": + if ((message["body"] as JsonObject)?["conversationId"]?.GetValue() is { Length: > 0 } conversationId) + { + ChatChanged?.Invoke(this, new ChatChangedEventArgs(conversationId)); + } + break; } } diff --git a/apps/windows/Hopa.Windows/Integrations/Engine/EngineTransport.cs b/apps/windows/Hopa.Windows/Integrations/Engine/EngineTransport.cs index 307b18962..3dcd79443 100644 --- a/apps/windows/Hopa.Windows/Integrations/Engine/EngineTransport.cs +++ b/apps/windows/Hopa.Windows/Integrations/Engine/EngineTransport.cs @@ -137,5 +137,5 @@ private bool TryComplete(string id, JsonObject message) private static bool IsEvent(string type) => type is "ready" or "log" or "device.request" or "browser.request" or "approval.request" or "session" or "step" - or "backend.qr" or "backend.pair.result" or "backend.status"; + or "backend.qr" or "backend.pair.result" or "backend.status" or "chat.changed"; } diff --git a/apps/windows/Hopa.Windows/Ui/Shell/MainWindow.Chat.cs b/apps/windows/Hopa.Windows/Ui/Shell/MainWindow.Chat.cs index 971d015c1..ec10cf082 100644 --- a/apps/windows/Hopa.Windows/Ui/Shell/MainWindow.Chat.cs +++ b/apps/windows/Hopa.Windows/Ui/Shell/MainWindow.Chat.cs @@ -176,6 +176,48 @@ private async Task SendFromComposerAsync() private void MarkSelected(string? id) => Sidebar.Model.MarkSelected(id); + /// + /// A sync pass changed on the engine. The + /// sidebar picks up a new title or a removed row, and the open chat is + /// re-read through the same path a select uses. A turn running here is + /// authoritative locally, so it is not reloaded underneath the person. + /// + private void OnChatChanged(string conversationId) + { + if (Dispatcher.HasShutdownStarted) + { + return; + } + + _ = Dispatcher.InvokeAsync(async () => + { + try + { + if (chatController == null) + { + return; + } + + await ReloadConversationsAsync(); + if (chatController.Running || chatController.CurrentId != conversationId) + { + return; + } + + if (await chatController.ReloadAsync(conversationId) is { } title) + { + TitleText.Text = title; + } + + Chat.ScrollToEnd(); + } + catch (Exception error) + { + Log($"error: {error.Message}"); + } + }); + } + protected override void OnPreviewKeyDown(KeyEventArgs e) { if ((Keyboard.Modifiers & ModifierKeys.Control) != 0) diff --git a/apps/windows/Hopa.Windows/Ui/Shell/MainWindow.Connection.cs b/apps/windows/Hopa.Windows/Ui/Shell/MainWindow.Connection.cs index d8d357bcb..c1220822f 100644 --- a/apps/windows/Hopa.Windows/Ui/Shell/MainWindow.Connection.cs +++ b/apps/windows/Hopa.Windows/Ui/Shell/MainWindow.Connection.cs @@ -47,6 +47,7 @@ private async Task ConnectCoreAsync() var executed = message["executed"]?.GetValue() == true; Log($"step {index}: {action} tier={tier} executed={executed}"); }; + started.ChatChanged += OnChatChanged; session = started; client = started.Client; From b6920cd788ba166f7a34e64f3eb5f804afef62ef Mon Sep 17 00:00:00 2001 From: aharonamir Date: Mon, 30 Nov 2026 02:45:04 +0200 Subject: [PATCH 24/58] Read one session snapshot per sync pass The pass loaded the session for the token and device, then loaded it again for the content key. A re-pair between the two reads sealed the old household's ops under the new household's key, and every other device would wedge on that seq. The key is now derived from the same BackendSession the token came from, so one pass can only ever describe one household; the test makes the second read return a different household and asserts the pass reads once, sends the first token and seals with the first key. Part of #32. --- .../hopa/sidecar/backend/BackendSyncHost.kt | 21 ++--- .../com/hopa/sidecar/startup/ProtocolMode.kt | 5 +- .../sidecar/backend/BackendSyncHostTest.kt | 93 +++++++++++++------ 3 files changed, 75 insertions(+), 44 deletions(-) diff --git a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/BackendSyncHost.kt b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/BackendSyncHost.kt index fd6cd76a5..d363a41d3 100644 --- a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/BackendSyncHost.kt +++ b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/BackendSyncHost.kt @@ -35,10 +35,11 @@ import kotlinx.serialization.json.put * The PC's half of sync v0: one pull-then-push pass against the household op * log, on the same [ChatStore] the chat already uses. * - * A pass is built from the stored session each time, so a sign-out, a token - * rotation or a re-pair takes effect on the next pass without a restart. The - * shared engine owns the wire rules; this class only maps [ChatStore] rows to - * its target, builds the local backlog and serialises passes. + * A pass reads the stored session once and derives the token, the device, the + * gateway URL and the content key from that one snapshot, so a re-pair can never + * seal one household's ops under another household's key. The shared engine owns + * the wire rules; this class only maps [ChatStore] rows to its target, builds the + * local backlog and serialises passes. * * Two local rules matter here, both mirrored from the phone: * - A title already recorded as synced is not sent again just because a message @@ -48,8 +49,7 @@ import kotlinx.serialization.json.put * older title can never undo a rename that has not been pushed yet. */ class BackendSyncHost( - private val sessions: BackendSessionStore, - private val contentKey: () -> ByteArray?, + private val sessions: () -> BackendSession?, private val chats: ChatStore, private val cursorFile: Path, private val notify: (String) -> Unit, @@ -125,10 +125,10 @@ class BackendSyncHost( } private suspend fun runPass(): Int { - val session = sessions.load() ?: return 0 + // One snapshot: the token and the key must describe the same household. + val session = sessions() ?: return 0 if (session.deviceId.isBlank() || session.accessToken.isBlank() || session.gatewayUrl.isBlank()) return 0 - val key = contentKey() ?: return 0 - if (key.size != CONTENT_KEY_BYTES) return 0 + val key = backendContentKey(session) ?: return 0 val cursorStore = SyncCursorFile(cursorFile) val start = cursorStore.read() @@ -349,9 +349,6 @@ class BackendSyncHost( /** Wait this long for the rest of a burst before one pass. */ const val DEBOUNCE_MS = 250L - /** The household key size; anything else is a broken session. */ - const val CONTENT_KEY_BYTES = 32 - /** The last-synced title per thread, beside the cursor. */ const val TITLES_FILE = "synced-titles.json" diff --git a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/startup/ProtocolMode.kt b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/startup/ProtocolMode.kt index 47b1bee20..4b476f67a 100644 --- a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/startup/ProtocolMode.kt +++ b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/startup/ProtocolMode.kt @@ -89,10 +89,7 @@ internal fun runProtocol(options: CliOptions) { val sessionPath = dataDir.resolve("backend-session.json") val sessionStore = BackendSessionStore(sessionPath) val sync = BackendSyncHost( - sessions = sessionStore, - // Read per pass, like the token: a re-pair with a new household key - // takes effect on the next pass without a restart. - contentKey = { sessionStore.load()?.let(::backendContentKey) }, + sessions = sessionStore::load, chats = store, cursorFile = dataDir.resolve("sync-cursor.json"), notify = { conversationId -> io.send(Protocol.chatChanged(conversationId)) }, diff --git a/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/BackendSyncHostTest.kt b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/BackendSyncHostTest.kt index 00657a68a..551ae5e77 100644 --- a/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/BackendSyncHostTest.kt +++ b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/BackendSyncHostTest.kt @@ -210,6 +210,32 @@ class BackendSyncHostTest { } } + @Test + fun `a pass reads one session snapshot so the key matches the token`() = runBlocking { + Harness().use { harness -> + val first = session(household = "h1", device = DEVICE, key = KEY) + val second = session(household = "h2", device = "d-2", key = OTHER_KEY) + var loads = 0 + val conversation = harness.chats.create() + harness.chats.append(conversation.id, "user", "hello") + + // A re-pair lands between two reads of the session file: the pass + // must not seal household A's ops under household B's key. + val host = harness.host( + sessionSource = { + loads += 1 + if (loads == 1) first else second + }, + ) + + assertEquals(0, host.syncNow()) + + assertEquals(1, loads) + assertEquals(listOf("token-h1"), harness.server.pullTokens) + assertTrue(harness.server.pushBatches.single().all { harness.server.opensWith(KEY, it) }) + } + } + private class Harness(signedIn: Boolean = true) : AutoCloseable { val dataDir: Path = Files.createTempDirectory("hopa-sync") val chats = ChatStore(dataDir.resolve("conversations.json")) @@ -220,24 +246,12 @@ class BackendSyncHostTest { init { if (signedIn) { - sessions.save( - BackendSession( - deviceId = DEVICE, - householdId = "h1", - accessToken = "a1", - refreshToken = "r1", - expiresAt = "2026-11-30T00:15:00Z", - gatewayUrl = "wss://hopa.test/v1/gateway", - contentKeyBase64 = Base64.getEncoder().encodeToString(KEY), - privateKeyBase64 = "cA==", - ), - ) + sessions.save(session()) } } - fun host(): BackendSyncHost = BackendSyncHost( - sessions = sessions, - contentKey = { KEY }, + fun host(sessionSource: (() -> BackendSession?)? = null): BackendSyncHost = BackendSyncHost( + sessions = sessionSource ?: sessions::load, chats = chats, cursorFile = dataDir.resolve(CURSOR_FILE), notify = { id -> notified += id }, @@ -257,6 +271,7 @@ class BackendSyncHostTest { private val seqByOpId = mutableMapOf() private val threadOps = mutableListOf() val pullAfters = mutableListOf() + val pullTokens = mutableListOf() val pushBatches = mutableListOf>() var pulls = 0 @@ -265,6 +280,7 @@ class BackendSyncHostTest { override suspend fun pull(token: String, baseUrl: String, after: Long, limit: Int): PullAnswer { pulls += 1 pullAfters += after + pullTokens += token val page = log.filter { it.seq > after }.sortedBy { it.seq }.take(limit) return PullAnswer( ops = page, @@ -335,19 +351,24 @@ class BackendSyncHostTest { return PushAck(op.opId, seq, duplicate = false) } - private fun open(op: SealedOp): JsonObject = SyncCodec(key).open( - RemoteSyncOp( - seq = 0, - opId = op.opId, - kind = op.kind, - threadId = op.threadId, - turnId = op.turnId, - fromDevice = device, - memberId = "member-1", - clientAt = op.clientAt, - at = "", - ciphertext = Base64.getDecoder().decode(op.ct), - ), + private fun open(op: SealedOp): JsonObject = SyncCodec(key).open(remote(op)) + + /** True when [op] was sealed under [key], i.e. the pass used this household. */ + fun opensWith(key: ByteArray, op: SealedOp): Boolean = runCatching { + SyncCodec(key).open(remote(op)) + }.isSuccess + + private fun remote(op: SealedOp): RemoteSyncOp = RemoteSyncOp( + seq = 0, + opId = op.opId, + kind = op.kind, + threadId = op.threadId, + turnId = op.turnId, + fromDevice = device, + memberId = "member-1", + clientAt = op.clientAt, + at = "", + ciphertext = Base64.getDecoder().decode(op.ct), ) } @@ -355,6 +376,22 @@ class BackendSyncHostTest { const val DEVICE = "d-1" const val CURSOR_FILE = "sync-cursor.json" val KEY = ByteArray(32) { index -> index.toByte() } + val OTHER_KEY = ByteArray(32) { index -> (index + 1).toByte() } + + fun session( + household: String = "h1", + device: String = DEVICE, + key: ByteArray = KEY, + ): BackendSession = BackendSession( + deviceId = device, + householdId = household, + accessToken = "token-$household", + refreshToken = "refresh-$household", + expiresAt = "2026-11-30T00:15:00Z", + gatewayUrl = "wss://hopa.test/v1/gateway", + contentKeyBase64 = Base64.getEncoder().encodeToString(key), + privateKeyBase64 = "cA==", + ) fun turnPayload(role: String, text: String, at: Long): JsonObject = buildJsonObject { put("role", role) From 2492bd609d2ad03c0f6cfd5e8a46215591385e6b Mon Sep 17 00:00:00 2001 From: aharonamir Date: Mon, 30 Nov 2026 02:48:14 +0200 Subject: [PATCH 25/58] Start a sync pass on every reconnect The host remembered that it had started sync and never forgot until the sidecar restarted, so a dropped socket and a new Live state pulled nothing and the server does not replay what a peer wrote while this PC was away. A small trigger now compares each link state with the previous one and starts a pass on every transition into Live; a presence re-emit of Live is not a reconnect and adds no pass. The test drives Disconnected to Live, a presence change, a drop through Connecting, then Live again, and expects exactly two passes. Part of #32. --- .../com/hopa/sidecar/backend/GatewayHost.kt | 36 +++++++++++-------- .../hopa/sidecar/backend/GatewayStateTest.kt | 30 +++++++++++----- 2 files changed, 44 insertions(+), 22 deletions(-) diff --git a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/GatewayHost.kt b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/GatewayHost.kt index 947315b7c..7a1c54b88 100644 --- a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/GatewayHost.kt +++ b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/GatewayHost.kt @@ -82,10 +82,6 @@ internal class GatewayHost( ) : GatewayStarter { private var current: CoroutineScope? = null - /** True once this start's link reached `Live` and the sync host was started. */ - @Volatile - private var syncStarted = false - /** The session [start] was given; null until then, so `paired` stays false. */ @Volatile private var activeSession: BackendSession? = null @@ -111,7 +107,6 @@ internal class GatewayHost( require(contentKey.size == CONTENT_KEY_BYTES) { "content key must be $CONTENT_KEY_BYTES bytes" } current?.cancel() sync?.stop() - syncStarted = false activeSession = session activePhoneId = null var credentials = BackendCredentials( @@ -180,6 +175,7 @@ internal class GatewayHost( // scope, so replacing a link also stops the old one reporting. val live = CoroutineScope(scope.coroutineContext + SupervisorJob(scope.coroutineContext[Job])) current = live + val syncTrigger = LiveSyncTrigger { sync?.start() } live.launch { collectGatewayState( states = link.state, @@ -192,15 +188,7 @@ internal class GatewayHost( }, config = config, onStatus = onStatus, - onState = { state -> - // One pass per connection: the pull reconciles everything a - // peer wrote while this PC was away. Later frames arrive as - // `sync.changed` and ask for their own pass. - if (state is BackendState.Live && !syncStarted) { - syncStarted = true - sync?.start() - } - }, + onState = syncTrigger::onState, ) } live.launch { gateway.runForever(live) } @@ -264,6 +252,26 @@ internal class GatewayHost( } } +/** + * Starts a sync pass whenever the gateway enters `Live`. + * + * A reconnect must pull again: the server does not replay what a peer wrote + * while this PC was offline, so a pass that ran only on the first connection + * would leave those ops invisible until someone happens to send `sync.changed`. + * A presence re-emit of `Live` is not a reconnect and does not add a pass. + */ +internal class LiveSyncTrigger(private val onConnected: () -> Unit) { + private var wasLive = false + + fun onState(state: BackendState) { + val live = state is BackendState.Live + if (live && !wasLive) { + onConnected() + } + wasLive = live + } +} + /** * Follows the link's [StateFlow], resolving the phone on `Live` and writing the * gateway flags and a `backend.status` event on every change. `paired` is always diff --git a/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/GatewayStateTest.kt b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/GatewayStateTest.kt index 9dc79e4ad..b3968c1c6 100644 --- a/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/GatewayStateTest.kt +++ b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/GatewayStateTest.kt @@ -77,28 +77,42 @@ class GatewayStateTest { } @Test - fun `the collector reports the live state to the sync trigger`() = runTest { + fun `each return to live starts another pass`() = runTest { val states = MutableStateFlow(BackendState.Disconnected) - val config = RuntimeConfig() - val seen = mutableListOf() + val passes = mutableListOf() + val trigger = LiveSyncTrigger { passes += Unit } val job = launch { collectGatewayState( states = states, session = session, resolvePhone = { null }, - config = config, + config = RuntimeConfig(), onStatus = {}, - onState = { state -> seen += state }, + onState = trigger::onState, ) } runCurrent() - assertEquals(BackendState.Disconnected, seen.single()) states.value = BackendState.Live("pc-1", 0, emptyList()) runCurrent() - assertEquals(2, seen.size) - assertEquals(true, seen.last() is BackendState.Live) + assertEquals(1, passes.size) + + // A presence change re-emits Live; that is not a reconnect. + states.value = BackendState.Live("pc-1", 0, listOf("phone-1")) + runCurrent() + assertEquals(1, passes.size) + + states.value = BackendState.Failed("closed", false) + runCurrent() + states.value = BackendState.Connecting + runCurrent() + assertEquals(1, passes.size) + + // A new socket after a drop must reconcile what was written while away. + states.value = BackendState.Live("pc-1", 0, emptyList()) + runCurrent() + assertEquals(2, passes.size) job.cancel() runCurrent() From 003f25d240f1b6a3516a97ecef8f42f106592073 Mon Sep 17 00:00:00 2001 From: aharonamir Date: Mon, 30 Nov 2026 02:51:21 +0200 Subject: [PATCH 26/58] Never cancel a running sync pass for a trigger Every trigger cancelled the pending job, including a pass already inside its pull; with the cursor persisted only after the pull returns, a stream of sync.changed frames could starve the first sync forever. A trigger during the debounce or a pass now records one follow-up pass and leaves the pass alone, and stop() lets an in-flight pass finish too. The test holds the first pull open, fires three triggers, then expects two completed pulls, two total pulls and zero cancellations. Part of #32. --- .../hopa/sidecar/backend/BackendSyncHost.kt | 62 ++++++++++++++----- .../sidecar/backend/BackendSyncHostTest.kt | 56 ++++++++++++++++- 2 files changed, 101 insertions(+), 17 deletions(-) diff --git a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/BackendSyncHost.kt b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/BackendSyncHost.kt index d363a41d3..b5fc01809 100644 --- a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/BackendSyncHost.kt +++ b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/BackendSyncHost.kt @@ -18,6 +18,7 @@ import com.hopa.contracts.chat.ChatMessage import com.hopa.contracts.chat.Conversation import com.hopa.sidecar.store.ChatStore import java.nio.file.Path +import kotlin.coroutines.coroutineContext import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -63,6 +64,8 @@ class BackendSyncHost( @Volatile private var running = false private var pending: Job? = null + private var inPass = false + private var again = false private val titlesFile: Path = cursorFile.resolveSibling(TITLES_FILE) @@ -90,8 +93,11 @@ class BackendSyncHost( fun stop() { running = false synchronized(triggers) { - pending?.cancel() - pending = null + again = false + if (!inPass) { + pending?.cancel() + pending = null + } } } @@ -102,28 +108,52 @@ class BackendSyncHost( fun onLocalChange(@Suppress("UNUSED_PARAMETER") conversationId: String) = schedule() /** - * Coalesces triggers into one pass: a trigger inside the window replaces the - * pending one, so a burst of writes costs one pull. + * Coalesces triggers into passes. A trigger inside the debounce window or + * during a pass never aborts that pass: it marks exactly one more pass to run + * when the current one finishes, so a stream of `sync.changed` frames cannot + * starve the pull it interrupted. */ private fun schedule() { - if (!running) { - return - } synchronized(triggers) { - pending?.cancel() - pending = scope.launch { - delay(DEBOUNCE_MS) - try { - syncNow() - } catch (cancelled: CancellationException) { - throw cancelled - } catch (_: Exception) { - // A pass reports nothing; a trigger never crashes the scope. + if (!running) { + return + } + if (pending?.isActive == true) { + again = true + return + } + pending = scope.launch { runScheduled() } + } + } + + private suspend fun runScheduled() { + val self = coroutineContext[Job] + try { + delay(DEBOUNCE_MS) + do { + synchronized(triggers) { again = false } + runOnce() + } while (synchronized(triggers) { again && running }) + } finally { + synchronized(triggers) { + inPass = false + if (pending === self) { + pending = null } } } } + /** One scheduled pass; a failure is reported by [syncNow], never by a trigger. */ + private suspend fun runOnce() { + synchronized(triggers) { inPass = true } + try { + syncNow() + } finally { + synchronized(triggers) { inPass = false } + } + } + private suspend fun runPass(): Int { // One snapshot: the token and the key must describe the same household. val session = sessions() ?: return 0 diff --git a/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/BackendSyncHostTest.kt b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/BackendSyncHostTest.kt index 551ae5e77..97a01633b 100644 --- a/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/BackendSyncHostTest.kt +++ b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/BackendSyncHostTest.kt @@ -14,10 +14,13 @@ import com.hopa.sidecar.store.ChatStore import java.nio.file.Files import java.nio.file.Path import java.util.Base64 +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.buildJsonObject @@ -236,6 +239,37 @@ class BackendSyncHostTest { } } + @Test + fun `triggers during a slow pass add one follow-up pass and cancel nothing`() = runBlocking { + Harness().use { harness -> + val gate = CompletableDeferred() + harness.server.pullGate = gate + val host = harness.host(scope = this) + host.start() + + // The first pass is suspended inside its pull. + harness.server.firstPullStarted.await() + repeat(3) { host.onRemoteChanged() } + gate.complete(Unit) + + awaitUntil(timeoutMs = 3_000) { harness.server.completedPulls == 2 } + delay(500) + assertEquals(2, harness.server.pulls) + assertEquals(2, harness.server.completedPulls) + assertEquals(0, harness.server.cancelledPulls) + host.stop() + } + } + + private suspend fun awaitUntil(timeoutMs: Long, condition: () -> Boolean) { + val deadline = System.currentTimeMillis() + timeoutMs + while (System.currentTimeMillis() < deadline) { + if (condition()) return + delay(10) + } + throw AssertionError("condition not met within ${timeoutMs}ms") + } + private class Harness(signedIn: Boolean = true) : AutoCloseable { val dataDir: Path = Files.createTempDirectory("hopa-sync") val chats = ChatStore(dataDir.resolve("conversations.json")) @@ -250,7 +284,10 @@ class BackendSyncHostTest { } } - fun host(sessionSource: (() -> BackendSession?)? = null): BackendSyncHost = BackendSyncHost( + fun host( + sessionSource: (() -> BackendSession?)? = null, + scope: CoroutineScope = this.scope, + ): BackendSyncHost = BackendSyncHost( sessions = sessionSource ?: sessions::load, chats = chats, cursorFile = dataDir.resolve(CURSOR_FILE), @@ -274,6 +311,11 @@ class BackendSyncHostTest { val pullTokens = mutableListOf() val pushBatches = mutableListOf>() var pulls = 0 + var completedPulls = 0 + var cancelledPulls = 0 + var pullGate: CompletableDeferred? = null + val firstPullStarted = CompletableDeferred() + private var heldOnce = false private val head: Long get() = log.maxOfOrNull { it.seq } ?: 0L @@ -281,7 +323,19 @@ class BackendSyncHostTest { pulls += 1 pullAfters += after pullTokens += token + firstPullStarted.complete(Unit) + val gate = pullGate + if (gate != null && !heldOnce) { + heldOnce = true + try { + gate.await() + } catch (cancelled: CancellationException) { + cancelledPulls += 1 + throw cancelled + } + } val page = log.filter { it.seq > after }.sortedBy { it.seq }.take(limit) + completedPulls += 1 return PullAnswer( ops = page, hasMore = page.isNotEmpty() && log.any { it.seq > page.last().seq }, From 1bc7a67de1e2cdf3d5bbb7283722c19f9fd4f4e0 Mon Sep 17 00:00:00 2001 From: aharonamir Date: Mon, 30 Nov 2026 02:55:49 +0200 Subject: [PATCH 27/58] Report the ops a pass applied even when its push fails syncNow returned 0 on any exception, so a pull that applied ops and a push that then failed looked like nothing happened, contradicting the documented return. A push failure is now handled beside the push and returns the pull's applied count; a failed pull still returns 0 because the engine never reported one. Every failure path logs one line with the exception class name only (pull, push, notify, missing key), never a message that could quote plaintext. Tests cover the push and pull paths and their log lines. Part of #32. --- .../hopa/sidecar/backend/BackendSyncHost.kt | 49 +++++++++++++++---- .../com/hopa/sidecar/startup/ProtocolMode.kt | 1 + .../sidecar/backend/BackendSyncHostTest.kt | 34 +++++++++++++ 3 files changed, 75 insertions(+), 9 deletions(-) diff --git a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/BackendSyncHost.kt b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/BackendSyncHost.kt index b5fc01809..76a124322 100644 --- a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/BackendSyncHost.kt +++ b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/BackendSyncHost.kt @@ -48,12 +48,16 @@ import kotlinx.serialization.json.put * under a new op id. * - An op this PC wrote is inert when it comes back on a later pull, so our own * older title can never undo a rename that has not been pushed yet. + * + * A failure logs one line with the exception's class name only, never a message, + * a title or a turn: those could carry plaintext. */ class BackendSyncHost( private val sessions: () -> BackendSession?, private val chats: ChatStore, private val cursorFile: Path, private val notify: (String) -> Unit, + private val log: (String) -> Unit = {}, private val http: SyncHttp = OkHttpSyncHttp(), private val scope: CoroutineScope, ) { @@ -69,16 +73,21 @@ class BackendSyncHost( private val titlesFile: Path = cursorFile.resolveSibling(TITLES_FILE) - /** One pull-then-push pass; waits for a pass already in flight. */ + /** + * One pull-then-push pass; waits for a pass already in flight. + * + * @return the ops this pass applied. A failed push does not hide them; a + * pull that failed returns 0, because the engine never reported a count. + */ suspend fun syncNow(): Int = withContext(Dispatchers.IO) { try { pass.withLock { runPass() } } catch (cancelled: CancellationException) { throw cancelled - } catch (_: Exception) { - // A store read, a bad tag or a transport reset: the cursor and the - // applied rows are the only durable result. Nothing is logged, - // because a failure can quote plaintext. + } catch (failure: Exception) { + // A store read, a bad tag or a transport reset. Nothing is logged + // with the message, because it could quote plaintext. + log("sync pass failed (${failure.javaClass.simpleName})") 0 } } @@ -158,7 +167,11 @@ class BackendSyncHost( // One snapshot: the token and the key must describe the same household. val session = sessions() ?: return 0 if (session.deviceId.isBlank() || session.accessToken.isBlank() || session.gatewayUrl.isBlank()) return 0 - val key = backendContentKey(session) ?: return 0 + val key = backendContentKey(session) + if (key == null) { + log("sync pass skipped: the stored session has no usable content key") + return 0 + } val cursorStore = SyncCursorFile(cursorFile) val start = cursorStore.read() @@ -181,7 +194,14 @@ class BackendSyncHost( baseUrl = { BackendUrls.httpBase(session.gatewayUrl) }, ) - val report = engine.pull() + val report = try { + engine.pull() + } catch (cancelled: CancellationException) { + throw cancelled + } catch (failure: Exception) { + log("sync pull failed (${failure.javaClass.simpleName})") + return 0 + } // The pull is done: persist its cursor and announce what it applied even // if the push below fails, or the next pass would see duplicates and @@ -193,14 +213,25 @@ class BackendSyncHost( titlesStore.write(recordedTitles) } for (id in target.changed) { - runCatching { notify(id) } + runCatching { notify(id) }.onFailure { failed -> + log("sync notify failed (${failed.javaClass.simpleName})") + } } val backlog = backlog(session.deviceId, recordedTitles) if (backlog.drafts.isEmpty()) { return report.applied } - val answer = engine.push(backlog.drafts) + val answer = try { + engine.push(backlog.drafts) + } catch (cancelled: CancellationException) { + throw cancelled + } catch (failure: Exception) { + // What the pull applied still stands (and its cursor is persisted), + // so the caller sees that count instead of a misleading zero. + log("sync push failed (${failure.javaClass.simpleName})") + return report.applied + } // Only an acknowledged op proves the server holds the title. A duplicate // ack means it already did. var recorded = false diff --git a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/startup/ProtocolMode.kt b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/startup/ProtocolMode.kt index 4b476f67a..97fb04a3b 100644 --- a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/startup/ProtocolMode.kt +++ b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/startup/ProtocolMode.kt @@ -93,6 +93,7 @@ internal fun runProtocol(options: CliOptions) { chats = store, cursorFile = dataDir.resolve("sync-cursor.json"), notify = { conversationId -> io.send(Protocol.chatChanged(conversationId)) }, + log = io::log, scope = backendScope, ) val runner = EngineTaskRunner( diff --git a/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/BackendSyncHostTest.kt b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/BackendSyncHostTest.kt index 97a01633b..123e3134f 100644 --- a/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/BackendSyncHostTest.kt +++ b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/BackendSyncHostTest.kt @@ -239,6 +239,34 @@ class BackendSyncHostTest { } } + @Test + fun `a failed push still reports the ops the pull applied`() = runBlocking { + Harness().use { harness -> + harness.server.seed( + SyncKind.TURN_APPEND, + "c-1", + "m-1", + turnPayload("user", "hello", 10), + opId = "m-1", + clientAt = 10, + ) + harness.server.pushFailure = IllegalStateException("offline") + + assertEquals(1, harness.host().syncNow()) + assertTrue(harness.logs.any { it.contains("sync push failed (IllegalStateException)") }) + } + } + + @Test + fun `a failed pull logs its class and applies nothing`() = runBlocking { + Harness().use { harness -> + harness.server.pullFailure = IllegalArgumentException("bad tag") + + assertEquals(0, harness.host().syncNow()) + assertTrue(harness.logs.any { it.contains("sync pull failed (IllegalArgumentException)") }) + } + } + @Test fun `triggers during a slow pass add one follow-up pass and cancel nothing`() = runBlocking { Harness().use { harness -> @@ -275,6 +303,7 @@ class BackendSyncHostTest { val chats = ChatStore(dataDir.resolve("conversations.json")) val server = FakeSyncServer() val notified = mutableListOf() + val logs = mutableListOf() private val sessions = BackendSessionStore(dataDir.resolve("backend-session.json")) private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) @@ -292,6 +321,7 @@ class BackendSyncHostTest { chats = chats, cursorFile = dataDir.resolve(CURSOR_FILE), notify = { id -> notified += id }, + log = { line -> logs += line }, http = server, scope = scope, ) @@ -314,12 +344,15 @@ class BackendSyncHostTest { var completedPulls = 0 var cancelledPulls = 0 var pullGate: CompletableDeferred? = null + var pushFailure: Exception? = null + var pullFailure: Exception? = null val firstPullStarted = CompletableDeferred() private var heldOnce = false private val head: Long get() = log.maxOfOrNull { it.seq } ?: 0L override suspend fun pull(token: String, baseUrl: String, after: Long, limit: Int): PullAnswer { + pullFailure?.let { throw it } pulls += 1 pullAfters += after pullTokens += token @@ -344,6 +377,7 @@ class BackendSyncHostTest { } override suspend fun push(token: String, baseUrl: String, ops: List): PushAnswer { + pushFailure?.let { throw it } pushBatches += ops return PushAnswer(head = head, accepted = ops.map(::accept)) } From eaa1be4b043072ef8f5d87e97999a00f2fa41fc3 Mon Sep 17 00:00:00 2001 From: aharonamir Date: Mon, 30 Nov 2026 02:59:54 +0200 Subject: [PATCH 28/58] Hold the sync state when a merge did not reach disk mergeRemote saved through a runCatching that swallowed every I/O error, and the pass then advanced the cursor; a restart lost the merged ops and never pulled them again. ChatStore now keeps the last write's failure, and a pass that sees one holds both the cursor and the last-synced title record, logging the exception class and the held seq. A failed cursor or title write is logged too. The test points the store at a directory, so every save fails, and asserts the cursor stays at 0, no title record is written and the failure is logged. Part of #32. --- .../hopa/sidecar/backend/BackendSyncHost.kt | 29 ++++++++++---- .../com/hopa/sidecar/store/ChatStore.kt | 13 ++++++- .../sidecar/backend/BackendSyncHostTest.kt | 39 +++++++++++++++++++ 3 files changed, 71 insertions(+), 10 deletions(-) diff --git a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/BackendSyncHost.kt b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/BackendSyncHost.kt index 76a124322..23a473b65 100644 --- a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/BackendSyncHost.kt +++ b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/BackendSyncHost.kt @@ -205,12 +205,23 @@ class BackendSyncHost( // The pull is done: persist its cursor and announce what it applied even // if the push below fails, or the next pass would see duplicates and - // never announce those rows. - if (cursor.read() != start) { - cursorStore.write(cursor.read()) - } - if (recordedTitles != storedTitles) { - titlesStore.write(recordedTitles) + // never announce those rows. A merge that did not reach disk must not be + // covered by a cursor that did: hold both records so the ops are pulled + // again after a restart. + val saveFailure = chats.lastSaveFailure + if (saveFailure != null) { + log("sync merge not saved (${saveFailure.javaClass.simpleName}); state held at $start") + } else { + if (cursor.read() != start) { + runCatching { cursorStore.write(cursor.read()) }.onFailure { failed -> + log("sync cursor write failed (${failed.javaClass.simpleName})") + } + } + if (recordedTitles != storedTitles) { + runCatching { titlesStore.write(recordedTitles) }.onFailure { failed -> + log("sync titles write failed (${failed.javaClass.simpleName})") + } + } } for (id in target.changed) { runCatching { notify(id) }.onFailure { failed -> @@ -242,8 +253,10 @@ class BackendSyncHost( recorded = true } } - if (recorded) { - titlesStore.write(recordedTitles) + if (recorded && saveFailure == null) { + runCatching { titlesStore.write(recordedTitles) }.onFailure { failed -> + log("sync titles write failed (${failed.javaClass.simpleName})") + } } return report.applied } diff --git a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/store/ChatStore.kt b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/store/ChatStore.kt index 73ebd7bb5..5719ebdc2 100644 --- a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/store/ChatStore.kt +++ b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/store/ChatStore.kt @@ -19,6 +19,15 @@ class ChatStore(path: Path) { } private var conversations: MutableList = load() + /** + * The last write's failure, or null when it landed. Sync reads it after a + * pull: a merge that did not reach disk must not be covered by an advanced + * cursor, or a restart would lose the op and never pull it again. + */ + @Volatile + var lastSaveFailure: Throwable? = null + private set + @Synchronized fun list(includeArchived: Boolean = false): List = conversations @@ -207,10 +216,10 @@ class ChatStore(path: Path) { } private fun save() { - runCatching { + lastSaveFailure = runCatching { Files.createDirectories(file.parent) Files.writeString(file, json.encodeToString(ListSerializer(Conversation.serializer()), conversations)) - } + }.exceptionOrNull() } private companion object { diff --git a/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/BackendSyncHostTest.kt b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/BackendSyncHostTest.kt index 123e3134f..5518b11e1 100644 --- a/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/BackendSyncHostTest.kt +++ b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/BackendSyncHostTest.kt @@ -22,12 +22,16 @@ import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject 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 import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertNotEquals import org.junit.jupiter.api.Assertions.assertNull import org.junit.jupiter.api.Assertions.assertTrue @@ -257,6 +261,30 @@ class BackendSyncHostTest { } } + @Test + fun `a merge that could not be saved holds the cursor and the title record`() = runBlocking { + Harness().use { harness -> + // A directory where the store file must be: every save() fails. + val blocked = Files.createTempDirectory("hopa-sync-blocked") + Files.createDirectories(blocked.resolve("conversations.json")) + val chats = ChatStore(blocked.resolve("conversations.json")) + harness.server.seed( + SyncKind.THREAD_UPSERT, + "c-1", + null, + threadPayload("Peer", deletedAt = 0, clientAt = 10), + opId = "peer-title", + clientAt = 10, + ) + + assertEquals(1, harness.host(chats = chats).syncNow()) + + assertEquals(0L, cursorSeq(harness.dataDir.resolve(CURSOR_FILE))) + assertFalse(Files.exists(harness.dataDir.resolve(TITLES_FILE))) + assertTrue(harness.logs.any { it.startsWith("sync merge not saved (") }) + } + } + @Test fun `a failed pull logs its class and applies nothing`() = runBlocking { Harness().use { harness -> @@ -315,6 +343,7 @@ class BackendSyncHostTest { fun host( sessionSource: (() -> BackendSession?)? = null, + chats: ChatStore = this.chats, scope: CoroutineScope = this.scope, ): BackendSyncHost = BackendSyncHost( sessions = sessionSource ?: sessions::load, @@ -463,9 +492,19 @@ class BackendSyncHostTest { private companion object { const val DEVICE = "d-1" const val CURSOR_FILE = "sync-cursor.json" + const val TITLES_FILE = "synced-titles.json" val KEY = ByteArray(32) { index -> index.toByte() } val OTHER_KEY = ByteArray(32) { index -> (index + 1).toByte() } + /** The seq in a cursor file, or 0 when the pass never wrote one. */ + fun cursorSeq(file: Path): Long { + if (!Files.exists(file)) return 0L + return Json.parseToJsonElement(Files.readString(file)).jsonObject["seq"] + ?.jsonPrimitive + ?.longOrNull + ?: 0L + } + fun session( household: String = "h1", device: String = DEVICE, From a8c974dca3ef76b02cb628ea884ebb38970ab5fb Mon Sep 17 00:00:00 2001 From: aharonamir Date: Mon, 30 Nov 2026 09:39:23 +0200 Subject: [PATCH 29/58] Reset the sync state when the household changes The cursor and the last-synced titles survived a re-pair, so the new household's earliest ops sat under a stale seq and were never pulled, while local titles looked already sent. Both files now carry the household and device they belong to; a mismatch starts at zero, clears the title record and logs the reset, and the seq is written back with its new owner. The test leaves a previous build's cursor at 5 and a bare title map, then pairs to a new household and expects a pull from 0, a title push and the new owner on disk. Part of #32. --- .../hopa/sidecar/backend/BackendSyncHost.kt | 31 +++++++-- .../hopa/sidecar/backend/SyncStateFiles.kt | 68 ++++++++++++------- .../sidecar/backend/BackendSyncHostTest.kt | 39 ++++++++++- 3 files changed, 104 insertions(+), 34 deletions(-) diff --git a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/BackendSyncHost.kt b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/BackendSyncHost.kt index 23a473b65..f4b84fccf 100644 --- a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/BackendSyncHost.kt +++ b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/BackendSyncHost.kt @@ -174,10 +174,27 @@ class BackendSyncHost( } val cursorStore = SyncCursorFile(cursorFile) - val start = cursorStore.read() - val cursor = PassCursor(start) val titlesStore = SyncedTitlesFile(titlesFile) - val storedTitles = titlesStore.read() + val storedSeq = cursorStore.read(session.householdId, session.deviceId) + val start: Long + val storedTitles: Map + if (storedSeq == null) { + // A re-pair: the previous household's seq sits on top of this one's + // earliest ops, and its titles are not this household's history. + start = 0 + storedTitles = emptyMap() + runCatching { + cursorStore.write(0, session.householdId, session.deviceId) + titlesStore.write(session.householdId, emptyMap()) + }.onFailure { failed -> + log("sync state reset failed (${failed.javaClass.simpleName})") + } + log("sync state reset: the stored household is not this one") + } else { + start = storedSeq + storedTitles = titlesStore.read(session.householdId) + } + val cursor = PassCursor(start) val recordedTitles = storedTitles.toMutableMap() val target = ChatTarget(chats) { threadId, title -> @@ -213,12 +230,14 @@ class BackendSyncHost( log("sync merge not saved (${saveFailure.javaClass.simpleName}); state held at $start") } else { if (cursor.read() != start) { - runCatching { cursorStore.write(cursor.read()) }.onFailure { failed -> + runCatching { + cursorStore.write(cursor.read(), session.householdId, session.deviceId) + }.onFailure { failed -> log("sync cursor write failed (${failed.javaClass.simpleName})") } } if (recordedTitles != storedTitles) { - runCatching { titlesStore.write(recordedTitles) }.onFailure { failed -> + runCatching { titlesStore.write(session.householdId, recordedTitles) }.onFailure { failed -> log("sync titles write failed (${failed.javaClass.simpleName})") } } @@ -254,7 +273,7 @@ class BackendSyncHost( } } if (recorded && saveFailure == null) { - runCatching { titlesStore.write(recordedTitles) }.onFailure { failed -> + runCatching { titlesStore.write(session.householdId, recordedTitles) }.onFailure { failed -> log("sync titles write failed (${failed.javaClass.simpleName})") } } diff --git a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/SyncStateFiles.kt b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/SyncStateFiles.kt index 006987a58..fbb3b7880 100644 --- a/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/SyncStateFiles.kt +++ b/apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/SyncStateFiles.kt @@ -1,6 +1,5 @@ package com.hopa.sidecar.backend -import com.hopa.backend.sync.client.SyncCursor import java.nio.file.AtomicMoveNotSupportedException import java.nio.file.Files import java.nio.file.Path @@ -9,15 +8,24 @@ import java.nio.file.attribute.PosixFileAttributeView import java.nio.file.attribute.PosixFilePermissions import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json -import kotlinx.serialization.json.JsonObject -import kotlinx.serialization.json.JsonPrimitive -import kotlinx.serialization.json.contentOrNull -import kotlinx.serialization.json.jsonObject -import kotlinx.serialization.json.jsonPrimitive -/** The one number the household op log needs: `{"seq":N}`. */ +/** + * The position in one household's op log: `{"seq":N,"householdId":"…","deviceId":"…"}`. + * The owner is what makes a stale file harmless after a re-pair. + */ +@Serializable +private data class CursorState( + val seq: Long = 0, + val householdId: String = "", + val deviceId: String = "", +) + +/** The titles this PC last synced in one household, with that household's id. */ @Serializable -private data class CursorState(val seq: Long = 0) +private data class TitlesState( + val householdId: String = "", + val titles: Map = emptyMap(), +) private val json = Json { ignoreUnknownKeys = true @@ -25,39 +33,47 @@ private val json = Json { /** * The seq this PC applied up to, written atomically like the session file. It - * holds no title, message or key, only the position. + * holds no title, message or key, only the position and its owner. */ -internal class SyncCursorFile(private val file: Path) : SyncCursor { - override fun read(): Long { +internal class SyncCursorFile(private val file: Path) { + /** + * The stored seq for this household and device, or null when the file + * belongs to another pairing — a different household's seq means nothing. + */ + fun read(householdId: String, deviceId: String): Long? { if (!Files.exists(file)) return 0 - return runCatching { - json.decodeFromString(CursorState.serializer(), Files.readString(file)).seq.coerceAtLeast(0) - }.getOrDefault(0) + val state = runCatching { + json.decodeFromString(CursorState.serializer(), Files.readString(file)) + }.getOrNull() ?: return 0 + if (state.householdId != householdId || state.deviceId != deviceId) return null + return state.seq.coerceAtLeast(0) } - override fun write(seq: Long) { - writeAtomically(file, json.encodeToString(CursorState.serializer(), CursorState(seq)), ownerOnly = false) + fun write(seq: Long, householdId: String, deviceId: String) { + val state = CursorState(seq = seq, householdId = householdId, deviceId = deviceId) + writeAtomically(file, json.encodeToString(CursorState.serializer(), state), ownerOnly = false) } } /** * The title this PC last synced per thread. A title that differs from its entry * is an unsent local edit; a title applied from the log is recorded here so the - * next pass does not echo it back. + * next pass does not echo it back. Titles from another household are not this + * household's history and are ignored. */ internal class SyncedTitlesFile(private val file: Path) { - fun read(): Map { + fun read(householdId: String): Map { if (!Files.exists(file)) return emptyMap() - return runCatching { - json.parseToJsonElement(Files.readString(file)).jsonObject - .mapValues { (_, value) -> value.jsonPrimitive.contentOrNull.orEmpty() } - .filterValues { it.isNotBlank() } - }.getOrDefault(emptyMap()) + val state = runCatching { + json.decodeFromString(TitlesState.serializer(), Files.readString(file)) + }.getOrNull() ?: return emptyMap() + if (state.householdId != householdId) return emptyMap() + return state.titles.filterValues { it.isNotBlank() } } - fun write(titles: Map) { - val jsonObject = JsonObject(titles.mapValues { (_, title) -> JsonPrimitive(title) }) - writeAtomically(file, jsonObject.toString(), ownerOnly = true) + fun write(householdId: String, titles: Map) { + val state = TitlesState(householdId = householdId, titles = titles) + writeAtomically(file, json.encodeToString(TitlesState.serializer(), state), ownerOnly = true) } } diff --git a/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/BackendSyncHostTest.kt b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/BackendSyncHostTest.kt index 5518b11e1..60d6fbdcd 100644 --- a/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/BackendSyncHostTest.kt +++ b/apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/backend/BackendSyncHostTest.kt @@ -108,8 +108,10 @@ class BackendSyncHostTest { ) assertEquals(1, harness.host().syncNow()) - val cursorText = Files.readString(harness.dataDir.resolve(CURSOR_FILE)) - assertEquals("{\"seq\":1}", cursorText.trim()) + val cursorPath = harness.dataDir.resolve(CURSOR_FILE) + assertEquals(1L, cursorSeq(cursorPath)) + assertEquals("h1", ownerOf(cursorPath)) + assertEquals(DEVICE, deviceOf(cursorPath)) // A new process over the same files asks after the applied seq. harness.host().syncNow() @@ -261,6 +263,28 @@ class BackendSyncHostTest { } } + @Test + fun `a re-pair to another household starts from zero and forgets the titles`() = runBlocking { + Harness().use { harness -> + // State left by the previous household in this PC's data dir. + Files.writeString(harness.dataDir.resolve(CURSOR_FILE), """{"seq":5}""") + Files.writeString(harness.dataDir.resolve(TITLES_FILE), """{"c-1":"Trip"}""") + harness.chats.mergeRemote("c-1", "Trip", 0, 1, ChatMessage("m-1", "user", "hi", 1)) + val second = session(household = "h-new", device = "d-new") + + harness.host(sessionSource = { second }).syncNow() + + assertEquals(listOf(0L), harness.server.pullAfters) + assertTrue( + harness.server.pushBatches.single().any { + it.kind == SyncKind.THREAD_UPSERT && it.threadId == "c-1" + }, + ) + assertEquals("h-new", ownerOf(harness.dataDir.resolve(CURSOR_FILE))) + assertEquals("d-new", deviceOf(harness.dataDir.resolve(CURSOR_FILE))) + } + } + @Test fun `a merge that could not be saved holds the cursor and the title record`() = runBlocking { Harness().use { harness -> @@ -505,6 +529,17 @@ class BackendSyncHostTest { ?: 0L } + fun ownerOf(file: Path): String? = cursorField(file, "householdId") + + fun deviceOf(file: Path): String? = cursorField(file, "deviceId") + + private fun cursorField(file: Path, key: String): String? { + if (!Files.exists(file)) return null + return Json.parseToJsonElement(Files.readString(file)).jsonObject[key] + ?.jsonPrimitive + ?.contentOrNull + } + fun session( household: String = "h1", device: String = DEVICE, From fc1a2f8e7625a2d3dee25644504f0ea787b577a2 Mon Sep 17 00:00:00 2001 From: aharonamir Date: Mon, 30 Nov 2026 10:57:44 +0200 Subject: [PATCH 30/58] Add a sealed task draft to the shared client The phone and the PC both need to author a device-to-device task, and the server only relays what the client sealed. TaskDraft builds the R29 body (`{"sealed": base64url(IV || ciphertext || tag)}`) under the household key and opens it again, so the composer and both receive paths share one rule. goalOf tries the sealed body first and never falls back to a plaintext goal beside it: an unauthentic body is a refusal, not a second chance. The trace is a fresh W3C traceparent; the server-owned TraceIds lives in the service module, which this client module cannot depend on. Part of #32. --- .../kotlin/com/hopa/backend/link/TaskDraft.kt | 105 ++++++++++++++++++ .../com/hopa/backend/link/TaskDraftTest.kt | 105 ++++++++++++++++++ 2 files changed, 210 insertions(+) create mode 100644 core/backend/src/main/kotlin/com/hopa/backend/link/TaskDraft.kt create mode 100644 core/backend/src/test/kotlin/com/hopa/backend/link/TaskDraftTest.kt diff --git a/core/backend/src/main/kotlin/com/hopa/backend/link/TaskDraft.kt b/core/backend/src/main/kotlin/com/hopa/backend/link/TaskDraft.kt new file mode 100644 index 000000000..7ce0897b1 --- /dev/null +++ b/core/backend/src/main/kotlin/com/hopa/backend/link/TaskDraft.kt @@ -0,0 +1,105 @@ +package com.hopa.backend.link + +import com.hopa.backend.crypto.PayloadCipher +import com.hopa.backend.wire.BackendEnvelope +import kotlinx.serialization.json.Json +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.put +import java.security.SecureRandom +import java.util.Base64 +import java.util.UUID + +/** + * The one place a client builds a `task.create`. + * + * The body is the R29 convention the apps already read: a real task travels as + * `{"sealed": base64url(IV || ciphertext || tag)}` under the household content + * key, so the server stores and relays ciphertext it cannot open. [goalOf] + * still accepts a plaintext `{"goal": …}` for the server-authored + * `admin.action` path; a sealed body that does not open is never replaced by a + * plaintext goal beside it. + */ +object TaskDraft { + /** The longest goal a composer accepts, matching the server's own cap. */ + const val MAX_GOAL_CHARS = 2_000 + + /** `{"sealed": base64url(PayloadCipher.seal(contentKey, {"goal": goal}))}`. */ + fun sealedBody(contentKey: ByteArray, goal: String): JsonObject { + require(goal.isNotBlank()) { "a task needs a goal" } + require(goal.length <= MAX_GOAL_CHARS) { "goal must be 1..$MAX_GOAL_CHARS characters" } + val plaintext = buildJsonObject { put("goal", goal) }.toString().toByteArray(Charsets.UTF_8) + return buildJsonObject { + put("sealed", base64Url(PayloadCipher.seal(contentKey, plaintext))) + } + } + + /** A `task.create` addressed to [toDeviceId], with a fresh UUID id and traceparent. */ + fun create( + contentKey: ByteArray, + toDeviceId: String, + fromDeviceId: String, + goal: String, + ts: Long = System.currentTimeMillis(), + trace: String = newTraceparent(), + ): BackendEnvelope = BackendEnvelope( + id = UUID.randomUUID().toString(), + type = "task.create", + ts = ts, + trace = trace, + from = fromDeviceId, + to = toDeviceId, + body = sealedBody(contentKey, goal), + ) + + /** The goal inside a sealed or plaintext body; null when neither parses. */ + fun goalOf(contentKey: ByteArray, body: JsonObject): String? { + val sealed = (body["sealed"] as? JsonPrimitive) + ?.takeIf { it.isString } + ?.contentOrNull + ?.takeIf { it.isNotBlank() } + if (sealed != null) { + // A sealed body that does not open is a failure, never a fallback. + return openGoal(contentKey, sealed) + } + return (body["goal"] as? JsonPrimitive) + ?.takeIf { it.isString } + ?.contentOrNull + ?.trim() + ?.takeIf { it.isNotBlank() } + } + + /** Null for a wrong key, a bad tag, a malformed blob or a body without a goal. */ + private fun openGoal(contentKey: ByteArray, sealed: String): String? = try { + val blob = Base64.getUrlDecoder().decode(sealed) + val plaintext = PayloadCipher.open(contentKey, blob) + val body = Json.parseToJsonElement(String(plaintext, Charsets.UTF_8)).jsonObject + (body["goal"] as? JsonPrimitive) + ?.takeIf { it.isString } + ?.contentOrNull + ?.takeIf { it.isNotBlank() } + } catch (unreadable: Exception) { + // AEADBadTagException, a wrong key size or a malformed body: all null. + null + } + + private fun base64Url(bytes: ByteArray): String = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes) +} + +/** + * A fresh W3C traceparent, `00-<32 hex>-<16 hex>-01`, the same shape the server + * accepts and echoes. The server-owned `TraceIds` lives in the service module, + * which this client module cannot depend on. + */ +private fun newTraceparent(): String = "00-${hex(16)}-${hex(8)}-01" + +private val traceRandom = SecureRandom() + +private fun hex(bytes: Int): String { + val buffer = ByteArray(bytes) + traceRandom.nextBytes(buffer) + return buffer.joinToString("") { "%02x".format(it) } +} diff --git a/core/backend/src/test/kotlin/com/hopa/backend/link/TaskDraftTest.kt b/core/backend/src/test/kotlin/com/hopa/backend/link/TaskDraftTest.kt new file mode 100644 index 000000000..91210bd2b --- /dev/null +++ b/core/backend/src/test/kotlin/com/hopa/backend/link/TaskDraftTest.kt @@ -0,0 +1,105 @@ +package com.hopa.backend.link + +import com.hopa.backend.crypto.PayloadCipher +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.put +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import java.util.Base64 + +/** + * The one place a client seals a `task.create`. The body is the R29 shape + * (`{"sealed": base64url}`) so the PC's gateway opens exactly what the phone + * wrote, and the plaintext `goal` path stays valid for a server-authored task. + */ +class TaskDraftTest { + private val key = ByteArray(32) { (it + 1).toByte() } + + @Test + fun `a sealed body round-trips the goal`() { + val body = TaskDraft.sealedBody(key, "open the settings app") + + val sealed = body["sealed"]!!.jsonPrimitive.content + assertFalse(sealed.contains('='), "base64url must not be padded") + assertFalse(sealed.contains('+') || sealed.contains('/'), "base64url must be url-safe") + val plaintext = PayloadCipher.open(key, Base64.getUrlDecoder().decode(sealed)) + val opened = Json.parseToJsonElement(String(plaintext, Charsets.UTF_8)).jsonObject + assertEquals("open the settings app", opened["goal"]!!.jsonPrimitive.content) + assertEquals("open the settings app", TaskDraft.goalOf(key, body)) + } + + @Test + fun `a plaintext goal is still read`() { + val body = buildJsonObject { put("goal", "open settings") } + + assertEquals("open settings", TaskDraft.goalOf(key, body)) + } + + @Test + fun `a sealed body under another key is null and never falls back to plaintext`() { + val other = ByteArray(32) { (it + 40).toByte() } + val body = JsonObject( + TaskDraft.sealedBody(other, "open settings") + + ("goal" to JsonPrimitive("leaked")), + ) + + assertNull(TaskDraft.goalOf(key, body)) + } + + @Test + fun `a tampered sealed body is null, not an exception`() { + val body = TaskDraft.sealedBody(key, "open settings") + val bytes = Base64.getUrlDecoder().decode(body["sealed"]!!.jsonPrimitive.content) + bytes[12] = (bytes[12].toInt() xor 0x01).toByte() + val tampered = buildJsonObject { + put("sealed", Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)) + } + + assertNull(TaskDraft.goalOf(key, tampered)) + } + + @Test + fun `a blank goal is refused`() { + assertThrows(IllegalArgumentException::class.java) { TaskDraft.sealedBody(key, " ") } + } + + @Test + fun `an over-long goal is refused`() { + assertThrows(IllegalArgumentException::class.java) { TaskDraft.sealedBody(key, "a".repeat(2_001)) } + } + + @Test + fun `a create frame is addressed, versioned and traced`() { + val frame = TaskDraft.create(key, toDeviceId = "pc-1", fromDeviceId = "phone-1", goal = "open settings") + + assertEquals(1, frame.v) + assertEquals("task.create", frame.type) + assertEquals("pc-1", frame.to) + assertEquals("phone-1", frame.from) + assertTrue(frame.id.isNotBlank()) + assertTrue(TRACEPARENT.matches(frame.trace.orEmpty()), "a fresh traceparent: ${frame.trace}") + assertEquals("open settings", TaskDraft.goalOf(key, frame.body)) + } + + @Test + fun `two creates do not share an id or a trace`() { + val first = TaskDraft.create(key, "pc-1", "phone-1", "one") + val second = TaskDraft.create(key, "pc-1", "phone-1", "two") + + assertFalse(first.id == second.id) + assertFalse(first.trace == second.trace) + } + + private companion object { + val TRACEPARENT = Regex("^00-[0-9a-f]{32}-[0-9a-f]{16}-01$") + } +} From 8d7be1fa98c31f03ec1cf0fddf68bd854cbf8cbb Mon Sep 17 00:00:00 2001 From: aharonamir Date: Mon, 30 Nov 2026 10:57:55 +0200 Subject: [PATCH 31/58] List the household's devices from the shared client Both composers need the same picker: `GET /v1/devices` with the stored bearer. The call lives in core/backend so the phone and the sidecar cannot parse it differently, and a refusal surfaces as its stable code (`E_AUTH`, `E_SYNC`, `E_SCHEMA`) instead of a raw IOException or an empty list. A device without an id is dropped; no target is ever guessed. Part of #32. --- .../hopa/backend/devices/DeviceListClient.kt | 109 ++++++++++++++ .../backend/devices/DeviceListClientTest.kt | 133 ++++++++++++++++++ 2 files changed, 242 insertions(+) create mode 100644 core/backend/src/main/kotlin/com/hopa/backend/devices/DeviceListClient.kt create mode 100644 core/backend/src/test/kotlin/com/hopa/backend/devices/DeviceListClientTest.kt diff --git a/core/backend/src/main/kotlin/com/hopa/backend/devices/DeviceListClient.kt b/core/backend/src/main/kotlin/com/hopa/backend/devices/DeviceListClient.kt new file mode 100644 index 000000000..82e284c37 --- /dev/null +++ b/core/backend/src/main/kotlin/com/hopa/backend/devices/DeviceListClient.kt @@ -0,0 +1,109 @@ +package com.hopa.backend.devices + +import com.hopa.backend.pairing.BackendUrls +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import okhttp3.OkHttpClient +import okhttp3.Request +import java.io.IOException +import java.util.concurrent.TimeUnit + +/** + * One device of the caller's household, as `GET /v1/devices` lists it. The + * server's own `DeviceView` is the same shape; this copy is what the clients + * can see, because the service module owns that class. + */ +data class HouseholdDevice( + val id: String, + val memberId: String, + val platform: String, + val name: String, + val lastSeenAt: String? = null, + val revokedAt: String? = null, + val current: Boolean = false, +) + +/** + * A refused device list: the server's own code when it answered with one, so a + * composer can show the stable code and never an English message. + */ +class DeviceListException( + val code: String, + val status: Int = 0, + message: String = code, +) : Exception(message) + +/** + * `GET /v1/devices` with the caller's bearer. Both apps need the household's + * devices to offer a task target, so the call lives here, not in either app. + * + * A non-2xx answer, an unreachable server or a body that is not a JSON array is + * a [DeviceListException] with a stable code. A device without an id is dropped + * rather than guessed at; an id is the only field the sender cannot do without. + */ +class DeviceListClient( + private val http: OkHttpClient = defaultHttp(), + private val dispatcher: CoroutineDispatcher = Dispatchers.IO, +) { + suspend fun list(gatewayUrl: String, accessToken: String): List { + return withContext(dispatcher) { + val request = Request.Builder() + .url("${BackendUrls.httpBase(gatewayUrl)}/v1/devices") + .header("Authorization", "Bearer $accessToken") + .get() + .build() + val response = try { + http.newCall(request).execute() + } catch (failed: IOException) { + throw DeviceListException("E_SYNC") + } + response.use { answer -> + val text = answer.body?.string().orEmpty() + if (!answer.isSuccessful) { + throw DeviceListException(codeOf(text, answer.code), answer.code) + } + parse(text) ?: throw DeviceListException("E_SCHEMA", answer.code) + } + } + } + + /** Null for a body that is not an array; ids that are not strings are skipped. */ + private fun parse(text: String): List? = runCatching { + Json.parseToJsonElement(text).jsonArray.mapNotNull { element -> + val entry = element as? JsonObject ?: return@mapNotNull null + val id = entry["id"]?.jsonPrimitive?.contentOrNull?.takeIf { it.isNotBlank() } + ?: return@mapNotNull null + HouseholdDevice( + id = id, + memberId = entry["memberId"]?.jsonPrimitive?.contentOrNull.orEmpty(), + platform = entry["platform"]?.jsonPrimitive?.contentOrNull.orEmpty(), + name = entry["name"]?.jsonPrimitive?.contentOrNull.orEmpty(), + lastSeenAt = entry["lastSeenAt"]?.jsonPrimitive?.contentOrNull, + revokedAt = entry["revokedAt"]?.jsonPrimitive?.contentOrNull, + current = entry["current"]?.jsonPrimitive?.contentOrNull?.toBooleanStrictOrNull() ?: false, + ) + } + }.getOrNull() + + /** The server's `{"code": …}` when present, else 401 = auth and anything else = sync. */ + private fun codeOf(text: String, status: Int): String { + val code = runCatching { + Json.parseToJsonElement(text).jsonObject["code"]?.jsonPrimitive?.contentOrNull + }.getOrNull() + return code?.takeIf { it.isNotBlank() } ?: if (status == 401) "E_AUTH" else "E_SYNC" + } + + private companion object { + fun defaultHttp(): OkHttpClient = OkHttpClient.Builder() + .connectTimeout(15, TimeUnit.SECONDS) + .readTimeout(15, TimeUnit.SECONDS) + .build() + } +} diff --git a/core/backend/src/test/kotlin/com/hopa/backend/devices/DeviceListClientTest.kt b/core/backend/src/test/kotlin/com/hopa/backend/devices/DeviceListClientTest.kt new file mode 100644 index 000000000..20a513462 --- /dev/null +++ b/core/backend/src/test/kotlin/com/hopa/backend/devices/DeviceListClientTest.kt @@ -0,0 +1,133 @@ +package com.hopa.backend.devices + +import kotlinx.coroutines.runBlocking +import okhttp3.OkHttpClient +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertThrows +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test + +/** + * `GET /v1/devices` with the caller's bearer, against a loopback server. Both + * apps list the household from here, so the parse must fail closed: a device + * without an id is dropped, and a refused call is a stable code, never a crash. + */ +class DeviceListClientTest { + @Test + fun `the household's devices are parsed with their state`() { + withServer(okJson(DEVICES)) { server -> + val devices = runBlocking { + DeviceListClient(http = OkHttpClient()).list(server.gatewayUrl(), "token") + } + + assertEquals(2, devices.size) + val phone = devices.first() + assertEquals("phone-1", phone.id) + assertEquals("m-1", phone.memberId) + assertEquals("android", phone.platform) + assertEquals("Pixel", phone.name) + assertEquals("2026-11-30T09:00:00Z", phone.lastSeenAt) + assertNull(phone.revokedAt) + assertTrue(phone.current) + assertEquals("pc-1", devices[1].id) + assertTrue(devices[1].revokedAt != null) + } + } + + @Test + fun `the request carries the bearer and names the devices route`() { + withServer(okJson(emptyList())) { server -> + runBlocking { DeviceListClient(http = OkHttpClient()).list(server.gatewayUrl(), "token-1") } + + val request = server.takeRequest() + assertEquals("/v1/devices", request.path) + assertEquals("Bearer token-1", request.getHeader("Authorization")) + } + } + + @Test + fun `a device without an id is dropped, not invented`() { + withServer( + okJson( + listOf( + """{"id":"phone-1","memberId":"m-1","platform":"android","name":"Pixel","current":true}""", + """{"memberId":"m-1","platform":"android","name":"Ghost","current":false}""", + ), + ), + ) { server -> + val devices = runBlocking { + DeviceListClient(http = OkHttpClient()).list(server.gatewayUrl(), "token") + } + + assertEquals(listOf("phone-1"), devices.map { it.id }) + } + } + + @Test + fun `a refused call is its stable code`() { + withServer( + MockResponse().setResponseCode(401) + .setBody("""{"code":"E_AUTH","message":"unknown or expired token"}"""), + ) { server -> + val failure = assertThrows(DeviceListException::class.java) { + runBlocking { DeviceListClient(http = OkHttpClient()).list(server.gatewayUrl(), "token") } + } + + assertEquals("E_AUTH", failure.code) + assertEquals(401, failure.status) + } + } + + @Test + fun `an unreachable server is E_SYNC and never throws a raw IOException`() { + // Nothing listens on the port once the server is shut down. + val server = MockWebServer().apply { start() } + val url = server.gatewayUrl() + server.shutdown() + + val failure = assertThrows(DeviceListException::class.java) { + runBlocking { DeviceListClient(http = OkHttpClient()).list(url, "token") } + } + + assertEquals("E_SYNC", failure.code) + } + + @Test + fun `a malformed list is refused instead of half-read`() { + withServer(MockResponse().setResponseCode(200).setBody("""{"devices":[]}""")) { server -> + val failure = assertThrows(DeviceListException::class.java) { + runBlocking { DeviceListClient(http = OkHttpClient()).list(server.gatewayUrl(), "token") } + } + + assertEquals("E_SCHEMA", failure.code) + } + } + + private fun withServer(response: MockResponse, block: (MockWebServer) -> Unit) { + val server = MockWebServer() + server.enqueue(response) + server.start() + try { + block(server) + } finally { + server.shutdown() + } + } + + private fun MockWebServer.gatewayUrl(): String = "ws://$hostName:$port/v1/gateway" + + private fun okJson(devices: List) = + MockResponse().setResponseCode(200).setBody(devices.joinToString(prefix = "[", postfix = "]")) + + private companion object { + val DEVICES = listOf( + """{"id":"phone-1","memberId":"m-1","platform":"android","name":"Pixel",""" + + """"lastSeenAt":"2026-11-30T09:00:00Z","revokedAt":null,"current":true}""", + """{"id":"pc-1","memberId":"m-1","platform":"windows","name":"Studio",""" + + """"lastSeenAt":null,"revokedAt":"2026-11-29T08:00:00Z","current":false}""", + ) + } +} From 3d590bd2617b57114745b84ef61ab46482196fce Mon Sep 17 00:00:00 2001 From: aharonamir Date: Mon, 30 Nov 2026 10:58:07 +0200 Subject: [PATCH 32/58] Send and open sealed tasks on the phone MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The phone only ran plaintext goals, so a task from the PC (which seals) could never run, and nothing let the phone start a task at all. - RemoteTaskRunner opens `{"sealed": …}` with the household key before it claims an id. A body that does not open is E_SCHEMA "the task could not be opened", non-retryable and unclaimed, so a re-pair can resend it. The plaintext goal still runs for the server-authored admin.action. - RemoteTaskSender seals one goal, sends `task.create`, learns the server-assigned id from the acceptance ack, and shows only an answer from the addressed peer naming exactly that id. - BackendSession forwards relayed task replies; AppContainer wires them to the sender and decodes the key once for both directions. - One sheet and one view model list the household's devices (minus this phone and revoked rows), take a goal, and show "Sent to ", the sealed answer, or the stable failure code. Nothing logs or renders the goal. Part of #32. --- .../kotlin/com/hopa/app/di/AppContainer.kt | 30 +++ .../com/hopa/app/feature/shell/HomeShell.kt | 27 +++ .../hopa/app/feature/shell/SendTaskSheet.kt | 151 +++++++++++++++ .../app/feature/shell/SendTaskViewModel.kt | 76 ++++++++ .../hopa/app/link/remote/RemoteTaskRunner.kt | 28 ++- .../hopa/app/link/remote/RemoteTaskSender.kt | 151 +++++++++++++++ .../hopa/app/link/session/BackendSession.kt | 6 + .../app/link/remote/RemoteTaskRunnerTest.kt | 62 +++++- .../app/link/remote/RemoteTaskSenderTest.kt | 176 ++++++++++++++++++ .../com/hopa/backend/link/BackendLink.kt | 4 +- 10 files changed, 701 insertions(+), 10 deletions(-) create mode 100644 apps/android/app/src/main/kotlin/com/hopa/app/feature/shell/SendTaskSheet.kt create mode 100644 apps/android/app/src/main/kotlin/com/hopa/app/feature/shell/SendTaskViewModel.kt create mode 100644 apps/android/app/src/main/kotlin/com/hopa/app/link/remote/RemoteTaskSender.kt create mode 100644 apps/android/app/src/test/kotlin/com/hopa/app/link/remote/RemoteTaskSenderTest.kt diff --git a/apps/android/app/src/main/kotlin/com/hopa/app/di/AppContainer.kt b/apps/android/app/src/main/kotlin/com/hopa/app/di/AppContainer.kt index 29a607d7f..4b74a8395 100644 --- a/apps/android/app/src/main/kotlin/com/hopa/app/di/AppContainer.kt +++ b/apps/android/app/src/main/kotlin/com/hopa/app/di/AppContainer.kt @@ -390,6 +390,31 @@ class AppContainer @Inject constructor(@ApplicationContext context: Context) : C /** Task ids the gateway delivered, so a redelivery inside a day is skipped. */ private val processedTasks by lazy { ProcessedTaskStore.open(context) } + /** + * The household content key, decoded from the secret store. A sealed task + * and a sealed reply both open with it; anything that is not 32 bytes means + * the key is unusable, not a crash. + */ + private suspend fun householdContentKey(): ByteArray? = + runCatching { java.util.Base64.getDecoder().decode(settings.backendContentKey()) } + .getOrNull() + ?.takeIf { it.size == 32 } + + /** The household's devices for the send composers; shared with the sidecar's call. */ + val deviceList = com.hopa.backend.devices.DeviceListClient() + + /** + * A task this phone sends to a peer: seal the goal, send it, then show the + * peer's sealed answer. One composer, one in-flight send. + */ + val sentTasks by lazy { + com.hopa.app.link.remote.RemoteTaskSender( + deviceId = { backend.deviceId }, + link = { backend.currentLink() }, + contentKey = { householdContentKey() }, + ) + } + /** * A task delivered by the gateway runs on the configured surface and answers * on the wake socket. One at a time, so two deliveries never fight over the @@ -401,6 +426,9 @@ class AppContainer @Inject constructor(@ApplicationContext context: Context) : C link = { backend.currentLink() }, processed = processedTasks, settings = { settings.settings.first() }, + // The household key opening a sealed delivery; a blank or malformed + // stored key means a sealed task cannot open and is refused. + contentKey = { householdContentKey() }, surfaces = { current -> surfaces(current) }, screen = { current -> Surfaces.state(this, current) }, runGate = runGate, @@ -443,6 +471,8 @@ class AppContainer @Inject constructor(@ApplicationContext context: Context) : C backend.onDiagnostic = { } // A peer's write is a hint to pull; the pass itself decides what is new. backend.onSyncChanged = { sync.onRemoteChanged() } + // The answer to a task this phone sent; a composer shows it, nothing runs. + backend.onReply = { frame -> sentTasks.onReply(frame) } // Local writes are only pushed while a household identity is stored; // signed out, a debounced trigger would only read settings and stop. appScope.launch { diff --git a/apps/android/app/src/main/kotlin/com/hopa/app/feature/shell/HomeShell.kt b/apps/android/app/src/main/kotlin/com/hopa/app/feature/shell/HomeShell.kt index fa20daf35..8a31a6657 100644 --- a/apps/android/app/src/main/kotlin/com/hopa/app/feature/shell/HomeShell.kt +++ b/apps/android/app/src/main/kotlin/com/hopa/app/feature/shell/HomeShell.kt @@ -4,6 +4,7 @@ import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize @@ -73,6 +74,8 @@ fun HomeShell( settings.accountSkipped -> "This phone only — tap to connect" else -> "Connect this phone with your computer" } + // The one composer in this direction: only a signed-in phone has a peer. + val signedIn = settings.backendDeviceId.isNotBlank() if (settings.profile == "easy") { EasyShell( container = container, @@ -81,6 +84,7 @@ fun HomeShell( initialGoal = initialGoal, shared = incoming, banner = banner, + signedIn = signedIn, ) return } @@ -103,6 +107,7 @@ fun HomeShell( initialGoal = initialGoal, shared = incoming, banner = banner, + signedIn = signedIn, ) return } @@ -154,6 +159,7 @@ fun HomeShell( banner?.let { text -> AccountBanner(text, modifier = Modifier.align(Alignment.TopCenter)) } + SendTaskOverlay(signedIn) } } @@ -165,6 +171,7 @@ private fun EasyShell( initialGoal: String, shared: Boolean, banner: String?, + signedIn: Boolean, ) { var tab by rememberSaveable { mutableStateOf("talk") } androidx.compose.runtime.LaunchedEffect(shared) { @@ -202,6 +209,7 @@ private fun EasyShell( banner?.let { text -> AccountBanner(text, modifier = Modifier.align(Alignment.TopCenter)) } + SendTaskOverlay(signedIn) } } @@ -224,6 +232,7 @@ private fun PowerShell( initialGoal: String, shared: Boolean, banner: String?, + signedIn: Boolean, ) { var tab by rememberSaveable { mutableStateOf("chat") } var chatStarted by rememberSaveable { mutableStateOf(false) } @@ -290,6 +299,24 @@ private fun PowerShell( banner?.let { text -> AccountBanner(text, modifier = Modifier.align(Alignment.TopCenter)) } + SendTaskOverlay(signedIn) + } +} + +/** + * The signed-in shell's one composer for the other direction: a small chip + * under the header, and the sheet it opens. It lives in the shell rather than + * the account card because that card belongs to the capabilities feature + * module; a signed-in phone is the shell's own state. + */ +@Composable +private fun BoxScope.SendTaskOverlay(signedIn: Boolean) { + var open by rememberSaveable { mutableStateOf(false) } + if (signedIn) { + SendTaskTrigger(modifier = Modifier.align(Alignment.TopEnd), onOpen = { open = true }) + } + if (open) { + SendTaskSheet(onDismiss = { open = false }) } } diff --git a/apps/android/app/src/main/kotlin/com/hopa/app/feature/shell/SendTaskSheet.kt b/apps/android/app/src/main/kotlin/com/hopa/app/feature/shell/SendTaskSheet.kt new file mode 100644 index 000000000..71b696bfa --- /dev/null +++ b/apps/android/app/src/main/kotlin/com/hopa/app/feature/shell/SendTaskSheet.kt @@ -0,0 +1,151 @@ +package com.hopa.app.feature.shell + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.hilt.navigation.compose.hiltViewModel +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.hopa.app.link.remote.TaskSendState +import com.hopa.backend.link.TaskDraft + +/** + * The phone's one composer for the other direction: pick a household device, + * type a goal, and the goal travels sealed. One dialog, no navigation entry. + * + * [SendTaskTrigger] is the small chip the shell shows while this phone is + * signed in; it only opens this sheet. + */ +@Composable +fun SendTaskSheet(onDismiss: () -> Unit) { + val viewModel: SendTaskViewModel = hiltViewModel() + val devices by viewModel.devices.collectAsStateWithLifecycle() + val loading by viewModel.loading.collectAsStateWithLifecycle() + val error by viewModel.error.collectAsStateWithLifecycle() + val sendState by viewModel.sendState.collectAsStateWithLifecycle() + + var selectedId by rememberSaveable { mutableStateOf("") } + var goal by rememberSaveable { mutableStateOf("") } + + LaunchedEffect(Unit) { viewModel.open() } + LaunchedEffect(devices) { + if (devices.none { it.id == selectedId }) { + selectedId = devices.firstOrNull()?.id.orEmpty() + } + } + + val target = devices.firstOrNull { it.id == selectedId } + val status = when (val state = sendState) { + TaskSendState.Idle -> "" + is TaskSendState.Sent -> "Sent to ${state.toName}" + is TaskSendState.Replied -> "${state.toName}: ${state.text}" + is TaskSendState.Failed -> state.code + } + + AlertDialog( + onDismissRequest = onDismiss, + title = { Text("Send a task to your computer") }, + text = { + Column( + modifier = Modifier.verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + when { + loading -> CircularProgressIndicator(modifier = Modifier.padding(8.dp)) + error != null -> { + Text(error.orEmpty(), fontSize = 12.sp) + TextButton(onClick = viewModel::retry) { Text("Try again") } + } + devices.isEmpty() -> Text("No computer is in your household yet.", fontSize = 12.sp) + else -> devices.forEach { device -> + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { selectedId = device.id } + .padding(vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + RadioButton(selected = device.id == selectedId, onClick = { selectedId = device.id }) + Column(modifier = Modifier.padding(start = 4.dp)) { + Text(device.name.ifBlank { device.id }) + Text(device.platform, fontSize = 10.sp) + } + } + } + } + OutlinedTextField( + value = goal, + onValueChange = { next -> + if (next.length <= TaskDraft.MAX_GOAL_CHARS) goal = next + }, + label = { Text("What should it do?") }, + singleLine = false, + maxLines = 4, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done), + modifier = Modifier.fillMaxWidth(), + ) + if (status.isNotBlank()) { + Text(status, fontSize = 12.sp) + } + } + }, + confirmButton = { + TextButton( + onClick = { target?.let { viewModel.send(it.id, it.name, goal.trim()) } }, + enabled = target != null && goal.isNotBlank() && !loading, + ) { + Text("Send") + } + }, + dismissButton = { + TextButton(onClick = onDismiss) { Text("Close") } + }, + ) +} + +/** The shell's small "send to my computer" chip; shown only while signed in. */ +@Composable +fun SendTaskTrigger( + modifier: Modifier = Modifier, + onOpen: () -> Unit, +) { + Box(modifier = modifier.statusBarsPadding().padding(top = 64.dp, end = 12.dp)) { + Surface( + shape = RoundedCornerShape(14.dp), + tonalElevation = 2.dp, + onClick = onOpen, + ) { + Text( + "Send to PC", + fontSize = 11.sp, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 6.dp), + ) + } + } +} diff --git a/apps/android/app/src/main/kotlin/com/hopa/app/feature/shell/SendTaskViewModel.kt b/apps/android/app/src/main/kotlin/com/hopa/app/feature/shell/SendTaskViewModel.kt new file mode 100644 index 000000000..b50cc69d4 --- /dev/null +++ b/apps/android/app/src/main/kotlin/com/hopa/app/feature/shell/SendTaskViewModel.kt @@ -0,0 +1,76 @@ +package com.hopa.app.feature.shell + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.hopa.app.di.AppContainer +import com.hopa.app.link.remote.TaskSendState +import com.hopa.backend.devices.DeviceListException +import com.hopa.backend.devices.HouseholdDevice +import dagger.hilt.android.lifecycle.HiltViewModel +import javax.inject.Inject +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch + +/** + * The "send a task to my computer" sheet: the household's devices, a goal, and + * the peer's answer. A failure is a stable code only; a goal never reaches a + * message or a log line. + */ +@HiltViewModel +class SendTaskViewModel @Inject constructor( + private val container: AppContainer, +) : ViewModel() { + private val _devices = MutableStateFlow>(emptyList()) + val devices: StateFlow> = _devices.asStateFlow() + + private val _loading = MutableStateFlow(false) + val loading: StateFlow = _loading.asStateFlow() + + /** The stable code of the failed device list, or null. */ + private val _error = MutableStateFlow(null) + val error: StateFlow = _error.asStateFlow() + + val sendState: StateFlow get() = container.sentTasks.state + + /** Called when the sheet appears: a fresh list and no stale answer. */ + fun open() { + container.sentTasks.reset() + loadDevices() + } + + fun retry() = loadDevices() + + private fun loadDevices() { + viewModelScope.launch { + _loading.value = true + _error.value = null + try { + val credentials = container.backend.credentials() + if (credentials == null) { + _error.value = "E_AUTH" + return@launch + } + val listed = container.deviceList.list(credentials.gatewayUrl, credentials.accessToken) + // This phone and a revoked device are not targets. + _devices.value = listed.filter { !it.current && it.revokedAt == null } + } catch (cancelled: CancellationException) { + throw cancelled + } catch (failed: DeviceListException) { + _error.value = failed.code + } catch (failed: Exception) { + _error.value = "E_SYNC" + } finally { + _loading.value = false + } + } + } + + fun send(toDeviceId: String, toName: String, goal: String) { + viewModelScope.launch { + container.sentTasks.send(toDeviceId, toName, goal) + } + } +} diff --git a/apps/android/app/src/main/kotlin/com/hopa/app/link/remote/RemoteTaskRunner.kt b/apps/android/app/src/main/kotlin/com/hopa/app/link/remote/RemoteTaskRunner.kt index e9c894652..5322f102a 100644 --- a/apps/android/app/src/main/kotlin/com/hopa/app/link/remote/RemoteTaskRunner.kt +++ b/apps/android/app/src/main/kotlin/com/hopa/app/link/remote/RemoteTaskRunner.kt @@ -2,6 +2,7 @@ package com.hopa.app.link.remote import com.hopa.backend.wire.BackendEnvelope import com.hopa.backend.link.BackendLink +import com.hopa.backend.link.TaskDraft import com.hopa.backend.wire.BackendReplies import com.hopa.backend.link.ProcessedTaskLog import com.hopa.contracts.error.ErrorCodes @@ -16,8 +17,6 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull -import kotlinx.serialization.json.contentOrNull -import kotlinx.serialization.json.jsonPrimitive import com.hopa.runtime.RunGate import com.hopa.runtime.RunSource @@ -39,6 +38,7 @@ class RemoteTaskRunner( private val link: () -> BackendLink?, private val processed: ProcessedTaskLog, private val settings: suspend () -> AppSettings, + private val contentKey: suspend () -> ByteArray?, private val surfaces: suspend (AppSettings) -> ScreenSourceDevice, private val screen: (AppSettings) -> RemoteScreenState, private val runGate: com.hopa.runtime.RunGate, @@ -60,12 +60,19 @@ class RemoteTaskRunner( val live = link() ?: return live.ack(task) val id = task.task.orEmpty().trim() - val goal = runCatching { task.body["goal"]?.jsonPrimitive?.contentOrNull } - .getOrNull() - .orEmpty() - .trim() + // A sealed task travels as ciphertext: open it under the household + // content key. The plaintext `goal` stays for a server-authored + // `admin.action`. A sealed body that does not open is a schema error, + // never a fall back to a plaintext goal beside it. + val sealed = task.body.containsKey("sealed") + val goal = if (sealed) { + contentKey()?.let { key -> TaskDraft.goalOf(key, task.body) } + } else { + TaskDraft.goalOf(NO_KEY, task.body) + }.orEmpty().trim() if (id.isBlank() || goal.isBlank()) { - live.send(BackendReplies.error(task, deviceId(), "E_SCHEMA", INVALID, false)) + val message = if (sealed) OPEN_FAILED else INVALID + live.send(BackendReplies.error(task, deviceId(), "E_SCHEMA", message, false)) return } if (processed.seen(id)) { @@ -325,12 +332,19 @@ class RemoteTaskRunner( const val DEFAULT_SURFACE_TIMEOUT_MS = 25_000L const val INVALID = "the task needs an id and a goal" + const val OPEN_FAILED = "the task could not be opened" const val TIMEOUT = "the run did not finish in time" const val SURFACE_TIMEOUT = "the screen did not answer in time; send it again" const val APPROVAL_REFUSED = "a step needed your approval and was refused" const val NO_SCREEN = "I cannot reach your apps: open Running apps, turn on screen access, " + "start the hidden screen, or pair your computer." + + /** + * [TaskDraft.goalOf] needs a key only to open a sealed body; a plaintext + * read never touches it, so an unpaired phone still runs one. + */ + val NO_KEY = ByteArray(0) } /** The surface that will run, with the plan the planner made for it. */ diff --git a/apps/android/app/src/main/kotlin/com/hopa/app/link/remote/RemoteTaskSender.kt b/apps/android/app/src/main/kotlin/com/hopa/app/link/remote/RemoteTaskSender.kt new file mode 100644 index 000000000..c029e03e0 --- /dev/null +++ b/apps/android/app/src/main/kotlin/com/hopa/app/link/remote/RemoteTaskSender.kt @@ -0,0 +1,151 @@ +package com.hopa.app.link.remote + +import com.hopa.backend.crypto.PayloadCipher +import com.hopa.backend.link.BackendLink +import com.hopa.backend.link.TaskDraft +import com.hopa.backend.wire.BackendEnvelope +import java.util.Base64 +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.jsonObject + +/** How the last task this phone sent to a peer is going. */ +sealed interface TaskSendState { + data object Idle : TaskSendState + + /** The frame left this phone; the peer has not answered yet. */ + data class Sent(val toName: String, val taskId: String) : TaskSendState + + /** The peer ran the task and its answer came back sealed. */ + data class Replied(val toName: String, val text: String) : TaskSendState + + /** A stable code only; an English message never crosses the wire. */ + data class Failed(val code: String) : TaskSendState +} + +/** + * One direction of a composer: seal a goal with the household key, send the + * `task.create`, and follow the peer's answer on the same socket. + * + * The server reassigns the task id when it accepts a create, so correlation + * mirrors [com.hopa.sidecar.backend.BackendGateway]'s approval slot: the first + * `task.ack` after a send teaches the server-assigned id, and only a reply from + * the peer we addressed, naming exactly that id, completes the send. A result + * that arrives before the ack, or from another device, is never shown. + * + * Only one send is in flight: the composer is one dialog, and a second send + * replaces the pending one instead of interleaving two conversations. + */ +class RemoteTaskSender( + private val deviceId: () -> String, + private val link: () -> BackendLink?, + private val contentKey: suspend () -> ByteArray?, +) { + private val _state = MutableStateFlow(TaskSendState.Idle) + val state: StateFlow = _state.asStateFlow() + + private class Pending(val toDeviceId: String, val toName: String) { + @Volatile + var serverTask: String? = null + } + + @Volatile + private var pending: Pending? = null + + /** For a sheet opening again: the last answer belongs to the last send. */ + fun reset() { + pending = null + _state.value = TaskSendState.Idle + } + + /** Seals and sends one goal; the outcome is also [state] by the time it returns. */ + suspend fun send(toDeviceId: String, toName: String, goal: String): TaskSendState { + val live = link() ?: return fail("E_DEVICE") + val key = contentKey() ?: return fail("E_SCHEMA") + val frame = try { + TaskDraft.create(key, toDeviceId, deviceId(), goal) + } catch (invalid: IllegalArgumentException) { + return fail("E_SCHEMA") + } + val request = Pending(toDeviceId, toName) + pending = request + try { + live.send(frame) + } catch (cancelled: CancellationException) { + throw cancelled + } catch (failed: Exception) { + return fail("E_DEVICE") + } + return publish(TaskSendState.Sent(toName, frame.id)) + } + + /** + * A relayed reply on this device's socket. Frames that are not a reply to + * the pending send are ignored, so a late answer cannot overwrite a newer + * one. + */ + suspend fun onReply(frame: BackendEnvelope) { + val request = pending ?: return + when (frame.type) { + "task.ack" -> { + val serverTask = (frame.body["task"] as? JsonPrimitive) + ?.takeIf { it.isString } + ?.contentOrNull + ?.takeIf { it.isNotBlank() } + if (serverTask != null) request.serverTask = serverTask + } + + "task.result", "task.error" -> { + // A decision is only accepted after the acceptance ack named + // the id, from the peer we addressed, and for exactly that id. + val serverTask = request.serverTask ?: return + if (frame.from != request.toDeviceId) return + if (frame.task != serverTask) return + val next = if (frame.type == "task.error") { + TaskSendState.Failed( + (frame.body["code"] as? JsonPrimitive)?.contentOrNull + ?.takeIf { it.isNotBlank() } + ?: "E_AGENT", + ) + } else { + val text = openText(frame) + if (text == null) TaskSendState.Failed("E_SCHEMA") else TaskSendState.Replied(request.toName, text) + } + pending = null + _state.value = next + } + } + } + + /** The peer's `{"sealed": base64url({"text": …})}` answer, or null. */ + private suspend fun openText(frame: BackendEnvelope): String? { + val sealed = (frame.body["sealed"] as? JsonPrimitive) + ?.takeIf { it.isString } + ?.contentOrNull + ?.takeIf { it.isNotBlank() } + ?: return null + val key = contentKey() ?: return null + return try { + val blob = Base64.getUrlDecoder().decode(sealed) + val body = Json.parseToJsonElement(String(PayloadCipher.open(key, blob), Charsets.UTF_8)).jsonObject + (body["text"] as? JsonPrimitive)?.contentOrNull?.takeIf { it.isNotBlank() } + } catch (unreadable: Exception) { + null + } + } + + private fun fail(code: String): TaskSendState { + pending = null + return publish(TaskSendState.Failed(code)) + } + + private fun publish(next: TaskSendState): TaskSendState { + _state.value = next + return next + } +} diff --git a/apps/android/app/src/main/kotlin/com/hopa/app/link/session/BackendSession.kt b/apps/android/app/src/main/kotlin/com/hopa/app/link/session/BackendSession.kt index 8491b431f..33a486c9d 100644 --- a/apps/android/app/src/main/kotlin/com/hopa/app/link/session/BackendSession.kt +++ b/apps/android/app/src/main/kotlin/com/hopa/app/link/session/BackendSession.kt @@ -74,6 +74,10 @@ class BackendSession( @Volatile var onSyncChanged: (suspend (Long) -> Unit)? = null + /** A relayed reply to a task this phone sent (`task.ack`, `task.result`, …). */ + @Volatile + var onReply: (suspend (BackendEnvelope) -> Unit)? = null + /** The live socket, for the runner that answers a delivery on it. */ fun currentLink(): BackendLink? = link @@ -286,6 +290,8 @@ class BackendSession( onTask?.invoke(envelope) } created.onApproval = { envelope -> onApproval?.invoke(envelope) } + // A task reply addressed here is a composer's answer, never a goal. + created.onReply = { envelope -> onReply?.invoke(envelope) } // A sync notification is a seq only. The link delivers it off the reader, // so a slow pull cannot stall the socket. created.onSyncChanged = { seq -> onSyncChanged?.invoke(seq) } diff --git a/apps/android/app/src/test/kotlin/com/hopa/app/link/remote/RemoteTaskRunnerTest.kt b/apps/android/app/src/test/kotlin/com/hopa/app/link/remote/RemoteTaskRunnerTest.kt index aa87fdbcf..807237b18 100644 --- a/apps/android/app/src/test/kotlin/com/hopa/app/link/remote/RemoteTaskRunnerTest.kt +++ b/apps/android/app/src/test/kotlin/com/hopa/app/link/remote/RemoteTaskRunnerTest.kt @@ -2,6 +2,7 @@ package com.hopa.app.link.remote import com.hopa.runtime.RunGate import com.hopa.runtime.RunSource +import com.hopa.backend.link.TaskDraft import com.hopa.backend.wire.BackendEnvelope import com.hopa.backend.link.BackendLink import com.hopa.backend.link.BackendState @@ -355,8 +356,63 @@ class RemoteTaskRunnerTest { assertFalse(fixture.runGate.state.value.busy) assertEquals(1, fixture.runs) } + + @Test + fun `a sealed task runs with the goal it opened`() = runBlocking { + val fixture = Fixture(locked = false, contentKey = HOUSEHOLD_KEY) + val frame = TaskDraft.create( + HOUSEHOLD_KEY, + toDeviceId = "d1", + fromDeviceId = "pc-1", + goal = "open the settings app", + ).copy(task = "t-sealed") + + fixture.runner.handle(frame) + + assertEquals( + listOf("task.ack", "task.progress", "task.result"), + fixture.link.frames.map { it.type }, + ) + assertEquals("open the settings app", fixture.goalSeen) + assertEquals("Done.", fixture.link.frames.last().body["summary"]?.jsonPrimitive?.contentOrNull) + assertFalse(fixture.log.claim("t-sealed")) + } + + @Test + fun `a plaintext task still runs when the phone holds a content key`() = runBlocking { + val fixture = Fixture(locked = false, contentKey = HOUSEHOLD_KEY) + + fixture.runner.handle(delivery("t-plain")) + + assertEquals(1, fixture.runs) + assertEquals("open settings", fixture.goalSeen) + } + + @Test + fun `a sealed task under another key is refused and stays unprocessed`() = runBlocking { + val fixture = Fixture(locked = false, contentKey = HOUSEHOLD_KEY) + val frame = TaskDraft.create( + ByteArray(32) { (it + 40).toByte() }, + toDeviceId = "d1", + fromDeviceId = "pc-1", + goal = "open settings", + ).copy(task = "t-wrong") + + fixture.runner.handle(frame) + + assertEquals(listOf("task.ack", "task.error"), fixture.link.frames.map { it.type }) + val error = fixture.link.frames[1] + assertEquals("E_SCHEMA", error.body["code"]?.jsonPrimitive?.contentOrNull) + assertEquals("the task could not be opened", error.body["message"]?.jsonPrimitive?.contentOrNull) + assertEquals("false", error.body["retryable"]?.jsonPrimitive?.contentOrNull) + assertEquals(0, fixture.runs) + // The id is not claimed, so the person can send it again after a re-pair. + assertTrue(fixture.log.claim("t-wrong")) + } } +private val HOUSEHOLD_KEY = ByteArray(32) { (it + 1).toByte() } + private fun delivery(id: String): BackendEnvelope = BackendEnvelope( id = "e-$id", type = "task.create", @@ -402,6 +458,7 @@ private class Fixture( private val result: TurnResult? = TurnResult("Done."), surfaceTimeoutMs: Long = 25_000L, private val runOverride: (suspend () -> TurnResult?)? = null, + contentKey: ByteArray? = null, ) { val link = RecordingLink() val log = log() @@ -418,12 +475,14 @@ private class Fixture( var finished = 0 var services = 0 var busySeen = false + var goalSeen = "" val runner = RemoteTaskRunner( deviceId = { "d1" }, link = { link }, processed = log, settings = { AppSettings(screenPath = "auto", accessibilityAllowed = true) }, + contentKey = { contentKey }, surfaces = { resolutions += 1 events += "surface" @@ -446,10 +505,11 @@ private class Fixture( stopService = {}, postApproval = { approvals += 1 }, releaseSurface = {}, - run = { + run = { request -> runs += 1 busySeen = runGate.state.value.busy events += "run" + goalSeen = request.goal runOverride?.invoke() ?: result }, taskStarted = { diff --git a/apps/android/app/src/test/kotlin/com/hopa/app/link/remote/RemoteTaskSenderTest.kt b/apps/android/app/src/test/kotlin/com/hopa/app/link/remote/RemoteTaskSenderTest.kt new file mode 100644 index 000000000..d8504a909 --- /dev/null +++ b/apps/android/app/src/test/kotlin/com/hopa/app/link/remote/RemoteTaskSenderTest.kt @@ -0,0 +1,176 @@ +package com.hopa.app.link.remote + +import com.hopa.backend.crypto.PayloadCipher +import com.hopa.backend.link.BackendLink +import com.hopa.backend.link.BackendState +import com.hopa.backend.link.TaskDraft +import com.hopa.backend.wire.BackendEnvelope +import java.util.Base64 +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test + +/** + * The phone's side of a send: the frame carries only ciphertext, and a peer's + * answer is shown only when it belongs to the send and opens under the + * household key. + */ +class RemoteTaskSenderTest { + private val key = ByteArray(32) { (it + 1).toByte() } + + @Test + fun `a send is sealed, addressed and reported as sent`() = runBlocking { + val link = SendRecordingLink() + val sender = RemoteTaskSender(deviceId = { "phone-1" }, link = { link }, contentKey = { key }) + + val state = sender.send("pc-1", "Studio", "open the settings app") + + assertEquals(TaskSendState.Sent("Studio", link.frames.single().id), state) + val frame = link.frames.single() + assertEquals("task.create", frame.type) + assertEquals("pc-1", frame.to) + assertEquals("phone-1", frame.from) + assertEquals("open the settings app", TaskDraft.goalOf(key, frame.body)) + assertFalse(frame.body.containsKey("goal"), "the goal must not travel in plaintext") + } + + @Test + fun `a sealed result after the acceptance ack is shown`() = runBlocking { + val link = SendRecordingLink() + val sender = RemoteTaskSender(deviceId = { "phone-1" }, link = { link }, contentKey = { key }) + sender.send("pc-1", "Studio", "open settings") + + sender.onReply(ack("srv-1")) + sender.onReply(result("srv-1", sealedText("opened it"))) + + assertEquals(TaskSendState.Replied("Studio", "opened it"), sender.state.value) + } + + @Test + fun `a result from another device is ignored`() = runBlocking { + val link = SendRecordingLink() + val sender = RemoteTaskSender(deviceId = { "phone-1" }, link = { link }, contentKey = { key }) + sender.send("pc-1", "Studio", "open settings") + + sender.onReply(ack("srv-1")) + sender.onReply(result("srv-1", sealedText("not yours"), from = "tablet-9")) + + assertTrue(sender.state.value is TaskSendState.Sent) + } + + @Test + fun `a result before the ack names an id is ignored`() = runBlocking { + val link = SendRecordingLink() + val sender = RemoteTaskSender(deviceId = { "phone-1" }, link = { link }, contentKey = { key }) + sender.send("pc-1", "Studio", "open settings") + + sender.onReply(result("srv-1", sealedText("too early"))) + + assertTrue(sender.state.value is TaskSendState.Sent) + } + + @Test + fun `a result sealed under another key is a schema failure`() = runBlocking { + val link = SendRecordingLink() + val sender = RemoteTaskSender(deviceId = { "phone-1" }, link = { link }, contentKey = { key }) + sender.send("pc-1", "Studio", "open settings") + + sender.onReply(ack("srv-1")) + sender.onReply( + result( + "srv-1", + Base64.getUrlEncoder().withoutPadding().encodeToString( + PayloadCipher.seal(ByteArray(32) { (it + 40).toByte() }, """{"text":"x"}""".toByteArray()), + ), + ), + ) + + assertEquals(TaskSendState.Failed("E_SCHEMA"), sender.state.value) + } + + @Test + fun `a peer error is its stable code`() = runBlocking { + val link = SendRecordingLink() + val sender = RemoteTaskSender(deviceId = { "phone-1" }, link = { link }, contentKey = { key }) + sender.send("pc-1", "Studio", "open settings") + + sender.onReply(ack("srv-1")) + sender.onReply( + BackendEnvelope( + id = "e-err", + type = "task.error", + ts = 0, + from = "pc-1", + to = "phone-1", + task = "srv-1", + body = buildJsonObject { + put("code", "E_POLICY") + put("message", "refused") + put("retryable", false) + }, + ), + ) + + assertEquals(TaskSendState.Failed("E_POLICY"), sender.state.value) + } + + @Test + fun `no link is a device failure, not a crash`() = runBlocking { + val sender = RemoteTaskSender(deviceId = { "phone-1" }, link = { null }, contentKey = { key }) + + assertEquals(TaskSendState.Failed("E_DEVICE"), sender.send("pc-1", "Studio", "open settings")) + } + + @Test + fun `no household key is a schema failure`() = runBlocking { + val sender = RemoteTaskSender(deviceId = { "phone-1" }, link = { SendRecordingLink() }, contentKey = { null }) + + assertEquals(TaskSendState.Failed("E_SCHEMA"), sender.send("pc-1", "Studio", "open settings")) + } + + private fun ack(serverTask: String): BackendEnvelope = BackendEnvelope( + id = "e-ack", + type = "task.ack", + ts = 0, + from = "server", + to = "phone-1", + body = buildJsonObject { put("task", serverTask) }, + ) + + private fun result(serverTask: String, sealed: String, from: String = "pc-1"): BackendEnvelope = BackendEnvelope( + id = "e-result", + type = "task.result", + ts = 0, + from = from, + to = "phone-1", + task = serverTask, + body = buildJsonObject { put("sealed", sealed) }, + ) + + private fun sealedText(text: String): String = Base64.getUrlEncoder().withoutPadding().encodeToString( + PayloadCipher.seal(key, buildJsonObject { put("text", text) }.toString().toByteArray()), + ) +} + +private class SendRecordingLink : BackendLink { + val frames = mutableListOf() + override val state = MutableStateFlow(BackendState.Disconnected) + override var onTask: (suspend (BackendEnvelope) -> Unit)? = null + override var onApproval: (suspend (BackendEnvelope) -> Unit)? = null + + override fun start(scope: CoroutineScope) = Unit + override suspend fun stop() = Unit + + override suspend fun send(frame: BackendEnvelope) { + frames += frame + } + + override suspend fun ack(task: BackendEnvelope) = Unit + override suspend fun ping() = Unit +} diff --git a/core/backend/src/main/kotlin/com/hopa/backend/link/BackendLink.kt b/core/backend/src/main/kotlin/com/hopa/backend/link/BackendLink.kt index 7d9e8914a..41e61ecc5 100644 --- a/core/backend/src/main/kotlin/com/hopa/backend/link/BackendLink.kt +++ b/core/backend/src/main/kotlin/com/hopa/backend/link/BackendLink.kt @@ -44,8 +44,8 @@ interface BackendLink { /** * Task replies addressed to this device (`task.ack`, `task.progress`, - * `task.result`, `task.error`). The Android app leaves this null; the - * sidecar wires it to the waiter for an approval it asked a phone. + * `task.result`, `task.error`). Android wires it to the task it last sent; + * the sidecar wires it to the waiter for an approval it asked a phone. */ var onReply: (suspend (BackendEnvelope) -> Unit)? get() = null From 367ab942db1f56079e9189ef7783596ca115bfa8 Mon Sep 17 00:00:00 2001 From: aharonamir Date: Mon, 30 Nov 2026 11:01:47 +0200 Subject: [PATCH 33/58] Send a task to the phone from the Windows side The PC could only receive; the window had no way to hand a goal to the phone. `task.send` seals the goal with the session's content key in the sidecar and sends a `task.create` through the gateway link; `devices.list` answers the picker from `GET /v1/devices` with the stored bearer. Both run on the backend scope so the stdin loop never waits on the socket or the server. The window gets one menu button and one dialog: choose a device, type a goal, and StatusText confirms "Sent to " or shows the sidecar's stable code. No goal is logged, echoed in a reply, or carried in `chat.changed`. Part of #32. --- .../EngineHostClientBackendTests.cs | 46 ++++ .../Integrations/Engine/EngineHostClient.cs | 35 +++ .../Ui/Dialogs/SendTaskWindow.xaml | 37 +++ .../Ui/Dialogs/SendTaskWindow.xaml.cs | 93 ++++++++ .../Ui/Shell/MainWindow.SendTask.cs | 43 ++++ .../Hopa.Windows/Ui/Shell/MainWindow.xaml | 15 +- .../com/hopa/sidecar/backend/GatewayHost.kt | 44 +++- .../com/hopa/sidecar/backend/TaskComposer.kt | 25 +++ .../com/hopa/sidecar/protocol/Protocol.kt | 33 +++ .../sidecar/protocol/handler/TaskHandler.kt | 71 +++++- .../com/hopa/sidecar/startup/ProtocolMode.kt | 2 +- .../protocol/handler/TaskHandlerTest.kt | 210 ++++++++++++++++++ 12 files changed, 646 insertions(+), 8 deletions(-) create mode 100644 apps/windows/Hopa.Windows/Ui/Dialogs/SendTaskWindow.xaml create mode 100644 apps/windows/Hopa.Windows/Ui/Dialogs/SendTaskWindow.xaml.cs create mode 100644 apps/windows/Hopa.Windows/Ui/Shell/MainWindow.SendTask.cs create mode 100644 apps/windows/sidecar/src/main/kotlin/com/hopa/sidecar/backend/TaskComposer.kt create mode 100644 apps/windows/sidecar/src/test/kotlin/com/hopa/sidecar/protocol/handler/TaskHandlerTest.kt diff --git a/apps/windows/Hopa.Windows.Tests/EngineHostClientBackendTests.cs b/apps/windows/Hopa.Windows.Tests/EngineHostClientBackendTests.cs index 8d9295648..03cf41147 100644 --- a/apps/windows/Hopa.Windows.Tests/EngineHostClientBackendTests.cs +++ b/apps/windows/Hopa.Windows.Tests/EngineHostClientBackendTests.cs @@ -146,4 +146,50 @@ public async Task BackendStatusAsyncSerializesTheType() Assert.Equal("backend.status", JsonNode.Parse(sent!)!["type"]!.GetValue()); } + + [Fact] + public async Task SendTaskAsyncSerializesTheTargetAndGoal() + { + var reader = new QueueReader(); + var writer = new LineWriter(); + var client = new EngineHostClient(new EngineTransport(writer, reader)); + string? sent = null; + writer.OnLine = line => + { + sent = line; + var id = JsonNode.Parse(line)!["id"]!.GetValue(); + reader.Push($"{{\"type\":\"task.send\",\"id\":\"{id}\",\"ok\":true,\"taskId\":\"t-1\"}}"); + }; + + var reply = await client.SendTaskAsync("phone-1", "open the settings app"); + + var message = JsonNode.Parse(sent!)!.AsObject(); + Assert.Equal("task.send", message["type"]!.GetValue()); + Assert.Equal("phone-1", message["toDeviceId"]!.GetValue()); + Assert.Equal("open the settings app", message["goal"]!.GetValue()); + Assert.Equal("t-1", reply?["taskId"]?.GetValue()); + } + + [Fact] + public async Task DevicesAsyncSerializesTheTypeAndReturnsTheItems() + { + var reader = new QueueReader(); + var writer = new LineWriter(); + var client = new EngineHostClient(new EngineTransport(writer, reader)); + string? sent = null; + writer.OnLine = line => + { + sent = line; + var id = JsonNode.Parse(line)!["id"]!.GetValue(); + reader.Push( + $"{{\"type\":\"devices.list\",\"id\":\"{id}\",\"ok\":true,\"items\":" + + "[{\"id\":\"phone-1\",\"name\":\"Pixel\",\"platform\":\"android\",\"current\":false}]}"); + }; + + var devices = await client.DevicesAsync(); + + Assert.Equal("devices.list", JsonNode.Parse(sent!)!["type"]!.GetValue()); + Assert.Single(devices); + Assert.Equal("Pixel", devices[0]["name"]!.GetValue()); + } } diff --git a/apps/windows/Hopa.Windows/Integrations/Engine/EngineHostClient.cs b/apps/windows/Hopa.Windows/Integrations/Engine/EngineHostClient.cs index f2c4d2535..64fb10c34 100644 --- a/apps/windows/Hopa.Windows/Integrations/Engine/EngineHostClient.cs +++ b/apps/windows/Hopa.Windows/Integrations/Engine/EngineHostClient.cs @@ -359,6 +359,41 @@ public Task CancelPairingAsync() => public Task BackendStatusAsync() => RequestAsync("backend.status", new JsonObject(), TimeSpan.FromSeconds(10)); + /// + /// Seals a goal with the household key, in the sidecar, and sends it to one + /// household device. The goal never leaves this call in plaintext. + /// + public Task SendTaskAsync(string toDeviceId, string goal) => + RequestAsync( + "task.send", + new JsonObject { ["toDeviceId"] = toDeviceId, ["goal"] = goal }, + TimeSpan.FromSeconds(20)); + + /// The household's devices for the composer's picker. + public async Task> DevicesAsync() + { + var response = await RequestAsync("devices.list", new JsonObject(), TimeSpan.FromSeconds(20)); + if (response["ok"]?.GetValue() != true) + { + // The sidecar names the stable code; never invent a list from a failure. + throw new InvalidOperationException(response["code"]?.GetValue() ?? "E_SYNC"); + } + + var items = new List(); + if (response["items"] is JsonArray array) + { + foreach (var item in array) + { + if (item is JsonObject obj) + { + items.Add(obj); + } + } + } + + return items; + } + public void SendDeviceResult( string id, bool ok, diff --git a/apps/windows/Hopa.Windows/Ui/Dialogs/SendTaskWindow.xaml b/apps/windows/Hopa.Windows/Ui/Dialogs/SendTaskWindow.xaml new file mode 100644 index 000000000..ec5dd5bfd --- /dev/null +++ b/apps/windows/Hopa.Windows/Ui/Dialogs/SendTaskWindow.xaml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + +