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/account/AccountViewModel.kt b/apps/android/app/src/main/kotlin/com/hopa/app/account/AccountViewModel.kt index afed4b296..0d982772a 100644 --- a/apps/android/app/src/main/kotlin/com/hopa/app/account/AccountViewModel.kt +++ b/apps/android/app/src/main/kotlin/com/hopa/app/account/AccountViewModel.kt @@ -76,6 +76,9 @@ class AccountViewModel( ) persist(account, privateKey, normalized) settings.setBackendContentKey(Base64.getEncoder().encodeToString(contentKey)) + // Sign-up writes the identity, then the key: the tuple is whole + // only after both, so mark it new once the key has landed. + settings.bumpBackendCredentialEpoch() } else { val account = accountClient(gatewayUrl).signIn( phone = normalized, 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..7de049e54 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,12 @@ 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.LiveSyncTrigger +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 +83,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 +165,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 @@ -357,6 +391,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 @@ -368,6 +427,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, @@ -408,6 +470,26 @@ 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() } + // The answer to a task this phone sent; a composer shows it, nothing runs. + backend.onReply = { frame -> sentTasks.onReply(frame) } + // A refused create: the composer matches it by the send's trace. + backend.onError = { frame -> sentTasks.onError(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 { + settings.settings.collect { current -> + if (current.backendDeviceId.isNotBlank()) sync.start() else sync.stop() + } + } + // A reconnect while the app stays in the foreground must pull too: the + // socket replays nothing a peer wrote while it was down and v0 has no + // push wake for sync. Only entering `Live` counts, not a re-emit. + val liveSync = LiveSyncTrigger { sync.onLinkLive() } + appScope.launch { + backend.state.collect { liveSync.onState(it) } + } } private fun startRunServiceInternal() { @@ -634,11 +716,46 @@ 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, + skipped = outcome.skippedTurns, + skippedRemote = outcome.skippedRemote, + ) + 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 + + /** + * 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() } + } + override val backendState: StateFlow get() = backend.state 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..651483067 --- /dev/null +++ b/apps/android/app/src/main/kotlin/com/hopa/app/feature/shell/SendTaskSheet.kt @@ -0,0 +1,130 @@ +package com.hopa.app.feature.shell + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +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.rememberScrollState +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.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.Sending -> "Sending to ${state.toName}…" + 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 && + sendState !is TaskSendState.Sending, + ) { + Text("Send") + } + }, + dismissButton = { + TextButton(onClick = onDismiss) { Text("Close") } + }, + ) +} diff --git a/apps/android/app/src/main/kotlin/com/hopa/app/feature/shell/SendTaskTrigger.kt b/apps/android/app/src/main/kotlin/com/hopa/app/feature/shell/SendTaskTrigger.kt new file mode 100644 index 000000000..d592ab701 --- /dev/null +++ b/apps/android/app/src/main/kotlin/com/hopa/app/feature/shell/SendTaskTrigger.kt @@ -0,0 +1,33 @@ +package com.hopa.app.feature.shell + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.statusBarsPadding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp + +/** 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..b0d6423e0 --- /dev/null +++ b/apps/android/app/src/main/kotlin/com/hopa/app/link/remote/RemoteTaskSender.kt @@ -0,0 +1,180 @@ +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.CompletableDeferred +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.withTimeoutOrNull +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.jsonObject + +/** + * One direction of a composer: seal a goal with the household key, send the + * `task.create`, and wait for the server to accept or refuse it. + * + * A `task.create` is not a success when it leaves the socket. The server answers + * a rejected create with a top-level `error` and an accepted one with a + * `task.ack` whose body names the task id it routes under; both echo the + * client's traceparent, so the send's `trace` is the correlation key. A send + * reports [TaskSendState.Sent] only for its own acceptance, the server's code + * for a refusal, and `E_TIMEOUT` when neither arrives — never a fabricated + * success. + * + * The peer's answer arrives later as a `task.result` for the server-assigned + * id. Only a reply from the peer we addressed, naming exactly that id, is 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 ackTimeoutMs: Long = DEFAULT_ACK_TIMEOUT_MS, +) { + private val _state = MutableStateFlow(TaskSendState.Idle) + val state: StateFlow = _state.asStateFlow() + + private class Pending( + val trace: String, + val toDeviceId: String, + val toName: String, + ) { + val answer = CompletableDeferred() + + @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 trace = frame.trace.orEmpty() + if (trace.isBlank()) return fail("E_SCHEMA") + val request = Pending(trace, toDeviceId, toName) + pending = request + _state.value = TaskSendState.Sending(toName) + try { + live.send(frame) + } catch (cancelled: CancellationException) { + throw cancelled + } catch (failed: Exception) { + return fail("E_DEVICE") + } + // The acceptance ack and the refusal race the same deadline. A late + // frame after this point belongs to a send nobody is showing. + val outcome = withTimeoutOrNull(ackTimeoutMs) { request.answer.await() } + ?: return fail("E_TIMEOUT") + return outcome + } + + /** + * A relayed `task.ack`/`task.result`/`task.error` on this device's socket. + * An ack is accepted only for the pending send's trace; a result only from + * the addressed peer for the server-assigned id. + */ + suspend fun onReply(frame: BackendEnvelope) { + val request = pending ?: return + when (frame.type) { + "task.ack" -> { + if (frame.trace != request.trace) return + val serverTask = (frame.body["task"] as? JsonPrimitive) + ?.takeIf { it.isString } + ?.contentOrNull + ?.takeIf { it.isNotBlank() } + ?: return + request.serverTask = serverTask + val accepted = TaskSendState.Sent(request.toName, serverTask) + _state.value = accepted + request.answer.complete(accepted) + } + + "task.result", "task.error" -> { + 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 + request.answer.complete(next) + } + } + } + + /** A gateway `error` frame: the server refused the create. Matched by trace. */ + suspend fun onError(frame: BackendEnvelope) { + val request = pending ?: return + if (frame.type != "error") return + if (frame.trace != request.trace) return + val code = (frame.body["code"] as? JsonPrimitive) + ?.takeIf { it.isString } + ?.contentOrNull + ?.takeIf { it.isNotBlank() } + ?: "E_AGENT" + pending = null + val refused = TaskSendState.Failed(code) + _state.value = refused + request.answer.complete(refused) + } + + /** 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 + val failed = TaskSendState.Failed(code) + _state.value = failed + return failed + } + + companion object { + /** How long a create may wait for the server's acceptance or refusal. */ + const val DEFAULT_ACK_TIMEOUT_MS = 10_000L + } +} diff --git a/apps/android/app/src/main/kotlin/com/hopa/app/link/remote/TaskSendState.kt b/apps/android/app/src/main/kotlin/com/hopa/app/link/remote/TaskSendState.kt new file mode 100644 index 000000000..6338bcbfd --- /dev/null +++ b/apps/android/app/src/main/kotlin/com/hopa/app/link/remote/TaskSendState.kt @@ -0,0 +1,18 @@ +package com.hopa.app.link.remote + +/** 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 server has not accepted or refused it yet. */ + data class Sending(val toName: String) : TaskSendState + + /** The server accepted the create; [taskId] is the id it routes under. */ + 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 +} diff --git a/apps/android/app/src/main/kotlin/com/hopa/app/link/session/BackendIdentity.kt b/apps/android/app/src/main/kotlin/com/hopa/app/link/session/BackendIdentity.kt index a4a3a470e..106d9d7e0 100644 --- a/apps/android/app/src/main/kotlin/com/hopa/app/link/session/BackendIdentity.kt +++ b/apps/android/app/src/main/kotlin/com/hopa/app/link/session/BackendIdentity.kt @@ -101,12 +101,36 @@ internal class BackendIdentity( settings.setBackendAccessToken(credentials.accessToken) settings.setBackendRefreshToken(credentials.refreshToken) settings.setBackendPrivateKey(privateKey) - settings.update { - it.copy( + settings.update { current -> + val rePaired = current.backendDeviceId != credentials.deviceId || + current.backendHouseholdId != credentials.householdId + val next = current.copy( backendUrl = credentials.gatewayUrl, backendDeviceId = credentials.deviceId, backendHouseholdId = credentials.householdId, ) + if (!rePaired) { + next + } else { + // Another household's cursor would sit above this one's earliest + // ops, and its title record is not this household's history. + next.copy( + backendSyncSeq = 0, + backendSyncHouseholdId = "", + backendSyncDeviceId = "", + backendSyncedTitles = "", + backendSyncedTitlesHouseholdId = "", + ) + } } + // The tokens landed before the identity, so the tuple is only whole now. + // The bump closes the common tear: a pass that read the old tokens and + // checks after this line aborts. It does not close two windows — a pass + // whose whole read falls between the identity write and this line, and a + // process kill in that same gap, which leaves the tear on disk with an + // unchanged epoch. Both are a few store writes wide and need a + // coincident trigger; the cost if hit is a pass sealed under the old + // household key, which peers cannot open and which wedges that log. + settings.bumpBackendCredentialEpoch() } } 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..cb020a8e6 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,22 @@ 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 + + /** A relayed reply to a task this phone sent (`task.ack`, `task.result`, …). */ + @Volatile + var onReply: (suspend (BackendEnvelope) -> Unit)? = null + + /** + * A gateway `error` frame: the server refused a message this phone sent. The + * link already routes `error` with the board frames; the session narrows it + * to refusals so a composer can match one by its trace. + */ + @Volatile + var onError: (suspend (BackendEnvelope) -> Unit)? = null + /** The live socket, for the runner that answers a delivery on it. */ fun currentLink(): BackendLink? = link @@ -282,6 +298,18 @@ 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 top-level `error` is a refusal; the link routes it with board frames, + // so the session narrows it before a composer sees it. + created.onBoard = { envelope -> + if (envelope.type == "error") { + onError?.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/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..979a52290 --- /dev/null +++ b/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/BackendSync.kt @@ -0,0 +1,560 @@ +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.contracts.json.HopaJson +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.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 + +/** + * 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 one credential generation: the epoch is captured before + * the identity, token and key reads and checked after them, so a claim or a + * sign-up that lands mid-pass aborts instead of mixing two households. 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: + * - The titles the last finished pass established are persisted, with the + * household they belong to, so a title is pushed only when it differs from + * that record. A pulled title is authoritative (server seq decides): it + * overwrites a local rename this phone has not pushed yet, and the record + * then keeps that rename from being pushed back. + * - An op this device wrote is inert when it comes back on a later pull (the + * engine's `ignore` predicate); the cursor still moves past it. + */ +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) { + 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. */ + 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() + + /** + * The backend link entered `Live`: pull whatever a peer wrote while the + * socket was down. A repeated `Live` is filtered by [LiveSyncTrigger]. + */ + fun onLinkLive() { + // A live link implies an identity, so arm the triggers even when the + // settings collector has not run yet. + start() + 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 { + // One credential generation for the whole pass. The tuple is written in + // pieces (tokens, key, identity, in different orders per flow), so two + // identity reads can agree while the token and key come from different + // pairings. The epoch is bumped when any part of the tuple lands: if it + // moved, the three reads below may belong to two households. The check + // cannot see a pass whose whole read falls inside that write sequence, + // so a tear is still possible in a window a few store writes wide. + val current = settings.settings.first() + val epoch = current.backendCredentialEpoch + 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 confirmed = settings.settings.first() + if (confirmed.backendCredentialEpoch != epoch) { + return SyncOutcome.SignedOut + } + // A sign-out clears the epoch back to 0, so the marker alone cannot see + // it; the identity still can. + if (confirmed.backendDeviceId != current.backendDeviceId || + confirmed.backendHouseholdId != current.backendHouseholdId || + confirmed.backendUrl != current.backendUrl + ) { + return SyncOutcome.SignedOut + } + val key = decodeKey(storedKey) ?: return SyncOutcome.Failed("E_KEY") + + val startedAt: Long + val storedTitles: String + val householdId = current.backendHouseholdId + val deviceId = current.backendDeviceId + // The cursor and the title record only mean something for the pairing + // that wrote them. A re-pair leaves another household's seq on top of + // this one's earliest ops, and its titles are not this household's + // history, so a mismatched owner starts at 0 with no titles. + val cursorOwned = current.backendSyncHouseholdId == householdId && + current.backendSyncDeviceId == deviceId + val titlesOwned = current.backendSyncedTitlesHouseholdId == householdId + if (cursorOwned && titlesOwned) { + startedAt = current.backendSyncSeq + storedTitles = current.backendSyncedTitles + } else { + startedAt = 0 + storedTitles = "" + settings.setBackendSyncState(0, householdId, deviceId) + settings.setBackendSyncedTitles("", householdId) + } + val cursor = PassCursor(startedAt) + 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 = http, + codec = SyncCodec(key), + target = target, + cursor = cursor, + token = { token }, + baseUrl = { baseUrl }, + // This device's own ops come back on a pull. The cursor must move + // past them, but their content is never merged again: re-applying + // our own older title was how a rename could undo itself. + ignore = { op -> op.fromDevice == deviceId }, + ) + + val report = try { + engine.pull() + } catch (cancelled: CancellationException) { + throw cancelled + } catch (refused: SyncHttpException) { + return SyncOutcome.Failed(failureCode(refused)) + } catch (_: Exception) { + return SyncOutcome.Failed("E_SYNC") + } + + // 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. A quiet pass still records the owner once, + // so the next pass knows whose seq this is. + if (cursor.read() != startedAt || !cursorOwned) { + settings.setBackendSyncState(cursor.read(), householdId, deviceId) + } + var persistedTitles = persistTitles(recordedTitles, storedTitles, householdId) + publish(target.changed) + + val backlog = try { + backlog(current, recordedTitles) + } 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 } + // 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, householdId) + } + return SyncOutcome.Done( + applied = report.applied, + pushed = pushed, + skippedTurns = backlog.skippedTurns, + skippedRemote = report.skipped.size, + ) + } + + /** + * 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 suspend fun persistTitles( + titles: Map, + persisted: String, + householdId: String, + ): String { + val encoded = encodeTitles(titles) + if (encoded != persisted) { + settings.setBackendSyncedTitles(encoded, householdId) + } + 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 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, recordedTitles: Map): Backlog { + val device = current.backendDeviceId + val turns = mutableListOf() + val threads = mutableListOf() + val titlePushes = mutableMapOf() + var skippedTurns = 0 + 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() + 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 = 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( + drafts = threads + SyncBacklog.orderTurns(turns), + skippedTurns = skippedTurns, + titles = titlePushes, + ) + } + + 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 + 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 } + + private class Backlog( + val drafts: List, + val skippedTurns: Int, + /** 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 + + 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, + private val onRemoteTitle: (threadId: String, title: String) -> Unit, + ) : SyncTarget { + private var rows: Map? = null + private val changedIds = linkedSetOf() + + val changed: Set get() = changedIds + + 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, + ), + ) + changedIds += 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 tombstone is final: a later title must not resurrect the thread, + // and a deleted thread never takes a title. + val nextTitle = if (gone) "" 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) + 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 && title != null && 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 + + /** 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 = "" + + /** + * 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" + + val ROLES = setOf("user", "assistant") + } +} diff --git a/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/LiveSyncTrigger.kt b/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/LiveSyncTrigger.kt new file mode 100644 index 000000000..b3c73feaa --- /dev/null +++ b/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/LiveSyncTrigger.kt @@ -0,0 +1,23 @@ +package com.hopa.app.link.sync + +import com.hopa.backend.link.BackendState + +/** + * Runs a pass whenever the backend link enters `Live`. + * + * A socket that drops and reconnects while the app stays in the foreground + * must pull again: the gateway does not replay what a peer wrote while this + * phone was offline, and v0 has no push wake for sync. A repeated `Live` + * (presence, queue count) 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 + } +} 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..26f5471a5 --- /dev/null +++ b/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/SyncOutcome.kt @@ -0,0 +1,26 @@ +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; [skippedTurns] local turns were too large for one op and stayed + * on this phone; [skippedRemote] remote ops were unusable, so the cursor + * stepped over them and their content never arrived. + */ + data class Done( + val applied: Int, + val pushed: Int, + val skippedTurns: Int = 0, + val skippedRemote: Int = 0, + ) : 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/SyncOwner.kt b/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/SyncOwner.kt new file mode 100644 index 000000000..e180a887c --- /dev/null +++ b/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/SyncOwner.kt @@ -0,0 +1,13 @@ +package com.hopa.app.link.sync + +/** 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, +} 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..06fe04ba4 --- /dev/null +++ b/apps/android/app/src/main/kotlin/com/hopa/app/link/sync/SyncOwnership.kt @@ -0,0 +1,27 @@ +package com.hopa.app.link.sync + +import com.hopa.stores.SettingsRepository +import kotlinx.coroutines.flow.first + +/** + * 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/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/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..e3320fd2a --- /dev/null +++ b/apps/android/app/src/test/kotlin/com/hopa/app/link/remote/RemoteTaskSenderTest.kt @@ -0,0 +1,265 @@ +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.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.async +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 server answers a create with either an + * acceptance `task.ack` or a top-level `error`, both echoing the client's + * traceparent, so the trace is the correlation key: a send reports success only + * when its own ack arrives, and a refusal is the server's code. + */ +class RemoteTaskSenderTest { + private val key = ByteArray(32) { (it + 1).toByte() } + + @Test + fun `a send is sealed and addressed while it waits for its ack`() = runBlocking { + val link = SendRecordingLink() + val sender = sender(link) + val job = async { sender.send("pc-1", "Studio", "open the settings app") } + link.sent.await() + + 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") + assertEquals(TaskSendState.Sending("Studio"), sender.state.value) + + sender.onReply(ack("srv-1", frame.trace)) + assertEquals(TaskSendState.Sent("Studio", "srv-1"), job.await()) + } + + @Test + fun `a refused create is the server's error code`() = runBlocking { + val link = SendRecordingLink() + val sender = sender(link) + val job = async { sender.send("pc-1", "Studio", "open the settings app") } + link.sent.await() + + sender.onError(error("E_TENANT", link.frames.single().trace)) + + assertEquals(TaskSendState.Failed("E_TENANT"), job.await()) + assertEquals(TaskSendState.Failed("E_TENANT"), sender.state.value) + } + + @Test + fun `an error for another trace is ignored`() = runBlocking { + val link = SendRecordingLink() + val sender = sender(link) + val job = async { sender.send("pc-1", "Studio", "open settings") } + link.sent.await() + + sender.onError(error("E_RATE", OTHER_TRACE)) + + assertTrue(sender.state.value is TaskSendState.Sending) + sender.onReply(ack("srv-1", link.frames.single().trace)) + assertEquals(TaskSendState.Sent("Studio", "srv-1"), job.await()) + } + + @Test + fun `a stale ack for another trace is ignored`() = runBlocking { + val link = SendRecordingLink() + val sender = sender(link) + val job = async { sender.send("pc-1", "Studio", "open settings") } + link.sent.await() + + sender.onReply(ack("srv-other", OTHER_TRACE)) + + assertTrue(sender.state.value is TaskSendState.Sending) + sender.onReply(ack("srv-1", link.frames.single().trace)) + assertEquals(TaskSendState.Sent("Studio", "srv-1"), job.await()) + } + + @Test + fun `a missing ack is a timeout code, never a fabricated success`() = runBlocking { + val link = SendRecordingLink() + val sender = sender(link, ackTimeoutMs = 100) + + assertEquals(TaskSendState.Failed("E_TIMEOUT"), sender.send("pc-1", "Studio", "open settings")) + } + + @Test + fun `a sealed result after the acceptance ack is shown under the server id`() = runBlocking { + val link = SendRecordingLink() + val sender = sender(link) + val job = async { sender.send("pc-1", "Studio", "open settings") } + link.sent.await() + sender.onReply(ack("srv-1", link.frames.single().trace)) + job.await() + + 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 = sender(link) + val job = async { sender.send("pc-1", "Studio", "open settings") } + link.sent.await() + sender.onReply(ack("srv-1", link.frames.single().trace)) + job.await() + + sender.onReply(result("srv-1", sealedText("not yours"), from = "tablet-9")) + + assertEquals(TaskSendState.Sent("Studio", "srv-1"), sender.state.value) + } + + @Test + fun `a result before the ack names an id is ignored`() = runBlocking { + val link = SendRecordingLink() + val sender = sender(link) + val job = async { sender.send("pc-1", "Studio", "open settings") } + link.sent.await() + + sender.onReply(result("srv-1", sealedText("too early"))) + + assertTrue(sender.state.value is TaskSendState.Sending) + sender.onReply(ack("srv-1", link.frames.single().trace)) + assertEquals(TaskSendState.Sent("Studio", "srv-1"), job.await()) + } + + @Test + fun `a result sealed under another key is a schema failure`() = runBlocking { + val link = SendRecordingLink() + val sender = sender(link) + val job = async { sender.send("pc-1", "Studio", "open settings") } + link.sent.await() + sender.onReply(ack("srv-1", link.frames.single().trace)) + job.await() + + val foreign = Base64.getUrlEncoder().withoutPadding().encodeToString( + PayloadCipher.seal(ByteArray(32) { (it + 40).toByte() }, """{"text":"x"}""".toByteArray()), + ) + sender.onReply(result("srv-1", foreign)) + + assertEquals(TaskSendState.Failed("E_SCHEMA"), sender.state.value) + } + + @Test + fun `a peer error is its stable code`() = runBlocking { + val link = SendRecordingLink() + val sender = sender(link) + val job = async { sender.send("pc-1", "Studio", "open settings") } + link.sent.await() + sender.onReply(ack("srv-1", link.frames.single().trace)) + job.await() + + 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 sender(link: BackendLink, ackTimeoutMs: Long = 5_000) = RemoteTaskSender( + deviceId = { "phone-1" }, + link = { link }, + contentKey = { key }, + ackTimeoutMs = ackTimeoutMs, + ) + + private fun ack(serverTask: String, trace: String?): BackendEnvelope = BackendEnvelope( + id = "e-ack", + type = "task.ack", + ts = 0, + trace = trace, + from = "server", + to = "phone-1", + body = buildJsonObject { put("task", serverTask) }, + ) + + private fun error(code: String, trace: String?): BackendEnvelope = BackendEnvelope( + id = "e-error", + type = "error", + ts = 0, + trace = trace, + to = "phone-1", + body = buildJsonObject { put("code", code) }, + ) + + 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 companion object { + const val OTHER_TRACE = "00-11111111111111111111111111111111-2222222222222222-01" + } +} + +private class SendRecordingLink : BackendLink { + val frames = mutableListOf() + val sent = CompletableDeferred() + 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 + sent.complete(Unit) + } + + override suspend fun ack(task: BackendEnvelope) = Unit + override suspend fun ping() = Unit +} diff --git a/apps/android/app/src/test/kotlin/com/hopa/app/link/session/BackendIdentityTest.kt b/apps/android/app/src/test/kotlin/com/hopa/app/link/session/BackendIdentityTest.kt index 218b34bd3..6b63fb8a6 100644 --- a/apps/android/app/src/test/kotlin/com/hopa/app/link/session/BackendIdentityTest.kt +++ b/apps/android/app/src/test/kotlin/com/hopa/app/link/session/BackendIdentityTest.kt @@ -5,6 +5,7 @@ import com.hopa.app.link.session.SessionFixtures.gateway import com.hopa.app.link.session.SessionFixtures.pairingServer import com.hopa.backend.pairing.BackendPairing import com.hopa.backend.pairing.BackendPairingFailure +import com.hopa.backend.pairing.PairingLink import java.util.concurrent.TimeUnit import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -20,6 +21,80 @@ import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test class BackendIdentityTest { + @Test + fun `a re-pair into another household clears the old cursor and titles`() = runBlocking { + val server = pairingServer( + MockResponse().setResponseCode(200).setBody( + """{"deviceId":"d2","householdId":"h2","accessToken":"a2","refreshToken":"r2", + "expiresAt":"2026-11-17T00:15:00Z"}""".trimIndent(), + ), + ) + try { + val settings = FakeSettings().paired(gateway(server)) + // What the old household left behind. + settings.update { + it.copy( + backendSyncSeq = 9, + backendSyncHouseholdId = "h1", + backendSyncDeviceId = "d1", + backendSyncedTitles = """{"c-1":"Trip"}""", + backendSyncedTitlesHouseholdId = "h1", + backendCredentialEpoch = 5, + ) + } + val identity = BackendIdentity(settings) { BackendPairing(it) } + val link = PairingLink(householdId = "h2", session = "s1", gatewayUrl = gateway(server)) + + identity.claim(link, "Xiaomi", pushToken = null) + + assertEquals("h2", settings.snapshot.backendHouseholdId) + assertEquals(0L, settings.snapshot.backendSyncSeq) + assertEquals("", settings.snapshot.backendSyncHouseholdId) + assertEquals("", settings.snapshot.backendSyncDeviceId) + assertEquals("", settings.snapshot.backendSyncedTitles) + assertEquals("", settings.snapshot.backendSyncedTitlesHouseholdId) + // The new credential tuple is marked as new. + assertEquals(6L, settings.snapshot.backendCredentialEpoch) + } finally { + server.shutdown() + } + } + + @Test + fun `a re-pair into the same household keeps the cursor`() = runBlocking { + val server = pairingServer( + MockResponse().setResponseCode(200).setBody( + """{"deviceId":"d1","householdId":"h1","accessToken":"a2","refreshToken":"r2", + "expiresAt":"2026-11-17T00:15:00Z"}""".trimIndent(), + ), + ) + try { + val settings = FakeSettings().paired(gateway(server)) + settings.update { + it.copy( + backendSyncSeq = 4, + backendSyncHouseholdId = "h1", + backendSyncDeviceId = "d1", + backendSyncedTitles = """{"c-1":"Trip"}""", + backendSyncedTitlesHouseholdId = "h1", + backendCredentialEpoch = 5, + ) + } + val identity = BackendIdentity(settings) { BackendPairing(it) } + val link = PairingLink(householdId = "h1", session = "s1", gatewayUrl = gateway(server)) + + identity.claim(link, "Xiaomi", pushToken = null) + + assertEquals(4L, settings.snapshot.backendSyncSeq) + assertEquals("h1", settings.snapshot.backendSyncHouseholdId) + assertEquals("""{"c-1":"Trip"}""", settings.snapshot.backendSyncedTitles) + // A new device credential is a new tuple even in the same household. + assertEquals(6L, settings.snapshot.backendCredentialEpoch) + } finally { + server.shutdown() + } + } + @Test fun `a cancelled refresh still persists the rotated pair`() = runBlocking { val server = pairingServer( 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..bd37c3d9e 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())) @@ -383,8 +407,11 @@ class BackendSessionTest { privateKey = "key", ) + // The factory appends the link before connect() calls start() on + // it, so wait for both: a bare size check can observe the window in + // between and see a link that has not started yet. withTimeout(WAIT_MS) { - while (links.isEmpty()) delay(10) + while (links.isEmpty() || !links.first().started) delay(10) } assertEquals(1, links.size) assertTrue(links.first().started) 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..bce97b837 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 @@ -152,6 +153,7 @@ internal object SessionFixtures { backendUrl = "", backendDeviceId = "", backendHouseholdId = "", + backendCredentialEpoch = 0, ) } } 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..166ebb06f --- /dev/null +++ b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/BackendSyncTest.kt @@ -0,0 +1,676 @@ +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.assertNotEquals +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 cursor from another household starts again at zero`() = 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, + ) + val settings = signedIn("d1") + // What a pass in household A left behind. + settings.update { it.copy(backendHouseholdId = "hA", backendSyncSeq = 7) } + // The same phone is paired into household B. + settings.update { it.copy(backendHouseholdId = "hB", backendDeviceId = "d2") } + val sync = BackendSync(settings = settings, store = store, http = server, scope = this) + + val outcome = sync.syncNow() as SyncOutcome.Done + + // Household B's log starts at 1: asking after 7 would never see it. + assertEquals(listOf(0L), server.pullAfters) + assertEquals(1, outcome.applied) + assertEquals("one", store.allWithDeleted().single { it.id == "c-1" }.messages.single().text) + // The cursor now belongs to B. + assertEquals("hB", settings.current.backendSyncHouseholdId) + assertEquals("d2", settings.current.backendSyncDeviceId) + assertEquals(1L, settings.current.backendSyncSeq) + } + + @Test + fun `a title record from another household does not suppress the push`() = runBlocking { + val store = InMemoryConversationStore() + store.adopt( + Conversation( + id = "c-1", + title = "Trip", + messages = listOf(ChatMessage("m-1", "user", "hi", 1)), + updatedAt = 1, + ), + ) + val server = FakeSyncServer() + val settings = signedIn("d1") + // Household A's record already holds this title; household B has never + // seen it, so B must push it. + settings.update { + it.copy( + backendHouseholdId = "hA", + backendSyncHouseholdId = "hA", + backendSyncDeviceId = "d1", + backendSyncedTitles = """{"c-1":"Trip"}""", + backendSyncedTitlesHouseholdId = "hA", + ) + } + settings.update { it.copy(backendHouseholdId = "hB", backendDeviceId = "d2") } + val sync = BackendSync(settings = settings, store = store, http = server, scope = this) + + sync.syncNow() + + assertEquals(1, server.pushBatches.single().count { it.kind == SyncKind.THREAD_UPSERT }) + assertEquals("Trip", server.titleOf("c-1")) + assertEquals("hB", settings.current.backendSyncedTitlesHouseholdId) + } + + @Test + fun `a pairing that lands mid-pass aborts before sending`() = runBlocking { + val store = InMemoryConversationStore() + val chat = store.create() + store.append(chat.id, ChatMessage("m-1", "user", "hello", 10)) + val server = FakeSyncServer() + val settings = signedIn("d1") + settings.update { it.copy(backendHouseholdId = "hA") } + // A claim for household B lands after the pass read A's token: B's key + // and B's identity must not be combined with A's token. + settings.afterTokenRead = { + settings.setBackendAccessToken("a2") + settings.setBackendContentKey(OTHER_CONTENT_KEY_BASE64) + settings.update { it.copy(backendHouseholdId = "hB", backendDeviceId = "d2") } + } + val sync = BackendSync(settings = settings, store = store, http = server, scope = this) + + val outcome = sync.syncNow() + + assertEquals(SyncOutcome.SignedOut, outcome) + assertEquals(0, server.pulls) + assertTrue(server.pushBatches.isEmpty()) + } + + @Test + fun `a pulled own op is not reported as skipped`() = runBlocking { + val store = InMemoryConversationStore() + val server = FakeSyncServer() + // A turn this device wrote comes back on a pull: the cursor must move + // past it, but nothing was lost, so it is not a skip. + server.seed( + SyncKind.TURN_APPEND, + "c-1", + "m-1", + turnPayload("user", "mine", 10), + opId = "m-1", + clientAt = 10, + fromDevice = "d1", + ) + val settings = signedIn("d1") + val sync = BackendSync(settings = settings, store = store, http = server, scope = this) + + val outcome = sync.syncNow() as SyncOutcome.Done + + assertEquals(0, outcome.applied) + assertEquals(0, outcome.skippedRemote) + assertEquals(1L, settings.current.backendSyncSeq) + assertTrue(store.all().isEmpty()) + } + + @Test + fun `a genuinely unusable remote op is still reported as skipped`() = runBlocking { + val store = InMemoryConversationStore() + val server = FakeSyncServer() + // A peer's role this store cannot hold: the engine records a skip. + server.seed( + SyncKind.TURN_APPEND, + "c-1", + "m-bad", + turnPayload("system", "hello", 10), + opId = "m-bad", + clientAt = 10, + fromDevice = "pc", + ) + val settings = signedIn("d1") + val sync = BackendSync(settings = settings, store = store, http = server, scope = this) + + val outcome = sync.syncNow() as SyncOutcome.Done + + assertEquals(0, outcome.applied) + assertEquals(1, outcome.skippedRemote) + assertEquals(1L, settings.current.backendSyncSeq) + assertTrue(store.all().isEmpty()) + } + + @Test + fun `a credential write between the token and key reads aborts the pass`() = runBlocking { + val store = InMemoryConversationStore() + val chat = store.create() + store.append(chat.id, ChatMessage("m-1", "user", "hello", 10)) + val server = FakeSyncServer() + val settings = signedIn("d1") + settings.update { it.copy(backendCredentialEpoch = 5) } + // A claim finishes between the token and the key read: the tuple the + // pass holds is no longer the stored one, even if the identity agrees. + settings.afterTokenRead = { settings.bumpBackendCredentialEpoch() } + val sync = BackendSync(settings = settings, store = store, http = server, scope = this) + + assertEquals(SyncOutcome.SignedOut, sync.syncNow()) + assertEquals(0, server.pulls) + assertTrue(server.pushBatches.isEmpty()) + } + + @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() + // A cursor this pairing already wrote; only ownership makes it usable. + settings.update { it.copy(backendSyncSeq = 5, backendSyncDeviceId = "d1") } + 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()) + } + + @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 { + // 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("Mine", deletedAt = 0, clientAt = 1), + opId = "peer-title", + clientAt = 1, + ) + + 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 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, + ) + + 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, + ), + ) + val server = FakeSyncServer() + val sync = BackendSync(settings = signedIn(), store = store, http = server, scope = this) + sync.syncNow() + + store.append("c-1", ChatMessage("m-2", "assistant", "hello", 2)) + val second = sync.syncNow() as SyncOutcome.Done + + 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" }) + } + + @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 `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, + "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() + // B sees Alpha, then renames on top of it. + syncB.syncNow() + storeB.rename("c-1", "Beta") + syncB.syncNow() + + syncA.syncNow() + 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/FakeSyncServer.kt b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/FakeSyncServer.kt new file mode 100644 index 000000000..03b041edb --- /dev/null +++ b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/FakeSyncServer.kt @@ -0,0 +1,105 @@ +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.SyncDraft +import com.hopa.backend.sync.client.SyncHttp +import com.hopa.backend.sync.client.SyncHttpException +import com.hopa.backend.sync.client.SyncKind +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonPrimitive + +/** + * 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. [forDevice] makes a second phone or PC view over the same log. + */ +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>() + + /** 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 + + /** 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 { + (pushFailure ?: failure)?.let { throw it } + baseUrls += baseUrl + pushBatches += ops + val accepted = ops.map { op -> + val duplicate = log.find(op.opId) + if (duplicate != null) { + PushAck(op.opId, duplicate.seq, duplicate = true) + } else { + 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 = log.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 = log.stored.filter { it.seq > after }.sortedBy { it.seq }.take(limit) + val last = page.lastOrNull()?.seq ?: after + return PullAnswer( + ops = page, + hasMore = log.stored.any { it.seq > last }, + head = log.stored.size.toLong(), + ) + } + + fun seed( + kind: SyncKind, + threadId: String, + turnId: String?, + payload: JsonObject, + opId: String, + clientAt: Long, + fromDevice: String = "pc", + ): RemoteSyncOp = log.append( + opId, + kind, + threadId, + turnId, + clientAt, + log.seal(SyncDraft(opId, kind, threadId, turnId, payload, clientAt)), + fromDevice, + ) + + 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? = log.stored.asReversed() + .firstOrNull { it.kind == SyncKind.THREAD_UPSERT && it.threadId == threadId } + ?.let { op -> log.open(op)["title"]?.jsonPrimitive?.content } +} diff --git a/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/FakeSyncSettings.kt b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/FakeSyncSettings.kt new file mode 100644 index 000000000..f33e0f74e --- /dev/null +++ b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/FakeSyncSettings.kt @@ -0,0 +1,103 @@ +package com.hopa.app.link.sync + +import com.hopa.stores.AppSettings +import com.hopa.stores.SettingsRepository +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow + +/** + * 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 = "" + + /** + * Runs right after the access token is read, so a test can model a pairing + * claim landing between the reads one pass makes. + */ + var afterTokenRead: (suspend () -> Unit)? = null + + 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 { + val value = accessToken + afterTokenRead?.invoke() + return value + } + 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, + backendSyncHouseholdId = "", + backendSyncDeviceId = "", + backendSyncedTitles = "", + backendSyncedTitlesHouseholdId = "", + backendCredentialEpoch = 0, + ) + } +} diff --git a/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/LiveSyncTriggerTest.kt b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/LiveSyncTriggerTest.kt new file mode 100644 index 000000000..be42fe638 --- /dev/null +++ b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/LiveSyncTriggerTest.kt @@ -0,0 +1,48 @@ +package com.hopa.app.link.sync + +import com.hopa.backend.link.BackendState +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test + +/** + * A reconnect while the app stays in the foreground must pull again: the + * gateway does not replay what a peer wrote while the socket was down, and v0 + * has no push wake for sync. + */ +class LiveSyncTriggerTest { + private val live = BackendState.Live(deviceId = "d1", queued = 0, peers = emptyList()) + + @Test + fun `entering live runs a pass, a repeated live and a departure run none`() { + var passes = 0 + val trigger = LiveSyncTrigger { passes += 1 } + + trigger.onState(BackendState.Disconnected) + assertEquals(0, passes) + + trigger.onState(live) + assertEquals(1, passes) + + // A presence or queue re-emit is not a reconnect. + trigger.onState(live) + assertEquals(1, passes) + + trigger.onState(BackendState.Connecting) + assertEquals(1, passes) + + trigger.onState(live) + assertEquals(2, passes) + } + + @Test + fun `a failed state that recovers runs one more pass`() { + var passes = 0 + val trigger = LiveSyncTrigger { passes += 1 } + + trigger.onState(live) + trigger.onState(BackendState.Failed("timeout", needsPairing = false)) + trigger.onState(live) + + assertEquals(2, passes) + } +} diff --git a/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/SharedSyncLog.kt b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/SharedSyncLog.kt new file mode 100644 index 000000000..2c94938b0 --- /dev/null +++ b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/SharedSyncLog.kt @@ -0,0 +1,48 @@ +package com.hopa.app.link.sync + +import com.hopa.backend.sync.client.RemoteSyncOp +import com.hopa.backend.sync.client.SyncCodec +import com.hopa.backend.sync.client.SyncDraft +import com.hopa.backend.sync.client.SyncKind +import java.util.Base64 +import kotlinx.serialization.json.JsonObject + +/** 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] +} 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..e25804504 --- /dev/null +++ b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/SyncFixtures.kt @@ -0,0 +1,13 @@ +package com.hopa.app.link.sync + +import java.util.Base64 + +/** 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) + +/** Another household's key, for the "never mix two pairings" cases. */ +internal val OTHER_CONTENT_KEY_BASE64: String = + Base64.getEncoder().encodeToString(ByteArray(32) { index -> (index + 64).toByte() }) 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())) + } +} diff --git a/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/threadPayload.kt b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/threadPayload.kt new file mode 100644 index 000000000..41eb95fcc --- /dev/null +++ b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/threadPayload.kt @@ -0,0 +1,15 @@ +package com.hopa.app.link.sync + +import com.hopa.contracts.json.HopaJson +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.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/turnPayload.kt b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/turnPayload.kt new file mode 100644 index 000000000..a29a0756b --- /dev/null +++ b/apps/android/app/src/test/kotlin/com/hopa/app/link/sync/turnPayload.kt @@ -0,0 +1,11 @@ +package com.hopa.app.link.sync + +import com.hopa.contracts.json.HopaJson +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonObject + +/** 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 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..ca300de00 --- /dev/null +++ b/apps/android/app/src/test/kotlin/com/hopa/feature/conversations/ConversationsSyncViewModelTest.kt @@ -0,0 +1,131 @@ +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 `a sync that skipped remote ops says so`() = runTest(dispatcher) { + val deps = FakeConversationsDependencies() + deps.outcome = ChatSyncOutcome(adopted = 1, tombstoned = 0, skippedRemote = 2) + val viewModel = ConversationsViewModel(deps) + advanceUntilIdle() + + viewModel.sync() + advanceUntilIdle() + + assertEquals("Synced: 1 chats, 2 skipped", viewModel.state.value.message) + } + + @Test + fun `a sync with no remote skips does not say skipped`() = runTest(dispatcher) { + val deps = FakeConversationsDependencies() + deps.outcome = ChatSyncOutcome(adopted = 3, tombstoned = 0) + val viewModel = ConversationsViewModel(deps) + advanceUntilIdle() + + viewModel.sync() + advanceUntilIdle() + + assertEquals("Synced: 3 chats", 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/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/DataStoreSettingsRepository.kt b/apps/android/data/src/main/kotlin/com/hopa/data/store/DataStoreSettingsRepository.kt index f90e99db4..fc7c748c2 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 @@ -12,7 +13,6 @@ import com.hopa.stores.DEFAULT_BACKEND_URL import com.hopa.stores.SecretStore import com.hopa.stores.SettingsRepository import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map private val Context.settingsDataStore by preferencesDataStore(name = "hopa_settings") @@ -25,8 +25,13 @@ class DataStoreSettingsRepository( context.settingsDataStore.data.map(DataStoreSettingsRepository::settingsFrom) override suspend fun update(transform: (AppSettings) -> AppSettings) { - val next = transform(settings.first()) context.settingsDataStore.edit { prefs -> + // Transform the current preferences inside `edit`, not a snapshot + // read outside it: two writers that both read first would otherwise + // write whole-map snapshots and silently revert each other (the + // sync cursor, the title record and the credential epoch all share + // this path with the UI and the sign-in flow). + val next = transform(settingsFrom(prefs)) prefs[PROVIDER] = next.provider prefs[ENDPOINT] = next.endpoint prefs[MODEL] = next.model @@ -55,6 +60,12 @@ 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[BACKEND_SYNC_HOUSEHOLD_ID] = next.backendSyncHouseholdId + prefs[BACKEND_SYNC_DEVICE_ID] = next.backendSyncDeviceId + prefs[BACKEND_SYNCED_TITLES] = next.backendSyncedTitles + prefs[BACKEND_SYNCED_TITLES_HOUSEHOLD_ID] = next.backendSyncedTitlesHouseholdId + prefs[BACKEND_CREDENTIAL_EPOCH] = next.backendCredentialEpoch prefs[ACCOUNT_SKIPPED] = next.accountSkipped prefs[BACKEND_PHONE] = next.backendPhone } @@ -116,6 +127,12 @@ class DataStoreSettingsRepository( backendUrl = DEFAULT_BACKEND_URL, backendDeviceId = "", backendHouseholdId = "", + backendSyncSeq = 0, + backendSyncHouseholdId = "", + backendSyncDeviceId = "", + backendSyncedTitles = "", + backendSyncedTitlesHouseholdId = "", + backendCredentialEpoch = 0, backendPhone = "", ) } @@ -155,6 +172,12 @@ 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, + backendSyncHouseholdId = prefs[BACKEND_SYNC_HOUSEHOLD_ID] ?: "", + backendSyncDeviceId = prefs[BACKEND_SYNC_DEVICE_ID] ?: "", + backendSyncedTitles = prefs[BACKEND_SYNCED_TITLES] ?: "", + backendSyncedTitlesHouseholdId = prefs[BACKEND_SYNCED_TITLES_HOUSEHOLD_ID] ?: "", + backendCredentialEpoch = prefs[BACKEND_CREDENTIAL_EPOCH] ?: 0, accountSkipped = prefs[ACCOUNT_SKIPPED] ?: false, backendPhone = prefs[BACKEND_PHONE] ?: "", ) @@ -188,6 +211,13 @@ 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 BACKEND_SYNC_HOUSEHOLD_ID = stringPreferencesKey("backend_sync_household_id") + val BACKEND_SYNC_DEVICE_ID = stringPreferencesKey("backend_sync_device_id") + val BACKEND_SYNCED_TITLES = stringPreferencesKey("backend_synced_titles") + val BACKEND_SYNCED_TITLES_HOUSEHOLD_ID = + stringPreferencesKey("backend_synced_titles_household_id") + val BACKEND_CREDENTIAL_EPOCH = longPreferencesKey("backend_credential_epoch") 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/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/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..8161c08bb 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,83 @@ 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) + } + + @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) + } + + @Test + fun `a fresh settings file knows no sync owner`() { + val settings = DataStoreSettingsRepository.settingsFrom(emptyPreferences()) + + assertEquals("", settings.backendSyncHouseholdId) + assertEquals("", settings.backendSyncDeviceId) + assertEquals("", settings.backendSyncedTitlesHouseholdId) + } + + @Test + fun `the household and device that own the cursor are read back`() { + val prefs = mutablePreferencesOf( + DataStoreSettingsRepository.BACKEND_SYNC_SEQ to 42L, + DataStoreSettingsRepository.BACKEND_SYNC_HOUSEHOLD_ID to "h1", + DataStoreSettingsRepository.BACKEND_SYNC_DEVICE_ID to "d1", + DataStoreSettingsRepository.BACKEND_SYNCED_TITLES_HOUSEHOLD_ID to "h1", + ) + + val settings = DataStoreSettingsRepository.settingsFrom(prefs) + + assertEquals("h1", settings.backendSyncHouseholdId) + assertEquals("d1", settings.backendSyncDeviceId) + assertEquals("h1", settings.backendSyncedTitlesHouseholdId) + } + + @Test + fun `a fresh settings file knows no credential generation`() { + val settings = DataStoreSettingsRepository.settingsFrom(emptyPreferences()) + + assertEquals(0L, settings.backendCredentialEpoch) + } + + @Test + fun `a stored credential generation is read back`() { + val prefs = mutablePreferencesOf( + DataStoreSettingsRepository.BACKEND_CREDENTIAL_EPOCH to 3L, + ) + + val settings = DataStoreSettingsRepository.settingsFrom(prefs) + + assertEquals(3L, settings.backendCredentialEpoch) + } } 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..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 @@ -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,18 @@ 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() + + /** + * 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 9c1e2c167..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 @@ -87,6 +87,28 @@ 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 touchesCurrent = threadId.isBlank() || threadId == currentId + val refreshed = if (touchesCurrent) { + all.firstOrNull { it.id == currentId } + } else { + null + } + _state.update { state -> + 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, + ) + } + } + } } fun onInput(value: String) { @@ -198,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 { @@ -681,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..0dbecedc0 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,11 @@ 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, + /** Remote ops that could not be applied; the log moved past them. */ + val skippedRemote: 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 c8e2e3d1e..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 @@ -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,16 @@ 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() + + /** + * 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 cde5b2eb0..354239d36 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) { @@ -67,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() @@ -109,7 +121,19 @@ class ConversationsViewModel @Inject constructor( } else { "" } - "Synced: ${outcome.adopted} chats$deleted" + val skipped = if (outcome.skipped > 0) { + ", ${outcome.skipped} too long to sync" + } else { + "" + } + // A remote op the engine could not use is reported too: the log + // moves past it, so silence would look like a clean sync. + val dropped = if (outcome.skippedRemote > 0) { + ", ${outcome.skippedRemote} skipped" + } else { + "" + } + "Synced: ${outcome.adopted} chats$deleted$skipped$dropped" }.getOrElse { error -> "Sync failed: ${error.message}" } load() _state.update { it.copy(syncing = false, message = message) } @@ -136,4 +160,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" + } } 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..535b64106 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,36 @@ 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 household and device [backendSyncSeq] was applied in. A seq without + * its owner means nothing: another household's position sits above this + * one's earliest ops, so a mismatched cursor starts again at 0. + */ + val backendSyncHouseholdId: String = "", + val backendSyncDeviceId: String = "", + /** + * 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 household [backendSyncedTitles] describes. Titles from another + * household are not this household's history and cannot suppress a push. + */ + val backendSyncedTitlesHouseholdId: String = "", + /** + * Bumped whenever the stored credential tuple (identity, tokens, household + * key) is written. A pass captures it before the reads and checks it again + * after: a change means part of the tuple was replaced under it. + */ + val backendCredentialEpoch: 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/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" + } } 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..530fa72db 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,42 @@ interface SettingsRepository { suspend fun setBackendContentKey(value: String) + /** + * The last sync seq the op log was applied up to, with the household and + * device that wrote it. The owner belongs beside the seq: a cursor from + * another pairing would sit above this one's earliest ops. + */ + suspend fun setBackendSyncState(seq: Long, householdId: String, deviceId: String) = update { + it.copy( + backendSyncSeq = seq, + backendSyncHouseholdId = householdId, + backendSyncDeviceId = deviceId, + ) + } + + /** + * The titles the server is known to hold, as JSON `{"threadId":"title"}`, + * with the household that record describes. 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 setBackendSyncedTitles(value: String, householdId: String) = update { + it.copy( + backendSyncedTitles = value, + backendSyncedTitlesHouseholdId = householdId, + ) + } + + /** + * Marks the stored credential tuple (identity, tokens, key) as new. A pass + * captures the epoch before its reads and checks it after: a bump means a + * claim, a sign-up or a sign-out wrote part of the tuple in between, so the + * pass would act on a torn identity/token/key and must not send. + */ + suspend fun bumpBackendCredentialEpoch() = update { + it.copy(backendCredentialEpoch = it.backendCredentialEpoch + 1) + } + /** * The Ed25519 seed that signs this phone's approval answers (ADR-0032), * base64. Blank until the first answer creates it. A store that cannot diff --git a/apps/windows/Hopa.Windows.Tests/ChatControllerTests.cs b/apps/windows/Hopa.Windows.Tests/ChatControllerTests.cs index c7c42bbf2..54468f770 100644 --- a/apps/windows/Hopa.Windows.Tests/ChatControllerTests.cs +++ b/apps/windows/Hopa.Windows.Tests/ChatControllerTests.cs @@ -72,6 +72,85 @@ 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 ReloadYieldsToASelectionMadeWhileItWasInFlight() + { + var engine = new FakeEngine + { + Open = id => new JsonObject + { + ["title"] = id.ToUpperInvariant(), + ["messages"] = new JsonArray(), + }, + }; + var chat = new ChatViewModel(); + var controller = new ChatController(engine, chat, new ConversationsViewModel()); + Assert.Equal("A", await controller.SelectAsync("a")); + + var gate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + engine.OpenGates["a"] = gate; + var reload = controller.ReloadAsync("a"); + + // The person selects b while the reload of a still waits for its reply. + Assert.Equal("B", await controller.SelectAsync("b")); + gate.SetResult(new JsonObject { ["title"] = "STALE", ["messages"] = new JsonArray() }); + + Assert.Null(await reload); + Assert.Equal("b", controller.CurrentId); + } + + [Fact] + public async Task ReloadYieldsToATurnThatStartedWhileItWasInFlight() + { + var engine = new FakeEngine + { + Open = id => new JsonObject { ["title"] = "A", ["messages"] = new JsonArray() }, + }; + var chat = new ChatViewModel(); + var controller = new ChatController(engine, chat, new ConversationsViewModel()); + Assert.Equal("A", await controller.SelectAsync("a")); + + var turnGate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + engine.TurnGate = turnGate; + var turn = controller.SendAsync("hello", null); + Assert.True(controller.Running); + + var openGate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + engine.OpenGates["a"] = openGate; + var reload = controller.ReloadAsync("a"); + openGate.SetResult(new JsonObject { ["title"] = "STALE", ["messages"] = new JsonArray() }); + + Assert.Null(await reload); + Assert.Contains(chat.Messages, message => message.Text == "hello"); + + turnGate.SetResult(new TurnResult("answer", "a", "A", null, true)); + Assert.Equal("answer", (await turn).Answer); + } + [Fact] public async Task CreateAddsTheRowTheEngineReturned() { @@ -147,6 +226,12 @@ private sealed class FakeEngine : IChatEngine public Func Open { get; set; } = _ => new JsonObject(); + /// An open for this id waits until the test completes its gate. + public Dictionary> OpenGates { get; } = new(); + + /// A turn waits until the test completes its gate. + public TaskCompletionSource? TurnGate { get; set; } + public Task StartTurnAsync( string goal, string? conversationId, @@ -156,10 +241,10 @@ public Task StartTurnAsync( bool paused = false) => Failure != null ? Task.FromException(Failure) - : Task.FromResult(Turn); + : TurnGate?.Task ?? Task.FromResult(Turn); public Task OpenConversationAsync(string id) => - Task.FromResult(Open(id)); + OpenGates.TryGetValue(id, out var gate) ? gate.Task : Task.FromResult(Open(id)); public Task CreateConversationAsync() => Task.FromResult(Created); diff --git a/apps/windows/Hopa.Windows.Tests/EngineHostClientBackendTests.cs b/apps/windows/Hopa.Windows.Tests/EngineHostClientBackendTests.cs index 2c5ec33ad..119617d0f 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() { @@ -133,4 +146,70 @@ 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\":\"srv-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("srv-1", reply?["taskId"]?.GetValue()); + } + + [Fact] + public async Task SendTaskAsyncCarriesTheRefusalCodeToTheWindow() + { + var reader = new QueueReader(); + var writer = new LineWriter(); + var client = new EngineHostClient(new EngineTransport(writer, reader)); + writer.OnLine = line => + { + var id = JsonNode.Parse(line)!["id"]!.GetValue(); + reader.Push($"{{\"type\":\"task.send\",\"id\":\"{id}\",\"ok\":false,\"code\":\"E_TENANT\"}}"); + }; + + var refused = await client.SendTaskAsync("phone-1", "open the settings app"); + + Assert.False(refused["ok"]!.GetValue()); + Assert.Equal("E_TENANT", Hopa.Windows.Ui.Dialogs.SendTaskWindow.RefusalCode(refused)); + Assert.Null(Hopa.Windows.Ui.Dialogs.SendTaskWindow.RefusalCode( + new JsonObject { ["ok"] = true, ["taskId"] = "srv-1" })); + } + + [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/Host/ChatController.cs b/apps/windows/Hopa.Windows/Host/ChatController.cs index 7176b322e..d83894264 100644 --- a/apps/windows/Hopa.Windows/Host/ChatController.cs +++ b/apps/windows/Hopa.Windows/Host/ChatController.cs @@ -1,5 +1,6 @@ using System.Diagnostics; using System.Text.Json.Nodes; +using System.Threading; using Hopa.Windows.Ui.Chat; using Hopa.Windows.Integrations.Engine; using Hopa.Windows.Ui.Panes; @@ -17,6 +18,9 @@ public sealed class ChatController private readonly ConversationsViewModel conversations; private bool running; + /// Bumped by every open, so a slow reply can tell it is stale. + private int openGeneration; + public ChatController(IChatEngine engine, ChatViewModel chat, ConversationsViewModel conversations) { this.engine = engine; @@ -110,12 +114,41 @@ public async Task SendAsync( return null; } + return await OpenAsync(id, reload: false); + } + + /// + /// 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. The + /// reload yields to anything newer: a selection the person made, or a turn + /// that started, while the read was in flight owns the view now. + /// + public async Task ReloadAsync(string id) => await OpenAsync(id, reload: true); + + private async Task OpenAsync(string id, bool reload) + { + // Every open bumps the generation. A reply that lands after a newer open + // started is stale and must not overwrite that open's view or CurrentId. + var generation = Interlocked.Increment(ref openGeneration); if (CurrentId != null) { chat.Drafts[CurrentId] = chat.ComposerText; } var open = await engine.OpenConversationAsync(id); + if (generation != Volatile.Read(ref openGeneration)) + { + return null; + } + + // A reload is a background refresh, so it also yields to a turn that + // started during the round trip: rebuilding the view mid-turn would + // clear the messages the turn is writing. + if (reload && (running || CurrentId != id)) + { + return null; + } + CurrentId = id; chat.ShowConversation( open?["messages"] as JsonArray, 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..64fb10c34 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(); @@ -356,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, @@ -462,6 +500,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/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 @@ + + + + + + + + + + + + + + + + + +