Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

fix(android): stop dictation's microphone with the chat, and keep each computer independent

leepokai866d1ac59a1a
diff --git a/apps/android/README.md b/apps/android/README.md
index 6c7a9d17..2658059a 100644
--- a/apps/android/README.md
+++ b/apps/android/README.md
@@ -154,8 +154,8 @@ and explicit HTTP links. Vosk/JNA and the checksum-verified English model have
notices in [voice-manifest.json](app/src/main/assets/licenses/voice-manifest.json).
That speech prototype does not establish full voice parity.
-AndroidX, Compose, CameraX, Glance, WorkManager, Firebase and desugaring artifacts
-come from Google Maven. Other dependencies use the configured repositories.
+AndroidX, Compose, CameraX, Glance, WorkManager, Firebase, Play app update / in-app review
+and desugaring artifacts come from Google Maven. Other dependencies use the configured repositories.
AndroidX native libraries, Vosk and JNA are upstream artifacts; no custom native
crypto or camera library is introduced. WebRTC comes from the webrtc-sdk build of libwebrtc.
@@ -175,6 +175,7 @@ crypto or camera library is introduced. WebRTC comes from the webrtc-sdk build o
| Java API desugaring | 2.1.5 | [Android desugaring](https://developer.android.com/studio/write/java11-default-support-table), GPL-2.0 with Classpath Exception; CommonMark runtime support |
| Clerk Android | 1.1.11 | [Clerk SDK](https://github.com/clerk/clerk-android), MIT; native account sessions and browser/provider authentication |
| Firebase BOM / Google Services plugin | 34.19.0 / 4.5.0 | [Firebase Android](https://firebase.google.com/support/release-notes/android), Apache-2.0; FID registration and data-only FCM delivery |
+| Play app update / in-app review | 2.1.0 / 2.0.2 | [Play Core](https://developer.android.com/guide/playcore), [Play Core SDK Terms](https://developer.android.com/guide/playcore#license); the update notice and reminder, and the rating invitation |
| WorkManager | 2.12.0 | [AndroidX Work](https://developer.android.com/jetpack/androidx/releases/work), Apache-2.0; bounded background registration retries |
| Glance | 1.2.0 | [AndroidX Glance](https://developer.android.com/jetpack/androidx/releases/glance), Apache-2.0; responsive native app widgets |
| CameraX | 1.6.2 | [AndroidX Camera](https://developer.android.com/jetpack/androidx/releases/camera), Apache-2.0; lifecycle-bound preview/analysis, minimum API 23, optional camera permission |
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/AccountScreenTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/AccountScreenTest.kt
index 58fa19f4..b768e3e1 100644
--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/AccountScreenTest.kt
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/AccountScreenTest.kt
@@ -31,7 +31,7 @@ class AccountScreenTest {
private val second = SavedAccount("second", "second-session", "[email protected]", null)
private val account = AccountState(ready = true, configured = true, userId = first.userId,
accounts = listOf(first, second), multiple = true)
- private val computer = Computer("paired", "Fixture computer", "fixture-key")
+ private val computer = Computer("paired-computer-000001", "Fixture computer", "fixture-key")
private fun fixture(accountState: AccountState = account) = AccountContext(loading = false,
setupComplete = true, account = accountState, contextId = "profile-fixture")
private fun paired(link: LinkState, bots: List<Bot> = emptyList()) =
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/ComputerRosterTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/ComputerRosterTest.kt
new file mode 100644
index 00000000..8730c8e9
--- /dev/null
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/ComputerRosterTest.kt
@@ -0,0 +1,65 @@
+package com.codync.android
+
+import androidx.activity.ComponentActivity
+import androidx.compose.ui.test.*
+import androidx.compose.ui.test.junit4.createAndroidComposeRule
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.*
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.runBlocking
+import org.junit.Assert.*
+import org.junit.Rule
+import org.junit.Test
+
+/** Two computers in the roster: a heading each that folds, the header's filter, and removing one keeps the other. Nothing links. */
+class ComputerRosterTest {
+ @get:Rule val compose = createAndroidComposeRule<ComponentActivity>()
+ private val mac = Computer("roster-test-mac-000001", "Mac fixture", "mac")
+ private val linux = Computer("roster-test-linux-0001", "Linux fixture", "linux")
+ // A ready account: one still loading shows a spinner in the header, and the roster never settles.
+ private val app = AccountContext(loading = false, setupComplete = true, account = AccountState(ready = true), computers = listOf(mac, linux))
+ private fun state(computer: Computer, bot: String) = AppState(computer, loading = false, rosterLoaded = true,
+ connection = LinkState.Ready(HostRoute.Direct), actualConnection = LinkState.Ready(HostRoute.Direct), bots = listOf(Bot(bot, bot)))
+ private fun heading(name: String) = hasContentDescription("$name,", substring = true) and isHeading()
+
+ @Test fun eachComputerHasAHeadingThatFoldsAndTheFilterShowsSomeOrOne() = compose.withPreviewAccounts(mac, linux) { accounts ->
+ val context = compose.activity
+ val hidden = RosterComputers.hidden(context)
+ val folded = RosterComputers.folded(context)
+ RosterComputers.setHidden(context, ""); RosterComputers.setFolded(context, emptySet())
+ try {
+ compose.setContent {
+ Hosted { BotListView(app, listOf(state(mac, "Mac bot"), state(linux, "Linux bot")), accounts, {}, {}, {}, {}, { _, _ -> }, {}, 0.dp) }
+ }
+ compose.onNode(heading("Mac fixture")).assertIsDisplayed()
+ compose.onNode(heading("Linux fixture")).assertIsDisplayed()
+ compose.onNodeWithText("2 connected").assertIsDisplayed()
+ // A tap on a heading folds its bots away, and unfolds them again.
+ compose.onNode(heading("Linux fixture")).performClick()
+ compose.onNodeWithText("Linux bot").assertDoesNotExist()
+ compose.onNodeWithText("Mac bot").assertIsDisplayed()
+ compose.onNode(heading("Linux fixture")).performClick()
+ compose.onNodeWithText("Linux bot").assertIsDisplayed()
+ // Leaving one out shows the other as the only computer: no headings.
+ compose.computerAction("Linux fixture")
+ compose.onNodeWithText("Linux bot").assertDoesNotExist()
+ compose.onNode(heading("Mac fixture")).assertDoesNotExist()
+ compose.onNodeWithText("1 connected").assertIsDisplayed()
+ compose.computerAction("All computers")
+ compose.onNodeWithText("Linux bot").assertIsDisplayed()
+ // Show only, from its submenu.
+ compose.computerAction("Show only")
+ compose.onNodeWithText("Linux fixture").performClick()
+ compose.onNodeWithText("Mac bot").assertDoesNotExist()
+ compose.onNodeWithText("Linux bot").assertIsDisplayed()
+ } finally {
+ RosterComputers.setHidden(context, hidden); RosterComputers.setFolded(context, folded)
+ }
+ }
+
+ @Test fun removingOneComputerKeepsTheOther() = compose.withPreviewAccounts(mac, linux) { accounts ->
+ runBlocking(Dispatchers.Main) { accounts.close(mac.id) }
+ assertNull(accounts.store(mac.id))
+ assertNotNull(accounts.store(linux.id))
+ }
+}
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/ConnectionUiTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/ConnectionUiTest.kt
index 01982653..c1eae040 100644
--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/ConnectionUiTest.kt
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/ConnectionUiTest.kt
@@ -12,8 +12,8 @@ import org.junit.Test
class ConnectionUiTest {
@get:Rule val compose = createAndroidComposeRule<ComponentActivity>()
- private val computer = Computer("fixture", "Fixture computer", "fixture")
- private val app = AccountContext(loading = false, setupComplete = true, computers = listOf(computer))
+ private val computer = Computer("fixture-computer-00001", "Fixture computer", "fixture")
+ private val app = AccountContext(loading = false, setupComplete = true, account = AccountState(ready = true), computers = listOf(computer))
private fun fixture(link: LinkState) = AppState(computer, loading = false, rosterLoaded = true, connection = link, actualConnection = link)
@Test fun theComputerRowNamesTheActualConnectionState() = compose.withPreviewAccounts(computer) { accounts ->
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LayoutTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LayoutTest.kt
index 13c94bfc..e367f26d 100644
--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/LayoutTest.kt
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LayoutTest.kt
@@ -18,8 +18,8 @@ import org.junit.Test
/** Read-only roster fixture: nothing here pairs, saves or sends. */
class LayoutTest {
@get:Rule val compose = createAndroidComposeRule<ComponentActivity>()
- private val computer = Computer("fixture", "Acceptance computer", "fixture")
- private val app = AccountContext(loading = false, setupComplete = true, computers = listOf(computer))
+ private val computer = Computer("fixture-computer-00001", "Acceptance computer", "fixture")
+ private val app = AccountContext(loading = false, setupComplete = true, account = AccountState(ready = true), computers = listOf(computer))
private val state = AppState(computer, loading = false, rosterLoaded = true,
connection = LinkState.Ready(HostRoute.Direct), actualConnection = LinkState.Ready(HostRoute.Direct), bots = (1..5).map {
Bot("bot-$it", "Bot $it", lastMessage = "A recent reply", unread = if (it == 1) 12 else 0)
@@ -70,7 +70,7 @@ class LayoutTest {
snapshot("large-text")
compose.onNode(computers).performClick()
compose.onNodeWithText("Manage computers").assertIsDisplayed()
- compose.onNodeWithText("Acceptance computer · Connected").assertIsDisplayed()
+ compose.onNodeWithText("Connected").assertIsDisplayed()
}
private fun snapshot(name: String) {
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/NavigationControls.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/NavigationControls.kt
index cdf844f6..ae849824 100644
--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/NavigationControls.kt
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/NavigationControls.kt
@@ -21,7 +21,7 @@ internal fun SemanticsNodeInteractionsProvider.onControl(label: String) = onNode
@Composable internal fun Hosted(content: @Composable () -> Unit) = CodyncTheme { OverlayRoot(content) }
/** The computer screens rendered on their own show. */
-internal val previewComputer = Computer("fixture", "Fixture computer", "fixture")
+internal val previewComputer = Computer("fixture-computer-00001", "Fixture computer", "fixture")
/** A store no account opened, for a screen rendered on its own: it stays loading, so its actions never run. */
internal fun previewStore(computer: Computer = previewComputer): AppStore {
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/ScreenPresentationTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/ScreenPresentationTest.kt
index 67811246..387d4899 100644
--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/ScreenPresentationTest.kt
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/ScreenPresentationTest.kt
@@ -24,7 +24,7 @@ import java.io.File
class ScreenPresentationTest {
@get:Rule val compose = createAndroidComposeRule<ComponentActivity>()
private val bot = Bot("presentation-fixture", "Scout")
- private val computer = Computer("fixture-computer", "Fixture computer", "fixture-key")
+ private val computer = Computer("fixture-computer-00001", "Fixture computer", "fixture-key")
private val state = AppState(computer, contextId = "presentation-fixture", loading = false, rosterLoaded = true, bots = listOf(bot))
private val computers = mapOf(computer.id to state)
private fun fixture() = AccountContext(contextId = "presentation-fixture", loading = false, setupComplete = true, computers = listOf(computer),
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/WidgetStoreTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/WidgetStoreTest.kt
index 19e9603b..0f5c89e2 100644
--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/WidgetStoreTest.kt
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/WidgetStoreTest.kt
@@ -48,6 +48,16 @@ class WidgetStoreTest {
assertEquals("Newer Account B", WidgetStore.feed(context).bots.single().name)
val persisted = File(second.directory, "widget-feed.json").readText()
assertFalse(persisted.contains("Private chat")); assertFalse(persisted.contains("lastMessage"))
+ // A second computer: unreachable, it keeps the bots it showed; forgotten here, they go with it.
+ val key = ByteArray(32) { 3 }
+ val laptop = Computer(RelayCrypto.computerId(key), "Laptop", java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(key))
+ second.saveComputers(listOf(computer, laptop))
+ WidgetStore.publish(context, b, listOf(WidgetComputer(computer, listOf(Bot("shared", "Newer Account B")), true),
+ WidgetComputer(laptop, listOf(Bot("laptop", "Laptop bot")), true)), computer, UsageReport(), false)
+ WidgetStore.publish(context, b, listOf(WidgetComputer(computer, emptyList(), true), WidgetComputer(laptop, null, false)), computer, UsageReport(), false)
+ assertEquals(listOf("Laptop bot"), WidgetStore.feed(context).bots.map { it.name })
+ second.saveComputers(listOf(computer))
+ assertTrue(WidgetStore.feed(context).bots.isEmpty())
second.saveComputers(emptyList())
assertNull(WidgetStore.feed(context).computerId)
assertTrue(WidgetStore.feed(context).bots.isEmpty())
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AccountStore.kt b/apps/android/app/src/main/kotlin/com/codync/android/AccountStore.kt
index 70f1b525..01e0493b 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AccountStore.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AccountStore.kt
@@ -9,6 +9,7 @@ import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
+import kotlinx.serialization.json.JsonObject
/**
* The ViewModel the UI talks to (iOS `AccountStore`): the active account, its computers with one
@@ -78,7 +79,10 @@ class AccountStore(application: Application) : AndroidViewModel(application) {
mutableState.update { AccountContext(contextId = local.referenceId, generation = it.generation + 1, account = it.account,
computers = computers, lastComputerId = last, tasks = PushPreferences.tasks(getApplication()),
setupComplete = complete || computers.isNotEmpty() || userId != null) }
- for (computer in computers) open(computer)
+ // A computer that can't open (damaged drafts) is reported; the others, the cloud and the widgets go on.
+ for (computer in computers) try { open(computer) }
+ catch (error: CancellationException) { throw error }
+ catch (error: Exception) { mutableState.update { it.copy(error = error.message ?: "Couldn't open ${computer.name}.") } }
// Outgoing files no queued message or draft of any computer needs anymore.
withContext(Dispatchers.IO) { AttachmentFiles(getApplication(), local.directory).retainPending(stores.value.flatMap { it.pendingFiles() }) }
if (userId != null) configureCloud(userId)
@@ -119,11 +123,10 @@ class AccountStore(application: Application) : AndroidViewModel(application) {
/** Opens [computer]'s store and, in the foreground, its link (iOS `AccountStore.open`). */
internal suspend fun open(computer: Computer) {
val context = state.value
- val store = AppStore(getApplication(), local, computer, context.contextId, context.generation, contextJob, ::saveComputer) { opened ->
+ val store = AppStore(getApplication(), local, computer, context.contextId, context.generation, contextJob, ::saveComputer, opened = { opened ->
for (other in stores.value) if (other !== opened) other.openBot(null)
noteActive(opened.id)
- }
- store.usageRead = ::publishUsage
+ }, usageRead = ::publishUsage)
store.open()
mutableStores.update { list -> list.filter { it.id != computer.id } + store }
sortStores()
@@ -139,7 +142,8 @@ class AccountStore(application: Application) : AndroidViewModel(application) {
val computers = state.value.computers.filter { it.id != id }
withContext(Dispatchers.IO) {
local.saveComputers(computers)
- local.directory.listFiles()?.filter { it.name.startsWith("mirror-$id") || it.name == "drafts-$id.json" }?.forEach { it.delete() }
+ MirrorDatabase.delete(local.directory, id)
+ DraftBook.delete(local.directory, id)
}
mutableState.update { it.copy(computers = computers) }
}
@@ -232,7 +236,8 @@ class AccountStore(application: Application) : AndroidViewModel(application) {
for (store in stores.value) store.clearError()
}
- private data class WidgetSource(val computers: List<Computer>, val states: List<AppState>, val current: String?)
+ /** Only what the widgets show, so a streaming answer doesn't publish (or hold off) anything. */
+ private data class WidgetSource(val paired: Boolean, val computers: List<WidgetComputer>, val usageComputer: Computer?, val usage: JsonObject?)
/** The Bots widgets show every computer's bots; Usage the last active computer's (iOS `BotsEntry`, `UsageTimeline`). */
@OptIn(FlowPreview::class)
@@ -240,16 +245,19 @@ class AccountStore(application: Application) : AndroidViewModel(application) {
contextScope.launch {
combine(state, computerStates) { context, states -> context to states }
.filter { (context, _) -> !context.loading && context.contextId == owner.scope }
- .map { (context, states) -> WidgetSource(context.computers, context.computers.mapNotNull { states[it.id] }, context.currentComputerId) }
+ .map { (context, states) ->
+ val usage = states[context.currentComputerId]
+ WidgetSource(context.computers.isNotEmpty(), context.computers.mapNotNull { states[it.id] }
+ .map { WidgetComputer(it.computer, it.bots, it.widgetBotsCurrent) }, usage?.computer, usage?.usage)
+ }
.distinctUntilChanged().debounce(350).collect { source ->
try {
- val usage = source.states.firstOrNull { it.computer.id == source.current }
val accepted = withContext(Dispatchers.IO) {
- WidgetStore.publish(getApplication(), owner, source.states.map { WidgetComputer(it.computer, it.bots, it.widgetBotsCurrent) },
- usage?.computer, UsageReport.decode(usage?.usage ?: kotlinx.serialization.json.JsonObject(emptyMap())), false)
+ WidgetStore.publish(getApplication(), owner, source.computers, source.usageComputer,
+ UsageReport.decode(source.usage ?: JsonObject(emptyMap())), false)
}
if (!accepted) return@collect
- WidgetRefreshWorker.schedule(getApplication(), source.computers.isNotEmpty())
+ WidgetRefreshWorker.schedule(getApplication(), source.paired)
CodyncWidgets.update(getApplication())
} catch (cancelled: CancellationException) { throw cancelled }
catch (_: Exception) { mutableState.update { it.copy(error = "Couldn't update widgets. Open State and try again.") } }
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt
index bcf3ead5..282ad890 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt
@@ -37,7 +37,7 @@ data class AccountContext(
val error: String? = null,
) {
/** The computer Usage acts on: the last active one, else the first. */
- val currentComputerId: String? get() = lastComputerId?.takeIf { id -> computers.any { it.id == id } } ?: computers.firstOrNull()?.id
+ val currentComputerId: String? get() = computers.currentId(lastComputerId)
}
/** One computer as the UI renders it (iOS `BotStore`); its `AppStore` owns the only writer. */
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt
index 5bef9416..df7f4fcf 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStore.kt
@@ -16,7 +16,7 @@ import kotlinx.serialization.json.*
* themselves are `AppStore` extensions in the `AppStore*.kt` files beside it.
*/
class AppStore internal constructor(
- private val application: Application,
+ internal val application: Application,
internal val local: LocalStore,
computer: Computer,
contextId: String,
@@ -26,9 +26,10 @@ class AppStore internal constructor(
private val saveComputer: suspend (Computer) -> Unit,
/** A chat opened here: the other computers close theirs (one chat is open at a time). */
internal val opened: (AppStore) -> Unit,
+ /** A usage read finished (the account refreshes the Usage widget). */
+ internal val usageRead: suspend (AppStore) -> Unit = {},
) {
val id: String = computer.id
- @Suppress("UNCHECKED_CAST") internal fun <T : Application> getApplication(): T = application as T
private val job = SupervisorJob(parent)
internal val contextScope = CoroutineScope(job + Dispatchers.Main.immediate)
/** One change to this computer's saved copy at a time (`changeComputer`). */
@@ -63,14 +64,12 @@ class AppStore internal constructor(
internal var pluginsRefreshAgain = false
/** The host version an undecodable event already made the mirror fetch everything again for. */
internal var rewoundFor: String? = null
- /** A usage read finished (the account refreshes the Usage widget). */
- internal var usageRead: suspend (AppStore) -> Unit = {}
/** Opens the mirror and the drafts this phone keeps for the computer; nothing connects yet. */
internal suspend fun open() {
val book = DraftBook(local.directory, id)
withContext(Dispatchers.IO) {
- database = MirrorDatabase(getApplication(), local.directory, id)
+ database = MirrorDatabase(application, local.directory, id)
database?.recoverInterrupted()
val snapshot = requireNotNull(database).snapshot()
val restored = book.recover(snapshot)
@@ -134,11 +133,11 @@ class AppStore internal constructor(
pending = snapshot.pending, usage = snapshot.usage, screen = screen, mirrorRevision = snapshot.rev, icons = snapshot.icons,
selectedBot = current.selectedBot?.takeIf { id -> snapshot.bots.any { it.id == id } }) }
if (voiceBinding != null && snapshot.bots.none { it.id == voiceBinding?.botId && !it.deleted }) endVoice("Voice chat ended because its bot was removed.")
- if (PushPreferences.tasks(getApplication())) {
+ if (PushPreferences.tasks(application)) {
val watched = withContext(Dispatchers.IO) { feed.all().filter { !it.finished }.map { it.botId }.toSet() }
for (bot in snapshot.bots.filter { it.id in watched }) {
val watch = withContext(Dispatchers.IO) { feed.local(bot) }
- if (watch != null) NotificationDisplay.task(getApplication(), local.referenceId, id, watch)
+ if (watch != null) NotificationDisplay.task(application, local.referenceId, id, watch)
}
}
}
@@ -175,7 +174,7 @@ class AppStore internal constructor(
/** The app is closing: drop the link and save the drafts on the way out. */
internal fun close(scope: CoroutineScope) {
- state.value.voice?.id?.let { VoiceService.stop(getApplication(), it) }
+ state.value.voice?.id?.let { VoiceService.stop(application, it) }
voiceBinding?.engine?.end()
channel?.close()
val old = database
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.kt
index 8c6bdcb2..9c98794b 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.kt
@@ -182,3 +182,15 @@ suspend fun AppStore.routineWebhook(botId: String, id: String, rotate: Boolean =
val response = hostQuery("routineWebhook", buildJsonObject { put("botId", botId); put("id", id); put("rotate", rotate) })
return WireJson.decodeFromJsonElement(response)
}
+
+/** Saves a dragged roster order (the host syncs it to every device). */
+internal fun AppStore.reorder(ids: List<String>) =
+ command("reorderBots", buildJsonObject { putJsonArray("ids") { ids.forEach { add(JsonPrimitive(it)) } } }, "reorder")
+
+/** Whether the bot's harness keeps its own memory on beside Codync's (iOS `setHarnessMemory`). */
+internal fun AppStore.setHarnessMemory(bot: Bot, on: Boolean) =
+ command("updateBot", buildJsonObject { put("id", bot.id); put("harnessMemory", on) }, "memory:" + bot.id)
+
+/** Whether the bot uses what all the user's bots share (iOS `setSharedMemory`). */
+internal fun AppStore.setSharedMemory(bot: Bot, shared: Boolean) =
+ command("updateBot", buildJsonObject { put("id", bot.id); put("sharedMemory", shared) }, "memory:" + bot.id)
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt
index 45e6a638..ce0bbaf3 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt
@@ -1,6 +1,5 @@
package com.codync.android
-import android.app.Application
import java.io.IOException
import java.util.UUID
import com.codync.android.core.*
@@ -115,10 +114,10 @@ internal suspend fun AppStore.deliver(send: PendingSend) {
withContext(Dispatchers.IO) { requireNotNull(database).receive(listOf(entry)) }
refresh()
val bot = state.value.bots.firstOrNull { it.id == send.botId }
- if (bot != null && PushPreferences.tasks(getApplication()) && getApplication<Application>().getSystemService(android.app.NotificationManager::class.java).areNotificationsEnabled()) {
+ if (bot != null && PushPreferences.tasks(application) && application.getSystemService(android.app.NotificationManager::class.java).areNotificationsEnabled()) {
val watch = withContext(Dispatchers.IO) { feed.start(bot) }
- NotificationDisplay.task(getApplication(), local.referenceId, id, watch)
- syncPush(); PushDelivery.schedule(getApplication())
+ NotificationDisplay.task(application, local.referenceId, id, watch)
+ syncPush(); PushDelivery.schedule(application)
}
} catch (error: CancellationException) {
withContext(NonCancellable) { savePending(send.copy(status = SendStatus.Failed, error = "Sending was interrupted. Retry uses the same message ID.")) }
@@ -140,3 +139,13 @@ fun AppStore.respond(entry: Entry, option: String?) = action("permission:" + ent
active.call("respondPermission", body("entryId" to entry.id, "optionId" to option))
delay(2_000)
}
+
+/** Carries on with the bot's current conversation instead of the handoff. */
+internal fun AppStore.keepConversation(entry: Entry) = command("keepConversation", body("entryId" to entry.id), "handoff:" + entry.id)
+
+/** Saves the user's version of a handoff that hasn't been sent; whether it did (its error shows). */
+internal suspend fun AppStore.editHandoff(entry: Entry, text: String): Boolean = try {
+ hostCall("editHandoff", body("entryId" to entry.id, "text" to text), 30_000)
+ true
+} catch (cancelled: CancellationException) { throw cancelled }
+catch (error: Exception) { showError(error); false }
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt
index 17ed2e78..6ac0232d 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt
@@ -1,6 +1,5 @@
package com.codync.android
-import android.os.Build
import java.io.IOException
import com.codync.android.core.*
import kotlinx.coroutines.*
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnectorSignIn.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnectorSignIn.kt
index fd99f833..41783411 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnectorSignIn.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnectorSignIn.kt
@@ -1,6 +1,5 @@
package com.codync.android
-import android.app.Application
import android.net.Uri
import java.io.IOException
import androidx.lifecycle.viewModelScope
@@ -26,7 +25,7 @@ fun AppStore.connectorSignIn(id: String, requestId: String? = null) = action("oa
withContext(Dispatchers.IO) { ConnectorOAuthBook(local.directory).clear() }
}
val intent = android.content.Intent(android.content.Intent.ACTION_VIEW, Uri.parse(plan.url)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
- try { getApplication<Application>().startActivity(intent) }
+ try { application.startActivity(intent) }
catch (error: Exception) { withContext(Dispatchers.IO) { ConnectorOAuthBook(local.directory).clear() }; throw IOException("Couldn't open the sign-in browser.", error) }
if (plan.callback == "host") {
val complete = withTimeoutOrNull(600_000) {
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreDrafts.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreDrafts.kt
index b8951750..6dcf66f0 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreDrafts.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreDrafts.kt
@@ -75,7 +75,7 @@ fun AppStore.sendDraft(key: String, botId: String, text: String, replyTo: ReplyQ
mutableState.update { it.copy(drafts = it.drafts - key) }
persistDrafts()
onQueued()
- ReviewPrompt.sent(getApplication(), send.nonce)
+ ReviewPrompt.sent(application, send.nonce)
action("send:" + send.nonce) { deliver(send) }
}
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreIcons.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreIcons.kt
index a5020267..898dd608 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreIcons.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreIcons.kt
@@ -1,6 +1,5 @@
package com.codync.android
-import android.app.Application
import android.net.Uri
import android.util.Base64
import com.codync.android.core.*
@@ -12,7 +11,7 @@ internal fun AppStore.setIcon(target: String, file: Uri? = null, url: String? =
action("icon:$target") {
require((file == null && url == null) || local.contextId != "local") { "Sign in to use custom images." }
val data = file?.let { uri -> withContext(Dispatchers.IO) {
- val bytes = getApplication<Application>().contentResolver.openInputStream(uri)?.use { input ->
+ val bytes = application.contentResolver.openInputStream(uri)?.use { input ->
val output = java.io.ByteArrayOutputStream()
val buffer = ByteArray(8192)
while (output.size() <= 5 * 1024 * 1024) {
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreNotifications.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreNotifications.kt
index a15c4eff..4748e146 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreNotifications.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreNotifications.kt
@@ -9,15 +9,15 @@ import kotlinx.serialization.json.*
fun AppStore.syncPush() = action("push") {
val active = channel?.takeIf { it.state.value is LinkState.Ready } ?: return@action
- try { PushDelivery.sync(getApplication(), local, state.value.computer, active) }
+ try { PushDelivery.sync(application, local, state.value.computer, active) }
catch (error: CancellationException) { throw error }
- catch (_: Exception) { PushDelivery.schedule(getApplication()) }
+ catch (_: Exception) { PushDelivery.schedule(application) }
}
/** Saved with the computer on this phone (iOS `AccountStore.setNotifications`). */
fun AppStore.notifications(enabled: Boolean) = action("notificationSettings") {
changeComputer { it.copy(notifications = enabled) }
Analytics.capture(AnalyticsEvent.SettingChanged(PhoneSetting.Push, enabled))
- if (!enabled) NotificationDisplay.cancel(getApplication(), 1, "${local.referenceId}/$id/")
- syncPush(); PushDelivery.schedule(getApplication())
+ if (!enabled) NotificationDisplay.cancel(application, 1, "${local.referenceId}/$id/")
+ syncPush(); PushDelivery.schedule(application)
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreVoice.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreVoice.kt
index 84316f1a..c8187131 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreVoice.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreVoice.kt
@@ -39,7 +39,7 @@ internal class VoiceBinding(val id: String, val botId: String, val generation: I
private val voiceHttp by lazy { OkHttpClient() }
-internal fun AppStore.voiceChoices(): VoiceChoices = VoicePreferences.choices(getApplication())
+internal fun AppStore.voiceChoices(): VoiceChoices = VoicePreferences.choices(application)
fun AppStore.startVoice(botId: String, expectedGeneration: Int = state.value.generation) {
if (state.value.generation != expectedGeneration || state.value.loading || state.value.voice != null) return
@@ -48,9 +48,9 @@ fun AppStore.startVoice(botId: String, expectedGeneration: Int = state.value.gen
}
val id = UUID.randomUUID().toString()
voiceGeneration = expectedGeneration
- val starting = VoiceState(settings = VoicePreferences.load(getApplication()), provider = voiceChoices().provider)
+ val starting = VoiceState(settings = VoicePreferences.load(application), provider = voiceChoices().provider)
mutableState.update { it.copy(voice = VoiceCallViewState(id, botId, starting)) }
- try { VoiceService.start(getApplication(), this, id, botId); PushDelivery.foreground = true }
+ try { VoiceService.start(application, this, id, botId); PushDelivery.foreground = true }
catch (_: Exception) { finishVoice(id, "Couldn't start voice chat. Allow microphone access and wait for any previous call to finish.") }
}
@@ -70,7 +70,7 @@ private fun AppStore.begin(call: VoiceBinding, provider: VoiceProvider?) {
val choices = voiceChoices()
// Picks up the computer's newest models for the next call; this one starts right away.
if (provider != null) contextScope.launch { try { choices.remember(voiceStatus()) } catch (_: Exception) { } }
- val settings = VoicePreferences.load(getApplication())
+ val settings = VoicePreferences.load(application)
call.choice = choices.engineChoice(provider, callLanguage())
// A muted call stays muted on the engine that takes over (what the call last showed).
val muted = call.state.value.muted
@@ -83,14 +83,14 @@ private fun AppStore.begin(call: VoiceBinding, provider: VoiceProvider?) {
else -> VoiceEngineKind.Gemini
}
val engine: VoiceEngine = if (provider == null) {
- val audio = LocalVoiceAudio(getApplication(), VoicePreferences.language(getApplication()))
+ val audio = LocalVoiceAudio(application, VoicePreferences.language(application))
call.recording = { audio.recordingSessionId }
startCallOnHost(call, "device", null)
VoiceSession(contextScope, audio, settings) { sendFromCall(call, it) }
} else {
val voice = choices.voice(provider)
val model = choices.model(provider, VoiceChoices.Model.Realtime)
- fun mic() = AndroidMic(getApplication()).also { mic -> call.recording = { mic.recordingSessionId } }
+ fun mic() = AndroidMic(application).also { mic -> call.recording = { mic.recordingSessionId } }
when {
choices.speechMode(provider) -> {
startCallOnHost(call, "speech", provider)
@@ -103,7 +103,7 @@ private fun AppStore.begin(call: VoiceBinding, provider: VoiceProvider?) {
}
// WebRTC records the microphone itself.
provider == VoiceProvider.OpenAI -> OpenAIRealtimeEngine(contextScope, settings, model, voice,
- choices.model(provider, VoiceChoices.Model.Transcribe), link, WebRtcPeer(getApplication())) { secret, offer ->
+ choices.model(provider, VoiceChoices.Model.Transcribe), link, WebRtcPeer(application)) { secret, offer ->
OpenAIRealtimeEngine.answer(voiceHttp, secret, offer)
}
else -> GeminiLiveEngine(contextScope, settings, model, voice, link, mic(), AndroidPcmPlayer(), voiceHttp)
@@ -202,7 +202,7 @@ internal fun AppStore.hearCalls(events: List<MirrorEvent>) {
fun AppStore.endVoice(error: String? = null) {
val id = state.value.voice?.id ?: return
- finishVoice(id, error); VoiceService.stop(getApplication(), id)
+ finishVoice(id, error); VoiceService.stop(application, id)
}
internal fun AppStore.finishVoice(id: String, error: String? = null) {
@@ -231,7 +231,7 @@ internal suspend fun AppStore.retireVoice() {
val call = voiceBinding; voiceBinding = null; voiceGeneration = null
val callId = state.value.voice?.id
mutableState.update { it.copy(voice = null) }
- if (callId != null) VoiceService.stop(getApplication(), callId)
+ if (callId != null) VoiceService.stop(application, callId)
call?.quality?.report()
call?.engine?.end(); call?.engine?.awaitEnd()
}
@@ -242,24 +242,24 @@ fun AppStore.resumeVoice() { voiceBinding?.engine?.focus(true) }
internal fun AppStore.focusVoice(active: Boolean) { voiceBinding?.engine?.focus(active) }
internal fun AppStore.voiceRecordingSession(): Int? = voiceBinding?.recording?.invoke()
/** The language on-device calls hear; empty follows the phone. */
-internal fun AppStore.callLanguage(): String = VoicePreferences.language(getApplication())
+internal fun AppStore.callLanguage(): String = VoicePreferences.language(application)
/** Picks it, and has Android fetch it when it hears it on device but hasn't downloaded it yet. */
internal fun AppStore.callLanguage(tag: String) {
- VoicePreferences.language(getApplication(), tag)
+ VoicePreferences.language(application, tag)
if (tag.isNotEmpty()) contextScope.launch {
- val support = PlatformSpeech.support(getApplication())
- if (tag !in support.installed && tag in support.downloadable) PlatformSpeech.download(getApplication(), tag)
+ val support = PlatformSpeech.support(application)
+ if (tag !in support.installed && tag in support.downloadable) PlatformSpeech.download(application, tag)
}
}
/** What on-device calls can hear on this phone: Android's on-device languages, and English always. */
internal suspend fun AppStore.callLanguages(): List<String> {
- val onDevice = PlatformSpeech.support(getApplication()).onDevice
+ val onDevice = PlatformSpeech.support(application).onDevice
return if (onDevice.any { VoiceLanguages.base(java.util.Locale.forLanguageTag(it)) == "en" }) onDevice else onDevice + VoiceLanguages.ENGLISH
}
-fun AppStore.voiceSettings(settings: VoiceSettings) { VoicePreferences.save(getApplication(), settings); voiceBinding?.engine?.settings(settings) }
+fun AppStore.voiceSettings(settings: VoiceSettings) { VoicePreferences.save(application, settings); voiceBinding?.engine?.settings(settings) }
// The computer's voice methods: it holds the provider keys and does the provider calls that need them.
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppUpdates.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppUpdates.kt
index 63657d21..fc954780 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppUpdates.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppUpdates.kt
@@ -34,6 +34,9 @@ import kotlinx.coroutines.flow.asStateFlow
* the needed version isn't on Play yet, and a newer release gets a dismissible reminder. A copy not installed from Google
* Play gets neither.
*/
+/** This app's release, without a build's suffix ("2.34.0" of "2.34.0-dev"). */
+internal val APP_RELEASE: String = BuildConfig.VERSION_NAME.substringBefore('-')
+
internal object AppUpdates {
private val mutableStore = MutableStateFlow<String?>(null)
/** The version Play has for this phone; null until asked, or when Play can't say. */
@@ -53,7 +56,7 @@ internal object AppUpdates {
try {
val info = AppUpdateManagerFactory.create(context).requestAppUpdateInfo()
mutableStore.value = if (info.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE)
- UpdateReminder.versionOf(info.availableVersionCode().toLong()) else BuildConfig.VERSION_NAME.substringBefore('-')
+ UpdateReminder.versionOf(info.availableVersionCode().toLong()) else APP_RELEASE
} catch (cancelled: CancellationException) { throw cancelled }
catch (_: Exception) { /* Not from Google Play, or Play can't be reached: no reminder. */ }
}
@@ -82,7 +85,7 @@ internal object AppUpdates {
Symbol("arrow.down.circle.fill", size = 22.dp, tint = Palette.text)
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(tr("Codync {version} is available").replace("{version}", version), style = Type.subheadline.semibold, color = Palette.text)
- Text(tr("You have {version}.").replace("{version}", BuildConfig.VERSION_NAME.substringBefore('-')), style = Type.footnote, color = Palette.secondary)
+ Text(tr("You have {version}.").replace("{version}", APP_RELEASE), style = Type.footnote, color = Palette.secondary)
SecondaryButton("Update", Modifier.padding(top = 4.dp)) { AppUpdates.open(context) }
}
IconButton("Dismiss", "xmark") { AppUpdates.dismiss(context) }
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/BotListView.kt b/apps/android/app/src/main/kotlin/com/codync/android/BotListView.kt
index 61f5b729..8b61211a 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/BotListView.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/BotListView.kt
@@ -21,10 +21,11 @@ import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.LazyItemScope
import androidx.compose.foundation.lazy.LazyListScope
+import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
import android.content.Context
-import androidx.compose.foundation.layout.Column
import androidx.compose.ui.unit.Dp
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
@@ -52,19 +53,32 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import coil3.compose.AsyncImage
import com.codync.android.core.Bot
+import com.codync.android.core.ComputerSelection
import com.codync.android.core.LinkState
import com.codync.android.design.*
import com.kyant.shapes.Capsule
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
-import kotlinx.serialization.json.putJsonArray
/** One computer's roster while the list shows it: its rows' and sections' drags and its section order (kept on this device). */
-private class ComputerRoster(context: Context, val key: String) {
+private class ComputerRoster(private val context: Context, val key: String) {
val reorder = RosterReorder()
val sections = SectionReorder()
var order by mutableStateOf(SectionOrders.load(context, key))
+
+ /** Points the drags at [state]'s bots and sections as [list] shows them. */
+ fun sync(state: AppState, list: LazyListState) {
+ val bots = roster(state.bots)
+ reorder.roster = bots
+ sections.names = orderedSections(sectionNames(bots.filterNot { it.pinned }) +
+ if (bots.any { !it.pinned && it.section == null }) listOf("") else emptyList(), order)
+ sections.save = { order = it; sections.names = it; SectionOrders.save(context, key, it) }
+ sections.position = { name ->
+ val item = "${state.computer.id}:" + if (name.isEmpty()) "label:bots" else "section:$name"
+ list.layoutInfo.visibleItemsInfo.firstOrNull { it.key == item }?.offset?.toFloat() ?: 0f
+ }
+ }
}
/**
@@ -94,18 +108,8 @@ private class ComputerRoster(context: Context, val key: String) {
// A lifted heading folds every computer's bots into their headings while it moves.
val movingComputer = computerReorder.dragged != null
val ordered = computerReorder.shown.mapNotNull { id -> shown.firstOrNull { it.computer.id == id } }
- for (state in shown) {
- val roster = rosters.getOrPut(state.computer.id) { ComputerRoster(context, SectionOrders.key(app.contextId, state.computer.id)) }
- val bots = roster(state.bots)
- roster.reorder.roster = bots
- roster.sections.names = orderedSections(sectionNames(bots.filterNot { it.pinned }) +
- if (bots.any { !it.pinned && it.section == null }) listOf("") else emptyList(), roster.order)
- roster.sections.save = { roster.order = it; roster.sections.names = it; SectionOrders.save(context, roster.key, it) }
- roster.sections.position = { name ->
- val key = "${state.computer.id}:" + if (name.isEmpty()) "label:bots" else "section:$name"
- listState.layoutInfo.visibleItemsInfo.firstOrNull { it.key == key }?.offset?.toFloat() ?: 0f
- }
- }
+ for (state in shown) rosters.getOrPut(state.computer.id) { ComputerRoster(context, SectionOrders.key(app.contextId, state.computer.id)) }
+ .sync(state, listState)
// A folded section renamed or removed here stays folded under its new name, at once, like its bots; a refusal puts the
// folds back, reading and writing the stored ones, as the list may have left the screen.
val renameSection = { roster: ComputerRoster, store: AppStore, from: String, to: String? ->
@@ -157,18 +161,9 @@ private class ComputerRoster(context: Context, val key: String) {
val store = accounts.store(id) ?: continue
val roster = rosters[id] ?: continue
if (grouped) item("computer:$id") {
- Column(Modifier.onSizeChanged { computerReorder.heights[id] = it.height }
- .then(if (computerReorder.dragged == id) Modifier.zIndex(1f).graphicsLayer { translationY = computerReorder.translation(id) } else Modifier.animateItem())) {
- // Not synced while it needs an update: "No bots yet" wouldn't be true.
- ComputerSection(state, empty = state.mismatch == null && roster(state.bots).isEmpty(), folded = movingComputer || id in collapsed,
- stale = app.isStale(state, states), toggle = {
- collapsed = if (id in collapsed) collapsed - id else collapsed + id
- RosterComputers.setFolded(context, collapsed)
- }, move = { computerReorder.move(id, it) },
- extensions = { extensions(id) }.takeIf { state.connection is LinkState.Ready && state.mismatch == null },
- drag = computerReorder.handle(id))
- state.mismatch?.let { UpdateNeededCard(state, it, store::requestHostUpdate, Modifier.padding(vertical = 8.dp)) }
- }
+ ComputerHeading(state, store, computerReorder, folded = movingComputer || id in collapsed, stale = app.isStale(state, states),
+ toggle = { collapsed = if (id in collapsed) collapsed - id else collapsed + id; RosterComputers.setFolded(context, collapsed) },
+ extensions = { extensions(id) })
}
if (grouped && (movingComputer || id in collapsed)) continue
botLines(state, store, roster, folded, grouped, RosterActions(toggleSection,
@@ -190,6 +185,19 @@ private class ComputerRoster(context: Context, val key: String) {
SectionNameDialog(naming) { naming = null }
}
+/** A computer's heading (and, while it needs one, its update notice) that drags to reorder the computers. */
+@Composable private fun LazyItemScope.ComputerHeading(state: AppState, store: AppStore, reorder: SectionReorder, folded: Boolean, stale: Boolean,
+ toggle: () -> Unit, extensions: () -> Unit) {
+ val id = state.computer.id
+ Column(reorderable(reorder, id)) {
+ // Not synced while it needs an update: "No bots yet" wouldn't be true.
+ ComputerSection(state, empty = state.mismatch == null && roster(state.bots).isEmpty(), folded = folded, stale = stale, toggle = toggle,
+ move = { reorder.move(id, it) }, extensions = extensions.takeIf { state.connection is LinkState.Ready && state.mismatch == null },
+ drag = reorder.handle(id))
+ state.mismatch?.let { UpdateNeededCard(state, it, store::requestHostUpdate, Modifier.padding(vertical = 8.dp)) }
+ }
+}
+
/** What a computer's rows and section headings ask of the roster. */
private class RosterActions(val toggleSection: (String) -> Unit, val rename: (String) -> Unit, val remove: (String) -> Unit,
val newSection: (Bot) -> Unit, val edit: (Bot) -> Unit, val delete: (Bot) -> Unit)
@@ -205,12 +213,10 @@ private fun LazyListScope.botLines(state: AppState, store: AppStore, roster: Com
// Folding drops the section's rows from the list; animateItem fades them out and slides the rest up.
is RosterLine.Header -> SectionHeader(line, toggle = { actions.toggleSection(line.name) },
actions = if (state.supportsSections) sectionActions(rename = { actions.rename(line.name) }, remove = { actions.remove(line.name) }) else emptyList(),
- modifier = Modifier.onSizeChanged { sectionReorder.heights[line.name] = it.height }
- .then(if (sectionReorder.dragged == line.name) Modifier.zIndex(1f).graphicsLayer { translationY = sectionReorder.translation(line.name) } else Modifier.animateItem()),
+ modifier = reorderable(sectionReorder, line.name),
drag = sectionReorder.handle(line.name),
move = { sectionReorder.move(line.name, it) })
- RosterLine.Label -> SectionLabel(Modifier.onSizeChanged { sectionReorder.heights[""] = it.height }
- .then(if (sectionReorder.dragged == "") Modifier.zIndex(1f).graphicsLayer { translationY = sectionReorder.translation("") } else Modifier.animateItem()), sectionReorder.handle("")) { sectionReorder.move("", it) }
+ RosterLine.Label -> SectionLabel(reorderable(sectionReorder, ""), sectionReorder.handle("")) { sectionReorder.move("", it) }
is RosterLine.Row -> {
val bot = line.bot
val lifted = reorder.dragged == bot.id
@@ -420,7 +426,3 @@ internal fun backendName(state: AppState, id: String): String =
?.firstOrNull { (it as? kotlinx.serialization.json.JsonObject)?.get("id") == JsonPrimitive(id) }
?.let { ((it as kotlinx.serialization.json.JsonObject)["name"] as? JsonPrimitive)?.content }
?: when (id) { "claude" -> "Claude Code"; "codex" -> "Codex"; "opencode" -> "OpenCode"; "grok" -> "Grok Build"; "gemini" -> "Gemini CLI"; else -> "Custom agent" }
-
-/** Saves a dragged roster order (the host syncs it to every device). */
-internal fun AppStore.reorder(ids: List<String>) =
- command("reorderBots", buildJsonObject { putJsonArray("ids") { ids.forEach { add(JsonPrimitive(it)) } } }, "reorder")
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt b/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt
index 21de91ec..766be69c 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt
@@ -99,8 +99,7 @@ import com.kyant.shapes.Capsule
// ponytail: "in sight" is the open chat with nothing over it, not its scroll position; add that if ratings come too early.
ReviewReading("${state.contextId}/${state.computer.id}/${bot.id}", state.entries.filter { it.botId == bot.id },
ready = details == null && viewing == null && peer == null && callLine == null && !state.trace && state.voice == null &&
- state.drafts[bot.id]?.let { it.text.isBlank() && it.files.isEmpty() } != false && state.actualConnection is LinkState.Ready &&
- state.mismatch == null && state.error == null && state.screenRequest == null && bot.status == "idle")
+ state.drafts[bot.id]?.let { it.text.isBlank() && it.files.isEmpty() } != false && state.settledForReview && bot.status == "idle")
GlassStage(Modifier.fillMaxSize().background(Palette.background), chrome = {
// Down to just above the header's bottom; the bottom one stops under Jump to latest.
ScrollEdge(Edge.Top, top + 84.dp)
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt b/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt
index c95040dc..dd87eef4 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/CodyncApp.kt
@@ -89,91 +89,102 @@ private data class Editing<T>(val computerId: String, val draft: T)
if (bot.kind == "group") groupEditor = Editing(computerId, GroupDraft.from(bot)) else editor = Editing(computerId, BotDraft.from(bot))
}
val openMarketplace = { id: String -> showAccount = false; showComputers = false; marketplace = id }
- Box(Modifier.fillMaxSize().background(Palette.background)) { CompositionLocalProvider(LocalAccounts provides accounts) {
- AnimatedContent(root, transitionSpec = {
- if (initialState == Root.Welcome && targetState == Root.Pairing)
- (slideInHorizontally(Motion.layoutOffset) { it } + fadeIn(Motion.fade())) togetherWith (slideOutHorizontally(Motion.layoutOffset) { -it } + fadeOut(Motion.fade()))
- else if (initialState == Root.Pairing && targetState == Root.Welcome)
- (slideInHorizontally(Motion.layoutOffset) { -it } + fadeIn(Motion.fade())) togetherWith (slideOutHorizontally(Motion.layoutOffset) { it } + fadeOut(Motion.fade()))
- else fadeIn(Motion.fade()) togetherWith fadeOut(Motion.fade())
- }, label = "Root") { shown ->
- when (shown) {
- Root.Loading -> Box(Modifier.fillMaxSize())
- Root.Welcome -> WelcomeView(app, accounts) { welcomed = true }
- Root.Pairing -> Box(Modifier.fillMaxSize().safeDrawingPadding()) {
- PairingView(app, accounts, onSkip = accounts::skipSetup) {
- if (signedIn) AccountSwitcherButton(app) { showAccount = true } else BackButton { welcomed = false }
+ // The sheets too: a bot's editor sets custom icons, which need sign-in.
+ CompositionLocalProvider(LocalAccounts provides accounts) {
+ Box(Modifier.fillMaxSize().background(Palette.background)) {
+ AnimatedContent(root, transitionSpec = {
+ if (initialState == Root.Welcome && targetState == Root.Pairing)
+ (slideInHorizontally(Motion.layoutOffset) { it } + fadeIn(Motion.fade())) togetherWith (slideOutHorizontally(Motion.layoutOffset) { -it } + fadeOut(Motion.fade()))
+ else if (initialState == Root.Pairing && targetState == Root.Welcome)
+ (slideInHorizontally(Motion.layoutOffset) { -it } + fadeIn(Motion.fade())) togetherWith (slideOutHorizontally(Motion.layoutOffset) { it } + fadeOut(Motion.fade()))
+ else fadeIn(Motion.fade()) togetherWith fadeOut(Motion.fade())
+ }, label = "Root") { shown ->
+ when (shown) {
+ Root.Loading -> Box(Modifier.fillMaxSize())
+ Root.Welcome -> WelcomeView(app, accounts) { welcomed = true }
+ Root.Pairing -> Box(Modifier.fillMaxSize().safeDrawingPadding()) {
+ PairingView(app, accounts, onSkip = accounts::skipSetup) {
+ if (signedIn) AccountSwitcherButton(app) { showAccount = true } else BackButton { welcomed = false }
+ }
+ }
+ Root.Tabs -> MainTabs(app, states, accounts, account = { showAccount = true }, manage = { showComputers = true }, usage = { showUsage = true },
+ newBot = { creating = NewTarget(group = false, computerId = it) }, newGroup = { creating = NewTarget(group = true, computerId = it) },
+ edit = edit, extensions = openMarketplace, covered = showAccount || showComputers || showPairing || showUsage ||
+ marketplace != null || creating != null || access != null || editor != null || groupEditor != null || app.error != null) { chat ->
+ // A conversation, talking to the computer the bot lives on.
+ accounts.store(chat.computer.id)?.let { store -> ChatScreen(chat, store) { bot -> edit(chat.computer.id, bot) } }
}
}
- Root.Tabs -> MainTabs(app, states, accounts, account = { showAccount = true }, manage = { showComputers = true }, usage = { showUsage = true },
- newBot = { creating = NewTarget(group = false, computerId = it) }, newGroup = { creating = NewTarget(group = true, computerId = it) },
- edit = edit, extensions = openMarketplace, covered = showAccount || showComputers || showPairing || showUsage ||
- marketplace != null || creating != null || access != null || editor != null || groupEditor != null || app.error != null) { chat ->
- // A conversation, talking to the computer the bot lives on.
- accounts.store(chat.computer.id)?.let { store -> ChatScreen(chat, store) { bot -> edit(chat.computer.id, bot) } }
+ }
+ }
+ CodyncSheet(showAccount && (app.setupComplete || signedIn) && !app.loading, { showAccount = false }) {
+ AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Account))
+ AccountSwitcherView(app, accounts) { showPairing = true }
+ }
+ CodyncSheet(showComputers && !app.loading, { showComputers = false }) {
+ AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Computers))
+ ComputersView(app, states, accounts, { showPairing = true }, { access = it }, openMarketplace)
+ }
+ CodyncSheet(access, { access = null }) { AccessRequestView(app, accounts, it) }
+ CodyncSheet(showPairing && !app.loading, { showPairing = false }) {
+ AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Pairing))
+ PairingView(app, accounts, inModal = true)
+ }
+ CodyncSheet(showUsage && !app.loading, { showUsage = false }) {
+ AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Usage))
+ UsageSheet(app, states, accounts)
+ }
+ // Each computer has its own Extensions; it's opened from that computer's heading or row.
+ CodyncSheet(marketplace?.takeIf { root == Root.Tabs && it in computers }, { marketplace = null }) { id ->
+ AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Marketplace))
+ OnComputer(id, computers, accounts) { state, store -> key(id) { MarketplaceView(state, store) } }
+ }
+ CodyncSheet(creating?.takeIf { !app.loading }, { creating = null }) { target ->
+ OnComputer(target.computerId, computers, accounts) { state, store ->
+ // Not keyed on the computer: a new bot keeps its name and face when it moves to another.
+ key(app.contextId, app.generation) {
+ if (target.group) NewGroupView(state, store)
+ // A new bot can move to another computer until it's created (iOS `NewBotView`'s Computer row).
+ else NewBotView(state, store, availableComputers(app, states).map { it.computer.id to computerChoice(it) }) {
+ creating = NewTarget(group = false, computerId = it)
+ }
}
}
}
- } }
- CodyncSheet(showAccount && (app.setupComplete || signedIn) && !app.loading, { showAccount = false }) {
- AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Account))
- AccountSwitcherView(app, accounts) { showPairing = true }
- }
- CodyncSheet(showComputers && !app.loading, { showComputers = false }) {
- AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Computers))
- ComputersView(app, states, accounts, { showPairing = true }, { access = it }, openMarketplace)
- }
- CodyncSheet(access, { access = null }) { AccessRequestView(app, accounts, it) }
- CodyncSheet(showPairing && !app.loading, { showPairing = false }) {
- AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Pairing))
- PairingView(app, accounts, inModal = true)
- }
- CodyncSheet(showUsage && !app.loading, { showUsage = false }) {
- AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Usage))
- UsageSheet(app, states, accounts)
- }
- // Each computer has its own Extensions; it's opened from that computer's heading or row.
- CodyncSheet(marketplace?.takeIf { root == Root.Tabs }?.let(computers::get), { marketplace = null }) { state ->
- AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Marketplace))
- accounts.store(state.computer.id)?.let { store -> key(state.computer.id) { MarketplaceView(state, store) } }
- }
- CodyncSheet(creating?.takeIf { !app.loading }, { creating = null }) { target ->
- val state = computers[target.computerId]
- val store = accounts.store(target.computerId)
- if (state != null && store != null) key(app.contextId, app.generation, target.computerId) {
- if (target.group) NewGroupView(state, store)
- // A new bot can move to another computer until it's created (iOS `NewBotView`'s Computer row).
- else NewBotView(state, store, availableComputers(app, states).map { it.computer.id to computerChoice(it) }) {
- creating = NewTarget(group = false, computerId = it)
+ // A group's editor is its details (a chat's title and the roster open it); a bot's (the roster's Edit profile) is all its settings.
+ CodyncSheet(groupEditor.takeIf { !app.loading }, { groupEditor = null }) { target ->
+ AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.BotDetails))
+ OnComputer(target.computerId, computers, accounts) { state, store ->
+ key(app.contextId, app.generation, target.computerId, target.draft.id) { GroupEditor(state, target.draft, store) }
}
}
+ CodyncSheet(editor.takeIf { !app.loading }, { editor = null }) { target ->
+ AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.BotDetails))
+ OnComputer(target.computerId, computers, accounts) { state, store ->
+ key(app.contextId, app.generation, target.computerId, target.draft.id) { BotEditor(state, target.draft, store) }
+ }
+ }
+ // The remote screen opens over the app once its sheets have slid away: any computer's request (chat header, Computers, `codync://screen`).
+ val screen = states.firstOrNull { it.screenRequest != null }
+ LaunchedEffect(screen?.computer?.id, screen?.screenRequest) { if (screen != null) { closeAll(); showUsage = false } }
+ ScreenLayer(screen, screen?.let { accounts.store(it.computer.id) })
+ // One place for every computer's errors the screen showing them doesn't handle itself (pairing, access, the new and edit sheets do).
+ val inline = root == Root.Pairing || showPairing || access != null || creating != null || editor != null || groupEditor != null
+ val error = app.error ?: states.firstNotNullOfOrNull { it.error }
+ CodyncDialog("Something went wrong", error != null && !inline, accounts::clearError, error, cancel = "OK") { emptyList() }
}
- // A group's editor is its details (a chat's title and the roster open it); a bot's (the roster's Edit profile) is all its settings.
- CodyncSheet(groupEditor.takeIf { !app.loading }, { groupEditor = null }) { target ->
- AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.BotDetails))
- val state = computers[target.computerId]
- val store = accounts.store(target.computerId)
- if (state != null && store != null) key(app.contextId, app.generation, target.computerId, target.draft.id) { GroupEditor(state, target.draft, store) }
- }
- CodyncSheet(editor.takeIf { !app.loading }, { editor = null }) { target ->
- AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.BotDetails))
- val state = computers[target.computerId]
- val store = accounts.store(target.computerId)
- if (state != null && store != null) key(app.contextId, app.generation, target.computerId, target.draft.id) { BotEditor(state, target.draft, store) }
- }
- // The remote screen opens over the app once its sheets have slid away: any computer's request (chat header, Computers, `codync://screen`).
- val screen = states.firstOrNull { it.screenRequest != null }
- LaunchedEffect(screen?.computer?.id, screen?.screenRequest) { if (screen != null) { closeAll(); showUsage = false } }
- ScreenLayer(screen, screen?.let { accounts.store(it.computer.id) })
- // One place for every computer's errors the screen showing them doesn't handle itself (pairing, access, the new and edit sheets do).
- val inline = root == Root.Pairing || showPairing || access != null || creating != null || editor != null || groupEditor != null
- val error = app.error ?: states.firstNotNullOfOrNull { it.error }
- CodyncDialog("Something went wrong", error != null && !inline, accounts::clearError, error, cancel = "OK") { emptyList() }
}
/** The account's store, for the few computer screens that also act on the account (custom icons need sign-in). */
internal val LocalAccounts = staticCompositionLocalOf<AccountStore?> { null }
+/** [content] with computer [id]'s state and store, while both are there (a sheet of one computer). */
+@Composable private fun OnComputer(id: String, computers: Map<String, AppState>, accounts: AccountStore, content: @Composable (AppState, AppStore) -> Unit) {
+ val state = computers[id] ?: return
+ val store = accounts.store(id) ?: return
+ content(state, store)
+}
+
/** Computers that can take a new bot once they're connected: not ones waiting for an update, or that won't come back (iOS `availableStores`). */
internal fun availableComputers(app: AccountContext, states: List<AppState>): List<AppState> =
states.filter { it.mismatch == null && !app.isStale(it, states) }
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ComputerSection.kt b/apps/android/app/src/main/kotlin/com/codync/android/ComputerSection.kt
index 64ccc718..d83bbeec 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/ComputerSection.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ComputerSection.kt
@@ -1,6 +1,5 @@
package com.codync.android
-import android.content.Context
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.fadeIn
@@ -9,11 +8,9 @@ import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
-import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
-import androidx.compose.foundation.layout.width
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
@@ -31,40 +28,13 @@ import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.stateDescription
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
-import androidx.core.content.edit
+import com.codync.android.core.ComputerSelection
import com.codync.android.core.HostRoute
import com.codync.android.core.LinkState
import com.codync.android.design.*
-// The roster's computers (iOS `ComputerSection`, `ComputerFilterHeader`, `ComputerSelection`): a heading per
-// computer once several show, and the header's filter. What's hidden or folded is kept on this device only.
-
-/** An empty exclusion list means all computers, newly paired ones included (iOS `ComputerSelection`). */
-internal class ComputerSelection(val all: List<String>, hidden: String) {
- private val hidden = hidden.split(',').filter(String::isNotEmpty).toSet()
-
- val shown: List<String> get() = all.filter { it !in hidden }.ifEmpty { all }
-
- fun toggling(id: String): String {
- if (id !in all) return encoded(all.toSet() - shown.toSet())
- val visible = shown.toMutableSet()
- if (id in visible) { if (visible.size > 1) visible.remove(id) } else visible.add(id)
- return encoded(all.toSet() - visible)
- }
-
- fun only(id: String): String = if (id !in all) "" else encoded(all.toSet() - id)
-
- private fun encoded(ids: Set<String>): String = ids.sorted().joinToString(",")
-}
-
-/** Computers left out of the roster, and computers whose bots are folded away, on this device (iOS `@AppStorage`). */
-internal object RosterComputers {
- private fun prefs(context: Context) = context.getSharedPreferences("codync-roster", Context.MODE_PRIVATE)
- fun hidden(context: Context): String = prefs(context).getString("hiddenComputers", "").orEmpty()
- fun setHidden(context: Context, value: String) = prefs(context).edit { putString("hiddenComputers", value) }
- fun folded(context: Context): Set<String> = prefs(context).getString("collapsedComputers", "").orEmpty().split(',').filter(String::isNotEmpty).toSet()
- fun setFolded(context: Context, ids: Set<String>) = prefs(context).edit { putString("collapsedComputers", ids.sorted().joinToString(",")) }
-}
+// The roster's computers (iOS `ComputerSection`, `ComputerFilterHeader`): a heading per computer once several show,
+// and the header's filter. What's hidden or folded is kept on this device only (`RosterComputers`).
/**
* A computer's heading above its bots: badge, name and connection. Tap folds its bots away; touch and hold,
@@ -119,8 +89,8 @@ internal object RosterComputers {
manage: () -> Unit) {
val selection = ComputerSelection(states.map { it.computer.id }, hidden)
val shown = states.filter { it.computer.id in selection.shown }
- val summary = connectionSummary(shown)
val translate = translator()
+ val summary = connectionSummary(shown).let { it.filled(translate(it.template)) }
DropdownMenu({
listOf(
MenuItem("All computers", icon = "desktopcomputer", selected = selection.shown.size == states.size) { setHidden("") },
@@ -134,25 +104,10 @@ internal object RosterComputers {
MenuItem("Reconnect", icon = "arrow.clockwise", divider = true, enabled = shown.isNotEmpty(), action = reconnect),
MenuItem("Manage computers", icon = "desktopcomputer", action = manage),
)
- }, label = "Computers, ${summaryPhrase(summary)}. Filter conversations") {
+ }, label = "Computers, $summary. Filter conversations") {
Row(Modifier.padding(vertical = 6.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
- Text(summaryPhrase(summary), style = Type.system(12f).medium, color = Palette.secondary, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Text(summary, style = Type.system(12f).medium, color = Palette.secondary, maxLines = 1, overflow = TextOverflow.Ellipsis)
Symbol("chevron.down", size = 15.dp, tint = Palette.secondary)
}
}
}
-
-/** "3 connected" and the other summaries, in the app's language (iOS `ComputerFilterHeader.phrase`). */
-@Composable private fun summaryPhrase(raw: String): String {
- val parts = raw.split(' ', limit = 2)
- val count = parts.getOrNull(0)?.toIntOrNull()
- if (parts.size == 2 && count != null) {
- if (parts[1] == "connected") return tr("%d connected").replace("%d", "$count")
- if (parts[1] == "offline") return tr("%d offline").replace("%d", "$count")
- }
- if (parts.size == 2 && parts[1] == "connected") {
- val ends = parts[0].split('/').mapNotNull(String::toIntOrNull)
- if (ends.size == 2) return tr("%d/%d connected").replaceFirst("%d", "${ends[0]}").replaceFirst("%d", "${ends[1]}")
- }
- return tr(raw)
-}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ComputersView.kt b/apps/android/app/src/main/kotlin/com/codync/android/ComputersView.kt
index a5755c9d..00d681b8 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/ComputersView.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ComputersView.kt
@@ -107,8 +107,9 @@ import kotlinx.serialization.json.put
CodyncSheet(networkState?.network?.let { networkState to it }, { network = null }) { (state, view) ->
accounts.store(state.computer.id)?.let { NetworkSheet(view, it::refreshNetwork) }
}
- val colorStore = accounts.store(coloring)
- SwatchPanel(coloring != null, colorStore?.state?.value?.computer?.color, { coloring = null }) { colorStore?.setColor(it) }
+ SwatchPanel(coloring != null, states.firstOrNull { it.computer.id == coloring }?.computer?.color, { coloring = null }) {
+ accounts.store(coloring)?.setColor(it)
+ }
val forgetting = confirmForget
CodyncDialog(tr("Remove {name}?").replace("{name}", forgetting?.computer?.name ?: "computer"), forgetting != null, { confirmForget = null },
"Its bots and conversations stay on that computer. You can pair again any time.") {
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.kt b/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.kt
index c855e2ce..e6b98d2d 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.kt
@@ -94,16 +94,22 @@ internal fun pairingLine(cloud: String?): String {
internal fun pairingLine(pasted: String, scheme: String): String =
pairingLine(runCatching { Pairing.parse(pasted, scheme).computer.cloud }.getOrNull())
+/** A sentence to translate, and the counts that fill its `%d`s in order. */
+internal data class Phrase(val template: String, val counts: List<Int> = emptyList()) {
+ /** [translated] (the template in the app's language) with the counts filled in. */
+ fun filled(translated: String = template): String = counts.fold(translated) { text, count -> text.replaceFirst("%d", "$count") }
+}
+
/** "3 connected", "1/2 connected", "Connecting…", "No access": the roster header's summary of the computers it shows (iOS `ConnectionSummary`). */
-internal fun connectionSummary(states: List<AppState>): String {
- if (states.isEmpty()) return "Computers"
+internal fun connectionSummary(states: List<AppState>): Phrase {
+ if (states.isEmpty()) return Phrase("Computers")
val online = states.count { it.connection is LinkState.Ready }
return when {
- online == states.size -> "$online connected"
- online > 0 -> "$online/${states.size} connected"
- states.any { it.connection is LinkState.Connecting } -> "Connecting…"
- states.all { it.connection.unauthorized } -> "No access"
- else -> "${states.size} offline"
+ online == states.size -> Phrase("%d connected", listOf(online))
+ online > 0 -> Phrase("%d/%d connected", listOf(online, states.size))
+ states.any { it.connection is LinkState.Connecting } -> Phrase("Connecting…")
+ states.all { it.connection.unauthorized } -> Phrase("No access")
+ else -> Phrase("%d offline", listOf(states.size))
}
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/Dictation.kt b/apps/android/app/src/main/kotlin/com/codync/android/Dictation.kt
index 567d1251..687e6488 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/Dictation.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/Dictation.kt
@@ -1,11 +1,10 @@
package com.codync.android
import android.content.Context
-import android.content.Intent
import android.os.Build
import android.os.Bundle
+import android.os.SystemClock
import android.speech.RecognitionListener
-import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
@@ -13,14 +12,15 @@ import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.codync.android.core.DictationText
+import com.codync.android.core.MicSource
import com.codync.android.core.Pcm
import com.codync.android.core.VoiceChoices
-import com.codync.android.core.VoiceLanguages
import com.codync.android.core.VoiceProvider
import java.io.ByteArrayOutputStream
import java.util.Locale
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
@@ -29,13 +29,41 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
+/** What dictation asks of the computer and the phone (iOS `DictationService`), so a test can stand in for them. */
+internal class DictationService(
+ /** The engine picked beside the mic: a provider, or null for on-device speech. */
+ val picked: VoiceProvider?,
+ /** Whether the computer has [VoiceProvider]'s key; it throws when the computer can't be reached. */
+ val hasKey: suspend (VoiceProvider) -> Boolean,
+ val openMic: () -> MicSource,
+ /** The computer's transcript of a recording, on the user's key. */
+ val transcribe: suspend (ByteArray, VoiceProvider) -> String,
+)
+
+/** Dictation through this computer: its keys and transcription, and the phone's microphone. */
+internal fun AppStore.dictationService(context: Context) = DictationService(voiceChoices().dictation,
+ hasKey = { provider -> voiceStatus().also { voiceChoices().remember(it) }.configured(provider) },
+ openMic = { AndroidMic(context) }, transcribe = ::transcribeDictation)
+
+/** The recording in pieces, a few transcribed at a time and joined in order, then counted toward this month's minutes. */
+private suspend fun AppStore.transcribeDictation(pcm: ByteArray, provider: VoiceProvider): String = coroutineScope {
+ val model = voiceChoices().model(provider, VoiceChoices.Model.Transcribe)
+ val gate = Semaphore(DictationText.IN_FLIGHT)
+ val texts = DictationText.pieces(pcm.size).map { range ->
+ async { gate.withPermit { voiceTranscribe(provider, model, Pcm.wav(pcm.copyOfRange(range.first, range.last + 1))).trim() } }
+ }.awaitAll()
+ voiceChoices().addUsage(provider, DictationText.seconds(pcm.size))
+ inReadersScript(texts.filter { it.isNotEmpty() }.fold("", DictationText::join))
+}
+
/**
* Dictation into the message box (iOS `Dictation`). On device, Android's recognizer types the words as it hears
* them, after what was in the box, and stops at a pause or at the recording pill's stop; it hears the call's
* language. With a provider picked beside the mic, it records, and the pill's stop has the computer transcribe all
* of it on the user's key; the transcript goes after what's in the box by then.
*/
-internal class Dictation(private val context: Context, private val scope: CoroutineScope) {
+internal class Dictation(private val context: Context, private val scope: CoroutineScope,
+ private val clock: () -> Long = SystemClock::elapsedRealtime) {
var listening by mutableStateOf(false); private set
/** Recorded for a provider, waiting for its transcript. */
var transcribing by mutableStateOf(false); private set
@@ -48,7 +76,7 @@ internal class Dictation(private val context: Context, private val scope: Corout
/** The picked provider has no key on the computer: Voice chat settings show where to add one. */
var needsKey by mutableStateOf(false)
private var recognizer: SpeechRecognizer? = null
- private var mic: AndroidMic? = null
+ private var mic: MicSource? = null
/** Recording for a provider: what the microphone heard, and whose computer transcribes it. */
private var recording: Recording? = null
/** Changes the box's text: on-device words replace what follows `before`; a transcript goes after the box as it is then. */
@@ -59,16 +87,16 @@ internal class Dictation(private val context: Context, private val scope: Corout
/** Bumped per start and stop, so a start still waiting (the key check) or a late result of an earlier one is dropped. */
private var generation = 0
- private class Recording(val provider: VoiceProvider, val store: AppStore, val pcm: ByteArrayOutputStream = ByteArrayOutputStream())
+ private class Recording(val provider: VoiceProvider, val service: DictationService, val pcm: ByteArrayOutputStream = ByteArrayOutputStream())
- /** Starts with the engine picked beside the mic, after [draft]; a provider goes through [store]'s computer. */
- fun start(draft: String, store: AppStore, edit: ((String) -> String) -> Unit) {
+ /** Starts with the engine picked beside the mic, after [draft]; a provider goes through [service]'s computer. */
+ fun start(draft: String, service: DictationService, edit: ((String) -> String) -> Unit) {
if (listening || transcribing) return
failure = null; needsKey = false
val asked = ++generation
before = draft
- val provider = store.voiceChoices().dictation
- scope.launch { if (provider != null) record(provider, store, asked, edit) else recognize(asked, edit) }
+ val provider = service.picked
+ scope.launch { if (provider != null) record(provider, service, asked, edit) else recognize(asked, edit) }
}
/** The pill's stop: on-device speech has already typed its words; a recording gets transcribed. */
@@ -82,7 +110,7 @@ internal class Dictation(private val context: Context, private val scope: Corout
transcribing = true
transcription = scope.launch {
try {
- val said = transcribe(pcm, recorded.provider, recorded.store)
+ val said = recorded.service.transcribe(pcm, recorded.provider)
if (asked == generation) apply?.invoke { DictationText.join(it, said) }
} catch (cancelled: CancellationException) { throw cancelled }
catch (error: Exception) { if (asked == generation) failure = error.message ?: "Couldn't transcribe." }
@@ -95,7 +123,8 @@ internal class Dictation(private val context: Context, private val scope: Corout
generation++
transcription?.cancel(); transcription = null
recognizer?.cancel(); recognizer?.destroy(); recognizer = null
- mic?.let { old -> scope.launch { old.stop() } }; mic = null
+ // Started at once: the box's scope may already be cancelled with it, and the microphone mustn't outlive the box.
+ mic?.let { old -> scope.launch(start = CoroutineStart.UNDISPATCHED) { old.stop() } }; mic = null
recording = null
transcribing = false
edit = null
@@ -106,33 +135,32 @@ internal class Dictation(private val context: Context, private val scope: Corout
private fun recognize(asked: Int, edit: ((String) -> String) -> Unit) {
if (asked != generation) return
if (!SpeechRecognizer.isRecognitionAvailable(context)) { failure = "Speech recognition isn't available on this phone."; return }
+ this.edit = edit
+ startedAt = clock()
+ listening = true
// On this phone where Android can (as the iPhone does when it can), else the phone's recognizer.
- val local = Build.VERSION.SDK_INT >= 31 && SpeechRecognizer.isOnDeviceRecognitionAvailable(context)
- val engine = if (local) SpeechRecognizer.createOnDeviceSpeechRecognizer(context) else SpeechRecognizer.createSpeechRecognizer(context)
+ listen(asked, onDevice = Build.VERSION.SDK_INT >= 31 && SpeechRecognizer.isOnDeviceRecognitionAvailable(context))
+ }
+
+ private fun listen(asked: Int, onDevice: Boolean) {
val language = VoicePreferences.language(context).ifEmpty { Locale.getDefault().toLanguageTag() }
- engine.setRecognitionListener(Listener(asked, language))
+ val engine = if (onDevice && Build.VERSION.SDK_INT >= 31) SpeechRecognizer.createOnDeviceSpeechRecognizer(context)
+ else SpeechRecognizer.createSpeechRecognizer(context)
+ engine.setRecognitionListener(Listener(asked, language, onDevice))
recognizer = engine
- this.edit = edit
- startedAt = android.os.SystemClock.elapsedRealtime()
- listening = true
- engine.startListening(Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
- .putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
- .putExtra(RecognizerIntent.EXTRA_LANGUAGE, language)
- .putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
- .putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, true))
+ engine.startListening(recognizerIntent(language))
}
/** Records for [provider] once the computer has its key, so nothing said is lost to a missing one. */
- private suspend fun record(provider: VoiceProvider, store: AppStore, asked: Int, edit: ((String) -> String) -> Unit) {
+ private suspend fun record(provider: VoiceProvider, service: DictationService, asked: Int, edit: ((String) -> String) -> Unit) {
try {
- val status = store.voiceStatus()
- store.voiceChoices().remember(status)
+ val configured = service.hasKey(provider)
if (asked != generation) return
- if (!status.configured(provider)) { needsKey = true; return }
+ if (!configured) { needsKey = true; return }
} catch (cancelled: CancellationException) { throw cancelled }
catch (error: Exception) { if (asked == generation) failure = error.message ?: "Can't reach the computer."; return }
- val microphone = AndroidMic(context)
- val take = Recording(provider, store)
+ val microphone = service.openMic()
+ val take = Recording(provider, service)
try {
microphone.start({ pcm, heard -> scope.launch { if (asked == generation && recording === take) { take.pcm.write(pcm); level = heard } } }) {
scope.launch { if (asked == generation) { failure = "The microphone isn't available."; stop() } }
@@ -143,21 +171,10 @@ internal class Dictation(private val context: Context, private val scope: Corout
mic = microphone
this.edit = edit
recording = take
- startedAt = android.os.SystemClock.elapsedRealtime()
+ startedAt = clock()
listening = true
}
- /** The recording in pieces, a few transcribed at a time and joined in order, then counted toward this month's minutes. */
- private suspend fun transcribe(pcm: ByteArray, provider: VoiceProvider, store: AppStore): String = coroutineScope {
- val model = store.voiceChoices().model(provider, VoiceChoices.Model.Transcribe)
- val gate = Semaphore(DictationText.IN_FLIGHT)
- val texts = DictationText.pieces(pcm.size).map { range ->
- async { gate.withPermit { store.voiceTranscribe(provider, model, Pcm.wav(pcm.copyOfRange(range.first, range.last + 1))).trim() } }
- }.awaitAll()
- store.voiceChoices().addUsage(provider, DictationText.seconds(pcm.size))
- inReadersScript(texts.filter { it.isNotEmpty() }.fold("", DictationText::join))
- }
-
private fun recognized(text: String, final: Boolean, asked: Int) {
if (asked != generation) return
val start = before
@@ -165,20 +182,21 @@ internal class Dictation(private val context: Context, private val scope: Corout
if (final) stop()
}
- private inner class Listener(private val asked: Int, private val language: String) : RecognitionListener {
- private fun text(results: Bundle?) = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull().orEmpty()
- .let { if (VoiceLanguages.base(Locale.forLanguageTag(language)) == "zh") inReadersScript(it) else it }
- override fun onPartialResults(partial: Bundle?) { text(partial).takeIf { it.isNotEmpty() }?.let { recognized(it, false, asked) } }
- override fun onResults(results: Bundle?) { recognized(text(results), true, asked) }
+ private inner class Listener(private val asked: Int, private val language: String, private val onDevice: Boolean) : RecognitionListener {
+ override fun onPartialResults(partial: Bundle?) { recognizedText(partial, language).takeIf { it.isNotEmpty() }?.let { recognized(it, false, asked) } }
+ override fun onResults(results: Bundle?) { recognized(recognizedText(results, language), true, asked) }
override fun onRmsChanged(rmsdB: Float) { if (asked == generation && listening) level = ((rmsdB + 2) / 12).coerceIn(0f, 1f) }
override fun onError(error: Int) {
if (asked != generation) return
+ val noLanguage = error == SpeechRecognizer.ERROR_LANGUAGE_NOT_SUPPORTED || error == SpeechRecognizer.ERROR_LANGUAGE_UNAVAILABLE
+ // The on-device recognizer may lack the language: the phone's own recognizer tries once more.
+ if (onDevice && noLanguage) { recognizer?.destroy(); listen(asked, onDevice = false); return }
// Nothing heard before the pause just ends it, as on the iPhone.
if (error != SpeechRecognizer.ERROR_NO_MATCH && error != SpeechRecognizer.ERROR_SPEECH_TIMEOUT && error != SpeechRecognizer.ERROR_CLIENT)
- failure = when (error) {
- SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS -> "Allow microphone access in Settings to dictate."
- SpeechRecognizer.ERROR_NETWORK, SpeechRecognizer.ERROR_NETWORK_TIMEOUT -> "Dictation needs a connection for this language."
- SpeechRecognizer.ERROR_LANGUAGE_NOT_SUPPORTED, SpeechRecognizer.ERROR_LANGUAGE_UNAVAILABLE -> "Speech recognition isn't available for this language right now."
+ failure = when {
+ error == SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS -> "Allow microphone access in Settings to dictate."
+ error == SpeechRecognizer.ERROR_NETWORK || error == SpeechRecognizer.ERROR_NETWORK_TIMEOUT -> "Dictation needs a connection for this language."
+ noLanguage -> "Speech recognition isn't available for this language right now."
else -> "Couldn't hear you. Check the microphone and Android's speech settings."
}
stop()
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/DictationControls.kt b/apps/android/app/src/main/kotlin/com/codync/android/DictationControls.kt
index 750edeef..95d09520 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/DictationControls.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/DictationControls.kt
@@ -49,7 +49,7 @@ import kotlinx.coroutines.delay
@Composable internal fun DictationButton(dictation: Dictation, state: AppState, store: AppStore, height: Dp, draft: () -> String,
edit: ((String) -> String) -> Unit) {
val context = LocalContext.current
- val start = { dictation.start(draft(), store, edit) }
+ val start = { dictation.start(draft(), store.dictationService(context), edit) }
val permission = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (granted) start() else dictation.failure = "Allow microphone access in Settings to dictate."
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/DraftBook.kt b/apps/android/app/src/main/kotlin/com/codync/android/DraftBook.kt
index e3b48d23..6de9238b 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/DraftBook.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/DraftBook.kt
@@ -20,11 +20,7 @@ data class ComposerDraft(val botId: String, val text: String = "",
/** One bounded draft book per account/computer; a draft's nonce also identifies its durable send. */
class DraftBook(private val directory: File, computerId: String) {
- private val file: AtomicFile
- init {
- require(computerId.matches(Regex("[A-Za-z0-9_-]{22}")))
- file = AtomicFile(File(directory, "drafts-$computerId.json"))
- }
+ private val file = bookFile(directory, computerId)
@Synchronized fun read(): List<ComposerDraft> {
if (!file.baseFile.exists()) return emptyList()
@@ -71,5 +67,13 @@ class DraftBook(private val directory: File, computerId: String) {
}
}
- companion object { private const val MAX_BYTES = 8 * 1024 * 1024 }
+ companion object {
+ private const val MAX_BYTES = 8 * 1024 * 1024
+ private fun bookFile(directory: File, computerId: String): AtomicFile {
+ require(computerId.matches(Regex("[A-Za-z0-9_-]{22}")))
+ return AtomicFile(File(directory, "drafts-$computerId.json"))
+ }
+ /** Deletes a computer's drafts. */
+ fun delete(directory: File, computerId: String) { bookFile(directory, computerId).delete() }
+ }
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/HandoffRows.kt b/apps/android/app/src/main/kotlin/com/codync/android/HandoffRows.kt
index 47dfc177..84e74ed4 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/HandoffRows.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/HandoffRows.kt
@@ -97,13 +97,3 @@ import kotlinx.serialization.json.JsonObject
}
}
}
-
-/** Carries on with the bot's current conversation instead of the handoff. */
-internal fun AppStore.keepConversation(entry: Entry) = command("keepConversation", body("entryId" to entry.id), "handoff:" + entry.id)
-
-/** Saves the user's version of a handoff that hasn't been sent; whether it did (its error shows). */
-internal suspend fun AppStore.editHandoff(entry: Entry, text: String): Boolean = try {
- hostCall("editHandoff", body("entryId" to entry.id, "text" to text), 30_000)
- true
-} catch (cancelled: kotlinx.coroutines.CancellationException) { throw cancelled }
-catch (error: Exception) { showError(error); false }
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MainTabs.kt b/apps/android/app/src/main/kotlin/com/codync/android/MainTabs.kt
index bf982b80..372919c0 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/MainTabs.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/MainTabs.kt
@@ -28,10 +28,8 @@ import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.zIndex
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.unit.dp
-import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.platform.LocalContext
import com.codync.android.core.Bot
-import com.codync.android.core.LinkState
import com.codync.android.core.ReviewCancellation
import com.codync.android.design.*
@@ -51,16 +49,9 @@ private enum class AppTab { Bots, State, Settings }
if (open != null && tab != AppTab.Bots) tab = AppTab.Bots
// Leaving a chat whose answer was read may invite a rating, once the roster has stayed clear (iOS `RootView`).
val context = LocalContext.current
- val openChat = open?.let { "${app.contextId}/${it.computer.id}/${it.selectedBot}" }
- var lastChat by remember { mutableStateOf<String?>(null) }
- LaunchedEffect(openChat) {
- if (openChat != null) ReviewPrompt.cancel(context, ReviewCancellation.Interaction)
- else lastChat?.let { ReviewPrompt.returned(context, it) }
- lastChat = openChat
- }
+ ReviewOnReturn(open?.let { "${app.contextId}/${it.computer.id}/${it.selectedBot}" })
ReviewInvitationEffect(covered || tab != AppTab.Bots || open != null || states.isEmpty() || states.any { state ->
- state.actualConnection !is LinkState.Ready || state.mismatch != null || state.error != null || state.screenRequest != null ||
- state.bots.any { it.status in listOf("working", "needsInput", "error") }
+ !state.settledForReview || state.bots.any { it.status in listOf("working", "needsInput", "error") }
})
AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(when (tab) {
AppTab.Bots -> AnalyticsScreen.Bots
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MemoryCard.kt b/apps/android/app/src/main/kotlin/com/codync/android/MemoryCard.kt
index fb19784e..5ca7bd7d 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/MemoryCard.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/MemoryCard.kt
@@ -3,7 +3,6 @@ package com.codync.android
import android.content.res.Configuration
import android.text.format.DateUtils
import androidx.compose.foundation.layout.Arrangement
-import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
@@ -34,8 +33,6 @@ import com.codync.android.core.MemoryFileDetail
import com.codync.android.core.MemoryFiles
import com.codync.android.design.*
import kotlinx.coroutines.launch
-import kotlinx.serialization.json.buildJsonObject
-import kotlinx.serialization.json.put
private enum class MemorySection { Yours, Bot, Dreams, Harness }
@@ -237,11 +234,3 @@ private fun CardRows.harnessRows(project: BotMemory.Project?) {
/** "5 minutes ago", "Yesterday": the system's relative date, as iOS's `.relative(presentation: .named)`. */
private fun relative(milliseconds: Long): String =
DateUtils.getRelativeTimeSpanString(milliseconds, System.currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS).toString()
-
-/** Whether the bot's harness keeps its own memory on beside Codync's (iOS `setHarnessMemory`). */
-internal fun AppStore.setHarnessMemory(bot: Bot, on: Boolean) =
- command("updateBot", buildJsonObject { put("id", bot.id); put("harnessMemory", on) }, "memory:" + bot.id)
-
-/** Whether the bot uses what all the user's bots share (iOS `setSharedMemory`). */
-internal fun AppStore.setSharedMemory(bot: Bot, shared: Boolean) =
- command("updateBot", buildJsonObject { put("id", bot.id); put("sharedMemory", shared) }, "memory:" + bot.id)
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MirrorDatabase.kt b/apps/android/app/src/main/kotlin/com/codync/android/MirrorDatabase.kt
index 5988e545..df30d14f 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/MirrorDatabase.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/MirrorDatabase.kt
@@ -18,8 +18,15 @@ import kotlinx.serialization.json.jsonObject
/** All entity writes, send reconciliation and the event cursor commit together. */
class MirrorDatabase(context: Context, directory: File, computerId: String) :
- SQLiteOpenHelper(context, File(directory, "mirror-$computerId.db").absolutePath, null, 3) {
- init { require(computerId.matches(Regex("[A-Za-z0-9_-]{22}"))) }
+ SQLiteOpenHelper(context, file(directory, computerId).absolutePath, null, 3) {
+ companion object {
+ private fun file(directory: File, computerId: String): File {
+ require(computerId.matches(Regex("[A-Za-z0-9_-]{22}")))
+ return File(directory, "mirror-$computerId.db")
+ }
+ /** Deletes a computer's mirror with its journal files, once it's closed. */
+ fun delete(directory: File, computerId: String) { SQLiteDatabase.deleteDatabase(file(directory, computerId)) }
+ }
override fun onCreate(db: SQLiteDatabase) {
db.execSQL("CREATE TABLE meta(k TEXT PRIMARY KEY, v TEXT NOT NULL)")
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/NewBotView.kt b/apps/android/app/src/main/kotlin/com/codync/android/NewBotView.kt
index 70f88fd6..97642cad 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/NewBotView.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/NewBotView.kt
@@ -46,8 +46,8 @@ import com.codync.android.design.*
var draft by remember { mutableStateOf(BotDraft()) }
val online = state.actualConnection is LinkState.Ready
val dismiss = LocalDismissModal.current
- // A new bot starts on an installed agent we know; the host turns on every connector and skill.
- LaunchedEffect(state.hello) { draft = fillDefaults(draft, state) }
+ // A new bot starts on an installed agent we know (again on another computer); the host turns on every connector and skill.
+ LaunchedEffect(state.computer.id, state.hello) { draft = fillDefaults(draft, state) }
CreateLayout(state, "New bot", draft.name, { draft = draft.copy(name = it) }, "Name your bot", online, { store.saveBot(draft) { dismiss() } },
{ CharacterAvatar(draft.avatarShape, draft.avatarColor, 96.dp) }) {
AvatarPicker(draft.avatarShape, draft.avatarColor, { draft = draft.copy(avatarShape = it) }, { draft = draft.copy(avatarColor = it) })
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/NotificationIcons.kt b/apps/android/app/src/main/kotlin/com/codync/android/NotificationIcons.kt
index 98ae00ce..942a8749 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/NotificationIcons.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/NotificationIcons.kt
@@ -1,7 +1,11 @@
package com.codync.android
import android.content.Context
+import android.graphics.Bitmap
import com.codync.android.core.CustomIcon
+import com.codync.android.design.AvatarPalette
+import com.codync.android.design.characterAvatarBitmap
+import com.codync.android.design.customAvatarBitmap
/** A notification can use only its active account's paired-computer cache. No network or chat reads. */
internal fun notificationIcons(context: Context, scope: String, computer: String): Map<String, CustomIcon> {
@@ -17,3 +21,8 @@ internal fun notificationIcons(context: Context, scope: String, computer: String
emptyMap()
}
}
+
+/** A bot's face in a notification (a task's, a call's): its own image, else its character. */
+internal fun notificationFace(shape: String, color: String, icon: CustomIcon?): Bitmap =
+ customAvatarBitmap(icon?.dataUrl, icon?.tinted == true, 128, AvatarPalette.colors[color]?.toInt() ?: 0xFF1084FE.toInt())
+ ?: characterAvatarBitmap(shape, color, 128, 0xFF141414.toInt())
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/PlatformSpeech.kt b/apps/android/app/src/main/kotlin/com/codync/android/PlatformSpeech.kt
index 98ed7fba..e56b1546 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/PlatformSpeech.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/PlatformSpeech.kt
@@ -59,6 +59,18 @@ internal object PlatformSpeech {
fun name(tag: String): String = ULocale.forLanguageTag(tag).getDisplayName(ULocale.getDefault()).ifEmpty { tag }
}
+/** Android's recognizer asked for free-form speech in [language], the words as it hears them, on the phone where it can. */
+internal fun recognizerIntent(language: String): Intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
+ .putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
+ .putExtra(RecognizerIntent.EXTRA_LANGUAGE, language)
+ .putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
+ .putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, true)
+
+/** The recognizer's best guess in [results], Chinese in the reader's script. */
+internal fun recognizedText(results: Bundle?, language: String): String =
+ results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull().orEmpty()
+ .let { if (VoiceLanguages.base(Locale.forLanguageTag(language)) == "zh") inReadersScript(it) else it }
+
/**
* One utterance at a time through Android's on-device recognizer: the microphone's PCM is written to
* it, so the level meter and echo cancelling are the call's own. What it hears so far is reported as
@@ -75,11 +87,7 @@ internal class PlatformSpeechInput(private val context: Context, private val lan
val (read, write) = ParcelFileDescriptor.createPipe()
source = read
val output = ParcelFileDescriptor.AutoCloseOutputStream(write).also { sink = it }
- val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
- .putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
- .putExtra(RecognizerIntent.EXTRA_LANGUAGE, language)
- .putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
- .putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, true)
+ val intent = recognizerIntent(language)
.putExtra(RecognizerIntent.EXTRA_AUDIO_SOURCE, read)
.putExtra(RecognizerIntent.EXTRA_AUDIO_SOURCE_CHANNEL_COUNT, 1)
.putExtra(RecognizerIntent.EXTRA_AUDIO_SOURCE_ENCODING, AudioFormat.ENCODING_PCM_16BIT)
@@ -114,8 +122,7 @@ internal class PlatformSpeechInput(private val context: Context, private val lan
/** The stretches finished so far in this utterance. */
private var heard = ""
- private fun text(results: Bundle?) = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull().orEmpty()
- .let { if (VoiceLanguages.base(Locale.forLanguageTag(language)) == "zh") inReadersScript(it) else it }
+ private fun text(results: Bundle?) = recognizedText(results, language)
override fun onPartialResults(partial: Bundle?) {
events(VoiceInput.Text(generation, VoiceLanguages.join(heard, text(partial)), false))
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/PushService.kt b/apps/android/app/src/main/kotlin/com/codync/android/PushService.kt
index 50a87e29..f1436f12 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/PushService.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/PushService.kt
@@ -283,9 +283,7 @@ internal object NotificationDisplay {
.setProgressSegments(List(4) { Notification.ProgressStyle.Segment(25).setColor(tint) })
.setProgress(filled * 25)
val custom = notificationIcons(context, scope, computer)["bot:${watch.botId}"]
- val face = com.codync.android.design.customAvatarBitmap(custom?.dataUrl, custom?.tinted == true, 128,
- com.codync.android.design.AvatarPalette.colors[watch.avatarColor]?.toInt() ?: 0xFF1084FE.toInt())
- ?: com.codync.android.design.characterAvatarBitmap(watch.avatarShape, watch.avatarColor, 128, 0xFF141414.toInt())
+ val face = notificationFace(watch.avatarShape, watch.avatarColor, custom)
val open = builder(context, scope, computer, watch.botId, TASKS).build().contentIntent
val notification = Notification.Builder(context, TASKS).setSmallIcon(R.drawable.ic_notification).setContentTitle(watch.name).setContentText(text)
.setLargeIcon(android.graphics.drawable.Icon.createWithBitmap(face)).setContentIntent(open).setStyle(style)
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ReviewPrompt.kt b/apps/android/app/src/main/kotlin/com/codync/android/ReviewPrompt.kt
index 43831be5..2c749b15 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/ReviewPrompt.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ReviewPrompt.kt
@@ -7,10 +7,13 @@ import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.core.content.edit
import com.codync.android.core.Entry
+import com.codync.android.core.LinkState
import com.codync.android.core.ReviewCancellation
import com.codync.android.core.ReviewHistory
import com.codync.android.core.ReviewInvitation
@@ -57,18 +60,33 @@ internal object ReviewPrompt {
fun setActive(context: Context, active: Boolean) = update(context) { setActive(active, System.currentTimeMillis()) }
fun sent(context: Context, nonce: String) = update(context) { sent(nonce, System.currentTimeMillis()) }
fun viewed(context: Context, chat: String, entries: List<Entry>) = update(context) { viewed(chat, entries, System.currentTimeMillis()) }
- fun returned(context: Context, chat: String) = update(context) { returned(chat, BuildConfig.VERSION_NAME.substringBefore('-'), System.currentTimeMillis()) }
+ fun returned(context: Context, chat: String) = update(context) { returned(chat, APP_RELEASE, System.currentTimeMillis()) }
fun cancel(context: Context, reason: ReviewCancellation) = update(context) { cancel(reason) }
fun interrupt(context: Context, token: Any, active: Boolean) = update(context) { interrupt(token, active) }
/** Uses up the opportunity (and this app's own cooldown) before Google Play is asked. */
fun request(context: Context, token: Long): Boolean {
var asked = false
- update(context) { asked = request(token, BuildConfig.VERSION_NAME.substringBefore('-'), System.currentTimeMillis()) }
+ update(context) { asked = request(token, APP_RELEASE, System.currentTimeMillis()) }
return asked
}
}
+/** A computer steady enough to read an answer on or to invite a rating over: connected, current, nothing else showing. */
+internal val AppState.settledForReview: Boolean
+ get() = actualConnection is LinkState.Ready && mismatch == null && error == null && screenRequest == null
+
+/** Leaving [openChat] (the open chat's ID, null on the roster) may invite a rating; opening one turns a waiting invitation down. */
+@Composable internal fun ReviewOnReturn(openChat: String?) {
+ val context = LocalContext.current
+ var lastChat by remember { mutableStateOf<String?>(null) }
+ LaunchedEffect(openChat) {
+ if (openChat != null) ReviewPrompt.cancel(context, ReviewCancellation.Interaction)
+ else lastChat?.let { ReviewPrompt.returned(context, it) }
+ lastChat = openChat
+ }
+}
+
/** While [active] (the composer in use, files picked, dictation), reading a result doesn't count and no invitation shows. */
@Composable internal fun ReviewInterruption(active: Boolean) {
val context = LocalContext.current
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/RosterSectionOrder.kt b/apps/android/app/src/main/kotlin/com/codync/android/RosterSectionOrder.kt
index 895c8d93..4e6e9617 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/RosterSectionOrder.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/RosterSectionOrder.kt
@@ -1,6 +1,11 @@
package com.codync.android
import android.content.Context
+import androidx.compose.foundation.lazy.LazyItemScope
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.layout.onSizeChanged
+import androidx.compose.ui.zIndex
import androidx.core.content.edit
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
@@ -22,12 +27,11 @@ internal fun renamedSectionOrder(order: List<String>, from: String, to: String?)
internal object SectionOrders {
fun key(account: String, computer: String): String = "sectionOrder:$account:$computer"
- private fun prefs(context: Context) = context.getSharedPreferences("codync-roster", Context.MODE_PRIVATE)
fun load(context: Context, key: String): List<String> = try {
- Json.parseToJsonElement(prefs(context).getString(key, "[]") ?: "[]").jsonArray.map { it.jsonPrimitive.content }
+ Json.parseToJsonElement(rosterPrefs(context).getString(key, "[]") ?: "[]").jsonArray.map { it.jsonPrimitive.content }
} catch (_: IllegalArgumentException) { emptyList() } // A malformed local preference starts with the default order.
fun save(context: Context, key: String, names: List<String>) {
- prefs(context).edit { putString(key, JsonArray(names.map(::JsonPrimitive)).toString()) }
+ rosterPrefs(context).edit { putString(key, JsonArray(names.map(::JsonPrimitive)).toString()) }
}
}
@@ -74,3 +78,7 @@ internal class SectionReorder {
}, end = { finish(true) }, cancel = { finish(false) })
}
}
+
+/** A heading [reorder] drags by [name]: its height for the swaps, lifted above the rest while held, otherwise sliding into place. */
+internal fun LazyItemScope.reorderable(reorder: SectionReorder, name: String): Modifier = Modifier.onSizeChanged { reorder.heights[name] = it.height }
+ .then(if (reorder.dragged == name) Modifier.zIndex(1f).graphicsLayer { translationY = reorder.translation(name) } else Modifier.animateItem())
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/RosterSections.kt b/apps/android/app/src/main/kotlin/com/codync/android/RosterSections.kt
index 2059270d..990e8111 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/RosterSections.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/RosterSections.kt
@@ -109,10 +109,20 @@ internal fun withMoves(bots: List<Bot>, pending: List<SectionMove>): List<Bot> {
return bots.map { bot -> if (bot.id in sections) bot.copy(section = sections[bot.id]) else bot }
}
-/** The sections folded on this device (iOS `@AppStorage("collapsedRosterSections")`); not synced. */
+/** The roster's preferences: kept on this device, never synced. */
+internal fun rosterPrefs(context: Context) = context.getSharedPreferences("codync-roster", Context.MODE_PRIVATE)
+
+/** The sections folded on this device (iOS `@AppStorage("collapsedRosterSections")`). */
internal object FoldedSections {
private const val KEY = "collapsedRosterSections"
- private fun prefs(context: Context) = context.getSharedPreferences("codync-roster", Context.MODE_PRIVATE)
- fun load(context: Context): Set<String> = prefs(context).getStringSet(KEY, null).orEmpty().toSet()
- fun save(context: Context, names: Set<String>) { prefs(context).edit { putStringSet(KEY, names) } }
+ fun load(context: Context): Set<String> = rosterPrefs(context).getStringSet(KEY, null).orEmpty().toSet()
+ fun save(context: Context, names: Set<String>) { rosterPrefs(context).edit { putStringSet(KEY, names) } }
+}
+
+/** Computers left out of the roster (`ComputerSelection`'s list), and computers whose bots are folded away (iOS `@AppStorage`). */
+internal object RosterComputers {
+ fun hidden(context: Context): String = rosterPrefs(context).getString("hiddenComputers", "").orEmpty()
+ fun setHidden(context: Context, value: String) = rosterPrefs(context).edit { putString("hiddenComputers", value) }
+ fun folded(context: Context): Set<String> = rosterPrefs(context).getStringSet("foldedComputers", null).orEmpty().toSet()
+ fun setFolded(context: Context, ids: Set<String>) = rosterPrefs(context).edit { putStringSet("foldedComputers", ids) }
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ScreenSession.kt b/apps/android/app/src/main/kotlin/com/codync/android/ScreenSession.kt
index e3368e2a..7ea76e98 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/ScreenSession.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ScreenSession.kt
@@ -73,7 +73,7 @@ class ScreenSession(private val store: AppStore, display: ScreenDisplay?) {
private set
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
- private val context: Context = store.getApplication<android.app.Application>()
+ private val context: Context = store.application
private var session: String? = null
private var pc: PeerConnection? = null
private var track: VideoTrack? = null
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/VoiceService.kt b/apps/android/app/src/main/kotlin/com/codync/android/VoiceService.kt
index 58a200da..7aa81905 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/VoiceService.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/VoiceService.kt
@@ -9,7 +9,9 @@ import android.media.*
import android.net.Uri
import android.os.*
import androidx.core.app.NotificationCompat
+import androidx.core.app.Person
import androidx.core.content.ContextCompat
+import androidx.core.graphics.drawable.IconCompat
import com.codync.android.core.*
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.collectLatest
@@ -131,13 +133,9 @@ class VoiceService : Service() {
.setAction(kind).putExtra(ID, callId), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
// An ongoing call, as Android draws one (iOS: the call's Live Activity): the bot's face and name, the call's length
// counting up, hang up and mute here, and the status bar's call chip while it lasts.
- val face = bot?.let {
- com.codync.android.design.customAvatarBitmap(it.customIcon?.dataUrl, it.customIcon?.tinted == true, 128,
- com.codync.android.design.AvatarPalette.colors[it.avatarColor]?.toInt() ?: 0xFF1084FE.toInt())
- ?: com.codync.android.design.characterAvatarBitmap(it.avatarShape, it.avatarColor, 128, 0xFF141414.toInt())
- }
- val caller = androidx.core.app.Person.Builder().setName(bot?.name ?: "Codync").setImportant(true)
- .apply { face?.let { setIcon(androidx.core.graphics.drawable.IconCompat.createWithBitmap(it)) } }.build()
+ val face = bot?.let { notificationFace(it.avatarShape, it.avatarColor, it.customIcon) }
+ val caller = Person.Builder().setName(bot?.name ?: "Codync").setImportant(true)
+ .apply { face?.let { setIcon(IconCompat.createWithBitmap(it)) } }.build()
return NotificationCompat.Builder(this, CHANNEL).setSmallIcon(R.drawable.ic_notification)
.setContentTitle(bot?.name ?: "Codync")
.setContentText(callNotificationText(state, progress))
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/WidgetRefreshWorker.kt b/apps/android/app/src/main/kotlin/com/codync/android/WidgetRefreshWorker.kt
index 06f61682..ebac5f25 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/WidgetRefreshWorker.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/WidgetRefreshWorker.kt
@@ -37,11 +37,17 @@ class WidgetRefreshWorker(context: Context, parameters: WorkerParameters) : Coro
val local = LocalStore(context, owner.context)
val computers = withContext(Dispatchers.IO) { local.computers() }
if (computers.isEmpty()) return@withTimeout false
- val usageId = withContext(Dispatchers.IO) { local.lastComputer() }?.takeIf { id -> computers.any { it.id == id } } ?: computers.first().id
+ val usageId = computers.currentId(withContext(Dispatchers.IO) { local.lastComputer() })
val identity = withContext(Dispatchers.IO) { local.identity() }
// Each computer at once; one that can't be reached keeps the bots it had (and isn't fresh).
val reads = coroutineScope {
- computers.map { computer -> async { runCatching { read(computer, identity, computer.id == usageId) }.getOrNull() } }.awaitAll()
+ computers.map { computer ->
+ async {
+ try { read(computer, identity, computer.id == usageId) }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (error: Exception) { android.util.Log.i("Codync", "Widget refresh couldn't read ${computer.id}: ${error.message}"); null }
+ }
+ }.awaitAll()
}
val previous = withContext(Dispatchers.IO) { WidgetStore.feed(context) }
val bots = computers.zip(reads).map { (computer, read) ->
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/WidgetStore.kt b/apps/android/app/src/main/kotlin/com/codync/android/WidgetStore.kt
index e4b9d130..0a3709d5 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/WidgetStore.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/WidgetStore.kt
@@ -51,11 +51,8 @@ internal object WidgetStore {
val file = feedFile(context, expected)
val stored = read<WidgetFeed>(file) ?: WidgetFeed(scope = expected.scope)
val previous = stored.takeIf { it.computerId == usageComputer?.id } ?: WidgetFeed(scope = expected.scope, bots = stored.bots, botsAt = stored.botsAt)
- val kept = stored.bots.filter { bot -> computers.any { it.bots == null && it.computer.id == bot.computerId } }
- val bots = (widgetBots(computers.mapNotNull { c -> c.bots?.let { c.computer.id to it } }.toMap()) + kept)
- .sortedBy { widgetRank(it.status) }.take(256)
- val next = WidgetFeed(expected.scope, usageComputer?.id, usageComputer?.name.orEmpty().take(256), bots,
- if (computers.isNotEmpty() && computers.all { it.fresh }) now else previous.botsAt, usage, if (freshUsage) now else
+ val shown = stored.readingBots(computers.map { it.computer.id to it.bots }, computers.all { it.fresh }, now)
+ val next = WidgetFeed(expected.scope, usageComputer?.id, usageComputer?.name.orEmpty().take(256), shown.bots, shown.botsAt, usage, if (freshUsage) now else
if (usage != previous.usage) usage.providers.mapNotNull { it.updatedAt?.takeIf { time -> time > 0 } }.minOrNull() ?: 0
else previous.usageAt)
if (previous == next) return true
diff --git a/apps/android/app/src/test/kotlin/com/codync/android/ConnectionPresentationTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/ConnectionPresentationTest.kt
index 6e0e91f5..ce4cd4ea 100644
--- a/apps/android/app/src/test/kotlin/com/codync/android/ConnectionPresentationTest.kt
+++ b/apps/android/app/src/test/kotlin/com/codync/android/ConnectionPresentationTest.kt
@@ -67,15 +67,15 @@ class ConnectionPresentationTest {
}
@Test fun theHeaderSummarizesTheComputers() {
- assertEquals("1 connected", connectionSummary(listOf(state(LinkState.Ready(HostRoute.Direct)))))
- assertEquals("Connecting…", connectionSummary(listOf(state(LinkState.Connecting))))
- assertEquals("No access", connectionSummary(listOf(state(LinkState.Failed("Revoked", 403)))))
- assertEquals("1 offline", connectionSummary(listOf(state(LinkState.ComputerOffline(null)))))
- assertEquals("Computers", connectionSummary(emptyList()))
+ assertEquals("1 connected", connectionSummary(listOf(state(LinkState.Ready(HostRoute.Direct)))).filled())
+ assertEquals("Connecting…", connectionSummary(listOf(state(LinkState.Connecting))).filled())
+ assertEquals("No access", connectionSummary(listOf(state(LinkState.Failed("Revoked", 403)))).filled())
+ assertEquals("1 offline", connectionSummary(listOf(state(LinkState.ComputerOffline(null)))).filled())
+ assertEquals("Computers", connectionSummary(emptyList()).filled())
val laptop = Computer("laptop", "Laptop", "laptop")
- assertEquals("2 connected", connectionSummary(listOf(state(LinkState.Ready(HostRoute.Direct)), state(LinkState.Ready(HostRoute.Relay), laptop))))
- assertEquals("1/2 connected", connectionSummary(listOf(state(LinkState.Ready(HostRoute.Direct)), state(LinkState.ComputerOffline(null), laptop))))
- assertEquals("2 offline", connectionSummary(listOf(state(LinkState.Failed("Revoked", 403)), state(LinkState.ComputerOffline(null), laptop))))
+ assertEquals("2 connected", connectionSummary(listOf(state(LinkState.Ready(HostRoute.Direct)), state(LinkState.Ready(HostRoute.Relay), laptop))).filled())
+ assertEquals("1/2 connected", connectionSummary(listOf(state(LinkState.Ready(HostRoute.Direct)), state(LinkState.ComputerOffline(null), laptop))).filled())
+ assertEquals("2 offline", connectionSummary(listOf(state(LinkState.Failed("Revoked", 403)), state(LinkState.ComputerOffline(null), laptop))).filled())
}
@Test fun aComputerTurningThisPhoneAwayOrReplacedByANewIdentityIsStale() {
diff --git a/apps/android/app/src/test/kotlin/com/codync/android/DictationTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/DictationTest.kt
new file mode 100644
index 00000000..827204ae
--- /dev/null
+++ b/apps/android/app/src/test/kotlin/com/codync/android/DictationTest.kt
@@ -0,0 +1,156 @@
+package com.codync.android
+
+import android.content.ContextWrapper
+import com.codync.android.core.DictationText
+import com.codync.android.core.MicSource
+import com.codync.android.core.VoiceProvider
+import java.io.IOException
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.cancel
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.yield
+import org.junit.Assert.*
+import org.junit.Test
+
+/** Dictation through a provider (iOS `DictationTests`): the computer's answers and the microphone are the test's. */
+class DictationTest {
+ /** The phone's microphone, hearing what the test plays it. */
+ private class Mic : MicSource {
+ var heard: ((ByteArray, Float) -> Unit)? = null
+ var stopped = false
+ override suspend fun start(frames: (ByteArray, Float) -> Unit, failed: () -> Unit) { heard = frames }
+ override suspend fun stop() { stopped = true }
+ }
+
+ /** A call to the computer that waits for the test's answer. */
+ private class Pending<T> {
+ val answer = CompletableDeferred<T>()
+ var calls = 0; private set
+ suspend fun call(): T { calls++; return answer.await() }
+ }
+
+ /** Dictation with OpenAI picked, on a scope the test cancels when it's done. */
+ private fun dictating(key: Pending<Boolean>? = null, transcript: Pending<String> = Pending(), mic: Mic = Mic(),
+ body: suspend (Dictation, DictationService, CoroutineScope) -> Unit) = runBlocking {
+ val scope = CoroutineScope(coroutineContext + Job(coroutineContext[Job]))
+ val service = DictationService(VoiceProvider.OpenAI, { key?.call() ?: true }, { mic }, { _, _ -> transcript.call() })
+ try { body(Dictation(object : ContextWrapper(null) {}, scope, clock = { 0L }), service, scope) } finally { scope.cancel() }
+ }
+
+ private suspend fun until(check: () -> Boolean): Boolean {
+ repeat(1_000) { if (check()) return true; yield() }
+ return check()
+ }
+
+ /** Records [bytes] of what [mic] hears and taps the pill's stop; the transcript changes the box through [edit]. */
+ private suspend fun Dictation.dictate(bytes: Int, mic: Mic, service: DictationService, edit: ((String) -> String) -> Unit) {
+ start("", service, edit)
+ assertTrue(until { listening })
+ mic.heard?.invoke(ByteArray(bytes), 0.5f)
+ assertTrue(until { level > 0 })
+ finish()
+ }
+
+ @Test fun `a recording is transcribed after what the box holds then`() {
+ val transcript = Pending<String>(); val mic = Mic()
+ dictating(transcript = transcript, mic = mic) { dictation, service, _ ->
+ var box = "Fix the bug"
+ dictation.dictate(DictationText.MIN_BYTES, mic, service) { box = it(box) }
+ assertTrue(dictation.transcribing && !dictation.listening && mic.stopped)
+ assertTrue(until { transcript.calls == 1 })
+ box += " now"
+ transcript.answer.complete("in the parser")
+ assertTrue(until { !dictation.transcribing })
+ assertEquals("Fix the bug now in the parser", box)
+ assertNull(dictation.failure)
+ }
+ }
+
+ @Test fun `a transcript arriving after a stop is dropped`() {
+ val transcript = Pending<String>(); val mic = Mic()
+ dictating(transcript = transcript, mic = mic) { dictation, service, _ ->
+ var box = "Fix the bug"
+ dictation.dictate(DictationText.MIN_BYTES, mic, service) { box = it(box) }
+ assertTrue(until { transcript.calls == 1 })
+ dictation.stop()
+ assertFalse(dictation.transcribing)
+ transcript.answer.complete("too late")
+ repeat(10) { yield() }
+ assertEquals("Fix the bug", box)
+ assertTrue(dictation.failure == null && !dictation.transcribing)
+ }
+ }
+
+ @Test fun `a failed transcription says why`() {
+ val transcript = Pending<String>(); val mic = Mic()
+ dictating(transcript = transcript, mic = mic) { dictation, service, _ ->
+ var box = "Fix the bug"
+ dictation.dictate(DictationText.MIN_BYTES, mic, service) { box = it(box) }
+ assertTrue(until { transcript.calls == 1 })
+ transcript.answer.completeExceptionally(IOException("The computer is offline."))
+ assertTrue(until { !dictation.transcribing })
+ assertEquals("The computer is offline.", dictation.failure)
+ assertEquals("Fix the bug", box)
+ }
+ }
+
+ @Test fun `a tap of the mic sends nothing`() {
+ val transcript = Pending<String>(); val mic = Mic()
+ dictating(transcript = transcript, mic = mic) { dictation, service, _ ->
+ dictation.dictate(DictationText.MIN_BYTES - 1, mic, service) { }
+ repeat(10) { yield() }
+ assertFalse(dictation.transcribing)
+ assertEquals(0, transcript.calls)
+ }
+ }
+
+ @Test fun `without the key it asks for settings and never opens the microphone`() {
+ val key = Pending<Boolean>(); val mic = Mic()
+ dictating(key = key, mic = mic) { dictation, service, _ ->
+ dictation.start("", service) { }
+ assertTrue(until { key.calls == 1 })
+ key.answer.complete(false)
+ assertTrue(until { dictation.needsKey })
+ assertTrue(dictation.failure == null && !dictation.listening && mic.heard == null)
+ }
+ }
+
+ @Test fun `an unreachable computer says why`() {
+ val key = Pending<Boolean>(); val mic = Mic()
+ dictating(key = key, mic = mic) { dictation, service, _ ->
+ dictation.start("", service) { }
+ assertTrue(until { key.calls == 1 })
+ key.answer.completeExceptionally(IOException("The computer is offline."))
+ assertTrue(until { dictation.failure != null })
+ assertEquals("The computer is offline.", dictation.failure)
+ assertTrue(!dictation.listening && mic.heard == null)
+ }
+ }
+
+ @Test fun `a stop while the key is checked wins`() {
+ for (answers in listOf(true, false)) {
+ val key = Pending<Boolean>(); val mic = Mic()
+ dictating(key = key, mic = mic) { dictation, service, _ ->
+ dictation.start("", service) { }
+ assertTrue(until { key.calls == 1 })
+ dictation.stop()
+ if (answers) key.answer.complete(true) else key.answer.completeExceptionally(IOException("Offline"))
+ repeat(10) { yield() }
+ assertTrue(!dictation.listening && mic.heard == null && dictation.failure == null)
+ }
+ }
+ }
+
+ @Test fun `the microphone stops with the box even after the box's scope is gone`() {
+ val mic = Mic()
+ dictating(mic = mic) { dictation, service, scope ->
+ dictation.start("", service) { }
+ assertTrue(until { dictation.listening })
+ scope.cancel()
+ dictation.stop()
+ assertTrue(mic.stopped)
+ }
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Computer.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Computer.kt
index 64e89a4e..8c6d330f 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Computer.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Computer.kt
@@ -29,6 +29,9 @@ data class Computer(
}
}
+/** The computer Usage follows, in the app and its widget: the last active one while it's still here, else the first. */
+fun Iterable<Computer>.currentId(last: String?): String? = last?.takeIf { id -> any { it.id == id } } ?: firstOrNull()?.id
+
@Serializable
enum class ConnectionRoute { Automatic, CloudflareFirst, DirectOnly }
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/ComputerSelection.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/ComputerSelection.kt
new file mode 100644
index 00000000..4cd31d94
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/ComputerSelection.kt
@@ -0,0 +1,23 @@
+package com.codync.android.core
+
+/**
+ * The computers the roster shows, from the ones left out ([hidden], comma-separated, kept on the device): an empty list
+ * means all of them, newly paired ones included, and at least one always shows (iOS `ComputerSelection`).
+ */
+class ComputerSelection(val all: List<String>, hidden: String) {
+ private val hidden = hidden.split(',').filter(String::isNotEmpty).toSet()
+
+ val shown: List<String> get() = all.filter { it !in hidden }.ifEmpty { all }
+
+ /** [id] shown or left out, keeping one shown. */
+ fun toggling(id: String): String {
+ if (id !in all) return encoded(all.toSet() - shown.toSet())
+ val visible = shown.toMutableSet()
+ if (id in visible) { if (visible.size > 1) visible.remove(id) } else visible.add(id)
+ return encoded(all.toSet() - visible)
+ }
+
+ fun only(id: String): String = if (id !in all) "" else encoded(all.toSet() - id)
+
+ private fun encoded(ids: Set<String>): String = ids.sorted().joinToString(",")
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Management.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Management.kt
index a7c4ca4f..d4023b73 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Management.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Management.kt
@@ -1,6 +1,5 @@
package com.codync.android.core
-import kotlinx.serialization.Serializable
import kotlinx.serialization.json.*
/** A group uses the existing bot endpoints; it never owns an agent or workspace. */
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/WidgetFeed.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/WidgetFeed.kt
index c7f1dbba..7e9afd51 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/WidgetFeed.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/WidgetFeed.kt
@@ -31,9 +31,12 @@ fun usageLimits(report: UsageReport): List<ProviderLimit> {
/** The Bots tile's bot: the one that needs you most, in the feed's order, if any bot is at work. */
fun mostUrgentBot(bots: List<WidgetBot>): WidgetBot? = bots.firstOrNull { it.status == "needsInput" || it.status == "working" }
-/** The Team widget's four spots: the picked bots first (a deleted pick falls back), then the feed's order (who needs you). */
+/**
+ * The Team widget's four spots: the picked bots first (a deleted pick falls back), then the feed's order (who needs you).
+ * A pick saved before several computers is a bare bot ID: the first bot with that ID.
+ */
fun teamSlots(bots: List<WidgetBot>, picks: List<String?>): List<WidgetBot?> {
- val picked = List(4) { i -> picks.getOrNull(i)?.let { key -> bots.firstOrNull { it.key == key } } }
+ val picked = List(4) { i -> picks.getOrNull(i)?.let { key -> bots.firstOrNull { it.key == key } ?: bots.firstOrNull { '/' !in key && it.id == key } } }
val queue = ArrayDeque(bots.filter { bot -> picked.none { it?.key == bot.key } })
return picked.map { it ?: queue.removeFirstOrNull() }
}
@@ -47,3 +50,13 @@ fun widgetBots(bots: Map<String, List<Bot>>): List<WidgetBot> = bots.flatMap { (
.sortedWith(compareBy<Pair<String, Bot>> { (_, bot) -> widgetRank(bot.status) }
.thenByDescending { it.second.pinned }.thenByDescending { it.second.lastAt }.thenBy { it.second.name })
.take(256).map { (computer, it) -> WidgetBot(it.id, it.name.take(256), it.status, it.unread, it.avatarColor, it.avatarShape, it.customIcon, computer) }
+
+/**
+ * The feed after reading [computers] (each one's ID and bots; null when it couldn't be read, so the bots it showed stay),
+ * who needs you first. A computer no longer listed takes its bots along; [botsAt] moves to [now] only when every one was [fresh].
+ */
+fun WidgetFeed.readingBots(computers: List<Pair<String, List<Bot>?>>, fresh: Boolean, now: Long): WidgetFeed {
+ val kept = bots.filter { bot -> computers.any { (id, read) -> read == null && id == bot.computerId } }
+ val read = widgetBots(computers.mapNotNull { (id, read) -> read?.let { id to it } }.toMap())
+ return copy(bots = (read + kept).sortedBy { widgetRank(it.status) }.take(256), botsAt = if (computers.isNotEmpty() && fresh) now else botsAt)
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/ComputerSelectionTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/ComputerSelectionTest.kt
new file mode 100644
index 00000000..b186cbe4
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/ComputerSelectionTest.kt
@@ -0,0 +1,29 @@
+package com.codync.android.core
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class ComputerSelectionTest {
+ @Test fun `the filter shows several computers or only one`() {
+ val all = listOf("a", "b", "c")
+ val initial = ComputerSelection(all, "")
+ assertEquals(all, initial.shown)
+ val withoutB = ComputerSelection(all, initial.toggling("b"))
+ assertEquals(listOf("a", "c"), withoutB.shown)
+ val onlyC = ComputerSelection(all, withoutB.only("c"))
+ assertEquals(listOf("c"), onlyC.shown)
+ assertEquals(listOf("a", "c"), ComputerSelection(all, onlyC.toggling("a")).shown)
+ }
+
+ @Test fun `one computer always shows, removed ones don't hide the rest, and newly paired ones show`() {
+ val single = ComputerSelection(listOf("a", "b"), "b")
+ assertEquals(listOf("a"), ComputerSelection(single.all, single.toggling("a")).shown)
+ val removed = ComputerSelection(listOf("b", "c"), "b,c")
+ assertEquals(listOf("b", "c"), removed.shown)
+ assertEquals(listOf("c"), ComputerSelection(removed.all, removed.toggling("b")).shown)
+ assertEquals(listOf("a", "new"), ComputerSelection(listOf("a", "b", "new"), "b").shown)
+ assertTrue(ComputerSelection(emptyList(), "a").shown.isEmpty())
+ assertEquals("", ComputerSelection(listOf("a"), "a").only("gone"))
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/ReviewTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/ReviewTest.kt
index 98714f7b..0bd5b73e 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/ReviewTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/ReviewTest.kt
@@ -11,6 +11,19 @@ class ReviewTest {
private fun user(nonce: String, turn: Long) = Entry("u$turn", turn, "b", turn, "user", turn,
buildJsonObject { put("text", "do it"); put("clientNonce", nonce); put("status", "sent") })
private fun answer(turn: Long) = Entry("a$turn", turn, "b", turn, "agent", turn, buildJsonObject { put("text", "done"); put("final", true) })
+ /** A message from this phone that isn't the person asking: a call's, a routine's or another bot's. */
+ private fun relayed(nonce: String, field: String) = Entry("r1", 1, "b", 1, "user", 1,
+ buildJsonObject { put("text", "do it"); put("clientNonce", nonce); put("status", "sent"); put(field, "x") })
+
+ /** An invitation with an opportunity waiting, made on day 10 as the person came back from "chat". */
+ private fun waiting(events: MutableList<ReviewInvitation.Event>): Pair<ReviewInvitation, Long> {
+ val invitation = ReviewInvitation(ReviewHistory(firstUse = 0, completed = 4, activeDays = setOf("a", "b", "c")), {}) { events += it }
+ invitation.setActive(true, 10 * day)
+ invitation.sent("n1", 10 * day)
+ invitation.viewed("chat", listOf(user("n1", 1), answer(1)), 10 * day + 1_000)
+ invitation.returned("chat", "2.34.0", 10 * day + 120_000)
+ return invitation to requireNotNull(invitation.opportunity)
+ }
@Test fun `only a final answer to this phone's own message finishes it`() {
val sent = mapOf("n1" to 0L)
@@ -57,6 +70,59 @@ class ReviewTest {
assertEquals(setOf("2.34.0"), history.requestedVersions)
}
+ @Test fun `twice in a rolling year at most`() {
+ val history = ReviewHistory(firstUse = 0, completed = 15, activeDays = setOf("a", "b", "c"),
+ requests = listOf(ReviewHistory.Request(0, "2.30.0", 5), ReviewHistory.Request(130 * day, "2.31.0", 10)),
+ requestedVersions = setOf("2.30.0", "2.31.0"))
+ assertFalse(history.eligible(260 * day, "2.32.0"))
+ assertTrue(history.eligible(366 * day, "2.32.0"))
+ }
+
+ @Test fun `leaving the app, a touch or something in use turns the opportunity down`() {
+ val events = mutableListOf<ReviewInvitation.Event>()
+ val (left, _) = waiting(events)
+ left.setActive(false, 10 * day + 121_000)
+ assertNull(left.opportunity)
+ val (touched, _) = waiting(events)
+ touched.cancel(ReviewCancellation.Interaction)
+ val (busy, token) = waiting(events)
+ busy.interrupt(Any(), true)
+ assertFalse(busy.request(token, "2.34.0", 10 * day + 122_000))
+ assertEquals(listOf(ReviewCancellation.Background, ReviewCancellation.Interaction, ReviewCancellation.Unavailable),
+ events.filterIsInstance<ReviewInvitation.Event.Cancelled>().map { it.reason })
+ // An answer read while something is in use doesn't count.
+ busy.sent("n2", 10 * day + 130_000)
+ busy.viewed("chat", listOf(user("n2", 2), answer(2)), 10 * day + 131_000)
+ assertEquals(5, busy.history.completed)
+ }
+
+ @Test fun `a call's, a routine's or another bot's turn never counts`() {
+ val sent = mapOf("n1" to 0L)
+ for (field in listOf("call", "routineId", "from")) assertNull(field, ReviewCompletion.match(listOf(relayed("n1", field), answer(1)), sent, day))
+ }
+
+ @Test fun `sent messages are forgotten after a month and kept to a hundred`() {
+ var history = ReviewHistory(firstUse = 0, sent = mapOf("old" to 0L, "recent" to 20 * day))
+ val invitation = ReviewInvitation(history, { history = it }) { }
+ invitation.setActive(true, 31 * day)
+ assertEquals(setOf("recent"), history.sent.keys)
+ for (i in 0 until 100) invitation.sent("n$i", 31 * day + i)
+ assertEquals(100, history.sent.size)
+ assertFalse("recent" in history.sent)
+ }
+
+ @Test fun `a turn with several messages counts once`() {
+ var history = ReviewHistory(firstUse = 0)
+ val invitation = ReviewInvitation(history, { history = it }) { }
+ invitation.setActive(true, day)
+ invitation.sent("n1", day)
+ invitation.sent("n2", day + 1)
+ val second = Entry("u1b", 2, "b", 2, "user", 1, buildJsonObject { put("text", "also"); put("clientNonce", "n2"); put("status", "sent") })
+ invitation.viewed("chat", listOf(user("n1", 1), second, answer(1)), day + 1_000)
+ assertEquals(1, history.completed)
+ assertTrue(history.sent.isEmpty())
+ }
+
@Test fun `play version codes read back as versions and a newer one is reminded until dismissed`() {
assertEquals("2.34.0", UpdateReminder.versionOf(2_034_000))
assertEquals("2.34.12", UpdateReminder.versionOf(2_034_012))
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/WidgetFeedTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/WidgetFeedTest.kt
index 72ca49ca..3bc776e8 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/WidgetFeedTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/WidgetFeedTest.kt
@@ -17,6 +17,18 @@ class WidgetFeedTest {
assertEquals(listOf("linux/a", "mac/b", "mac/a"), bots.map { it.key })
// The same bot ID on two computers stays two spots.
assertEquals(listOf("mac/a", "linux/a", "mac/b", null), teamSlots(bots, listOf("mac/a", null, null, null)).map { it?.key })
+ // A pick saved before several computers (a bare bot ID) still holds its spot.
+ assertEquals(listOf("mac/b", "linux/a", "mac/a", null), teamSlots(bots, listOf("b", null, null, null)).map { it?.key })
+ }
+
+ @Test fun `an unreachable computer keeps the bots it showed and a forgotten one takes its bots along`() {
+ val shown = WidgetFeed(bots = listOf(WidgetBot("a", "Old", "idle", computerId = "mac"), WidgetBot("b", "Gone", "idle", computerId = "old"),
+ WidgetBot("c", "Stale", "idle", computerId = "linux")), botsAt = 5)
+ val next = shown.readingBots(listOf("mac" to null, "linux" to listOf(Bot("d", "New", status = "working"))), fresh = false, now = 9)
+ assertEquals(listOf("linux/d", "mac/a"), next.bots.map { it.key })
+ assertEquals(5L, next.botsAt)
+ assertEquals(9L, shown.readingBots(listOf("linux" to emptyList()), fresh = true, now = 9).botsAt)
+ assertTrue(shown.readingBots(emptyList(), fresh = true, now = 9).let { it.bots.isEmpty() && it.botsAt == 5L })
}
@Test fun `team spots keep picks, skip deleted ones and fill the rest in feed order`() {
diff --git a/docs/architecture/overview.md b/docs/architecture/overview.md
index 03961ba6..6e008d47 100644
--- a/docs/architecture/overview.md
+++ b/docs/architecture/overview.md
@@ -71,7 +71,7 @@ When a client needs data or behavior the host doesn't offer, add a host method o
- Account changes retire the old stores; late responses must not update the new context. Signing out erases that context's local credentials and caches.
- The desktop app (`apps/desktop/`) has its own TypeScript `BotStore` and attaches its local host and configured SSH hosts through loopback only ([desktop app](desktop-app.md)). iPhone connections use device identities.
-The product currently prioritizes one computer. Existing account-scoped aggregation and SSH support remain; their presence is not a reason to add multi-computer features without a product requirement. What the iPhone already does with several computers, the Android app does too (pairing several, a heading per computer, Computer management for each).
+Several computers per account are supported: the iPhone and Android apps pair several, with a heading per computer in the roster, Computer management for each, and each computer's push, usage and widgets; the desktop app attaches its local host and configured SSH hosts. Account-scoped aggregation and SSH build on the same structure (`AccountStore`, `BotReference`).
## Service boundaries
diff --git a/docs/design/push-and-live-activity.md b/docs/design/push-and-live-activity.md
index 4749fb10..1333b951 100644
--- a/docs/design/push-and-live-activity.md
+++ b/docs/design/push-and-live-activity.md
@@ -19,7 +19,7 @@ The encrypted title is limited to 80 characters and the body to 400 characters.
Notification actions open the scoped conversation. Permission approval still requires the normal in-app permission card. An account mismatch does not navigate into another account. Notifications are grouped by computer plus bot. Muted and hidden bots do not alert. The existing host-wide suppression while an iOS event connection is open remains in place; independent foreground suppression for multiple phones is not implemented.
-Each computer's card in Computer management has a Push notifications switch: off saves it with that computer on this phone and calls `unregisterDevice` on that computer only, so it drops its alert ticket while the others keep theirs (Live Activities are unaffected; Android pairs one computer, so its switch stays a phone preference). Settings → Notifications requests access or opens the system notification settings. Per-bot notification preferences remain in the bot editor. State → Live Activity controls automatic activity creation and shows system authorization. Turning it off ends this phone's activities. State → Dynamic Island shows the same switch: iOS renders one activity in both places and offers no island-only opt-out. Under the bot's row (above Review when the bot needs you), the Lock Screen card shows a progress line, four segments in the state's color that fill as the task moves (one while sending or queued, two while working, three when the bot needs you, four once it ends), the same line as Android's Live update. The expanded island centers the bot name and current step under the camera, between the avatar and the orb (both vertically centered), so no text reaches the island's 44 pt corners. Its bottom row shows the elapsed time (from `startedAt`, counted by the system) or, when the bot needs you, a Review button that opens the conversation.
+Each computer's card in Computer management has a Push notifications switch: off saves it with that computer on this phone and calls `unregisterDevice` on that computer only, so it drops its alert ticket while the others keep theirs (Live Activities are unaffected; Android saves the switch with each computer the same way). Settings → Notifications requests access or opens the system notification settings. Per-bot notification preferences remain in the bot editor. State → Live Activity controls automatic activity creation and shows system authorization. Turning it off ends this phone's activities. State → Dynamic Island shows the same switch: iOS renders one activity in both places and offers no island-only opt-out. Under the bot's row (above Review when the bot needs you), the Lock Screen card shows a progress line, four segments in the state's color that fill as the task moves (one while sending or queued, two while working, three when the bot needs you, four once it ends), the same line as Android's Live update. The expanded island centers the bot name and current step under the camera, between the avatar and the orb (both vertically centered), so no text reaches the island's 44 pt corners. Its bottom row shows the elapsed time (from `startedAt`, counted by the system) or, when the bot needs you, a Review button that opens the conversation.
## Responsibilities and privacy
diff --git a/docs/features/voice-call.md b/docs/features/voice-call.md
index 24ba0e59..b514f1c6 100644
--- a/docs/features/voice-call.md
+++ b/docs/features/voice-call.md
@@ -88,7 +88,12 @@ on-device (its window doesn't reach the host).
`Thread/DictationEngineMenu.swift`, dots shared with the call bar in `LevelDots.swift`):
`SFSpeechRecognizer` on device; with no microphone route (some simulators) the mic does nothing.
A provider's errors (no key, no connection) show in a dialog.
-- Android has no composer mic yet.
+- Android (`Dictation.kt`, pill and engine menu in `DictationControls.kt`, dots shared with the call
+ bar): Android's on-device recognizer (Android 12+) in the call's language. Where the phone has none,
+ or it lacks the language, the phone's own recognizer listens instead, and that one may send the
+ audio to its provider (Google on most phones). A provider records through `AndroidMic`; the key
+ check, microphone and transcription sit behind `DictationService`, so `DictationTest` runs on the JVM.
+ A missing key opens Voice chat settings, with a card for a dictation-only provider.
- The terminal UI has no microphone, so no mic.
### Voice input shortcut
@@ -439,4 +444,4 @@ voice).
### Missing dictation keys
-Desktop and iPhone dictation open Voice chat settings when the selected provider has no key, before opening the microphone. Connection failures still show an error. Keys can be edited through local or SSH-loopback connections; paired remote connections show instructions to add the key on that computer. Windows and Linux hide On device in both engine pickers; old dictation preferences use OpenAI, while calls keep their configured-provider fallback. macOS keeps its on-device option. Android has voice calls but no composer dictation engine picker; the terminal UI has no microphone input, so this dictation change does not apply to either.
+Desktop and iPhone dictation open Voice chat settings when the selected provider has no key, before opening the microphone. Connection failures still show an error. Keys can be edited through local or SSH-loopback connections; paired remote connections show instructions to add the key on that computer. Windows and Linux hide On device in both engine pickers; old dictation preferences use OpenAI, while calls keep their configured-provider fallback. macOS keeps its on-device option. Android does the same and always offers On device. The terminal UI has no microphone input, so this dictation change does not apply to it.
diff --git a/docs/guides/linux-servers.md b/docs/guides/linux-servers.md
index 025057e6..7a0213c4 100644
--- a/docs/guides/linux-servers.md
+++ b/docs/guides/linux-servers.md
@@ -46,7 +46,7 @@ The host listens on `0.0.0.0:19222`. The local API (`/api/*`, `/events`, termina
- **Remote screen and the `computer` tool don't work.** They need a desktop session (portals + GStreamer, `apps/screen-linux/`). The feature turns itself on only while a graphical session is running, so on a server it stays off and nothing else is affected.
- **No desktop app.** The Linux desktop app (`codync`, AppImage/deb/tar.gz) needs a graphical session; it uses the installed `codync-host`. On a server, use the phone, the desktop app on another computer over SSH, or `codync-host tui`.
- **Keep-awake is a no-op.** The host tries `systemd-inhibit` while a bot works; VMs don't sleep, and failure only logs a warning.
-- **One computer per account.** A VM counts as the account's computer; multiple computers are future work.
+- **One of the account's computers.** A VM pairs like any other computer; the phones show it beside the rest, under its own heading.
- **Usage limits** come from the local Claude and Codex installs, same as on a desktop.
## Verification — 2026-09-26
diff --git a/docs/guides/user-docs.md b/docs/guides/user-docs.md
index 2a40ff75..29fa0386 100644
--- a/docs/guides/user-docs.md
+++ b/docs/guides/user-docs.md
@@ -43,7 +43,7 @@ the change.
unless the reader types them (a CLI command, an environment variable).
- Where the apps differ, say how in each, briefly: **iPhone**, **Desktop**, **Terminal UI**.
- Describe the current release only. Leave out the Android app until it's public, Codync 1.x, products the UI
- was modeled on, multiple computers per account, roadmap and internal investigations.
+ was modeled on, roadmap and internal investigations.
- Every claim is checkable against the code or a doc above. Numbers and limits are written as the code has them.
Security guidance (what the relay sees, loopback-only API, reverse-proxy rules) is exact.
- MDX: the page's title (its `#` heading) and description live in `pages.ts`, so the file holds only `##` and
diff --git a/docs/plans/android-app.md b/docs/plans/android-app.md
index 9b026f46..a9c395ff 100644
--- a/docs/plans/android-app.md
+++ b/docs/plans/android-app.md
@@ -50,7 +50,7 @@ on one emulator, 2026-10-31).
| What | Code | What it needs |
| --- | --- | --- |
-| Revoke this phone's access (also on Remove of a computer approved through the account); removing older copies of the computer from the account | `core/.../CloudClient.kt` (`revokeAccess`, `removeComputer`), `AppStoreAccount.kt`, `ComputersView.kt` | A signed-in account on the emulator or a phone; only request tests cover it |
+| Revoke this phone's access (also on Remove of a computer approved through the account); removing older copies of the computer from the account | `core/.../CloudClient.kt` (`revokeAccess`, `removeComputer`), `AccountStoreAccount.kt`, `ComputersView.kt` | A signed-in account on the emulator or a phone; only request tests cover it |
| Push delivery (alerts, background Live update refresh) | `PushService.kt`, `AppStoreNotifications.kt` | A device with Google Play services running the official build (Firebase and the relay's FCM secret are set up since 2026-10-24). The notification look is covered by `AlertNotificationTest` |
| OpenAI Realtime, Gemini Live and Speech mode with a real key | `WebRtcPeer.kt`, `core/.../OpenAIRealtimeEngine.kt`, `GeminiLiveEngine.kt`, `CloudSpeechEngine.kt` | A provider key on the paired computer; the fallback to on-device voice is verified |
| Remote screen: Chinese IME composition, a hardware keyboard, the TURN relay path and its credential renewal | `ScreenKeys.kt`, `ScreenSession.kt`, `ScreenView.kt` | A computer it's safe to type into, and a signed-in host for the relay; viewing, trackpad and pinch zoom are verified |
@@ -75,7 +75,7 @@ on one emulator, 2026-10-31).
recognizer; it never falls back to online recognition (iOS may use Apple's servers).
- **Jump to latest** is an opaque disc: it sits in the scrolling content, so there's no blur under it.
- **A removed computer's open chat** closes with it; the iPhone shows *This computer was removed* in its place.
-- **Dictation on device** stops at a pause, like the iPhone's; Android's recognizer runs on the phone where it can, otherwise the phone's own speech service.
+- **Dictation on device** stops at a pause, like the iPhone's; Android's recognizer runs on the phone where it can (it tries the phone's own speech service once when that one lacks the language), otherwise the phone's own speech service.
- **Shortcuts' lead** (Settings → Shortcuts → Lead to call) is part of the Apple-only Shortcuts actions.
## Before a Play release
diff --git a/docs/plans/harness-memory.md b/docs/plans/harness-memory.md
index fb66d3d2..95239165 100644
--- a/docs/plans/harness-memory.md
+++ b/docs/plans/harness-memory.md
@@ -47,7 +47,7 @@ Claude Code sessions in the terminal. The choice adds an off switch for Codync's
The draft (`chat::memory::on`, the `history`-only memory server, the skipped dreaming, the restart with a fresh
session) was written as a one-or-the-other `MemoryOwner`; rebase it as a Codync on/off beside `harnessMemory`, then
-do the apps (iPhone, desktop, terminal; Android once its memory screen is ported), the docs, a minor release and a
+do the apps (iPhone, desktop, terminal, Android), the docs, a minor release and a
Mac e2e.
## Open questions
diff --git a/docs/reference/analytics-events.md b/docs/reference/analytics-events.md
index 210ac1d0..8673072f 100644
--- a/docs/reference/analytics-events.md
+++ b/docs/reference/analytics-events.md
@@ -114,7 +114,7 @@ host answers and sends it once the host is up.
| `chat` | a conversation opened | a conversation opened | a conversation opened |
| `trace` | full conversation | full conversation | full trace |
| `bot_details` | bot details | details panel | settings page |
-| `memory` | bot memory (Android: the card in bot details, once it scrolls into sight) | memory tab | memory overlay |
+| `memory` | bot memory (Android: the Memory tab in bot details) | memory tab | memory overlay |
| `routines` | routines (iPhone: a routine's editor, the list being part of bot details) | a routine's editor | routines overlay |
| `marketplace` | extensions | extensions | marketplace overlay |
| `settings` | Settings tab | settings | — |
diff --git a/web/content/docs/privacy.mdx b/web/content/docs/privacy.mdx
index 6598db8b..1c52b365 100644
--- a/web/content/docs/privacy.mdx
+++ b/web/content/docs/privacy.mdx
@@ -49,7 +49,7 @@ What leaves your device in a voice call or during dictation depends on the engin
| Engine | Where your voice goes |
| --- | --- |
-| On device (the default) | Recognized on your iPhone or Mac with Apple speech. Apple's servers may be used when on-device recognition isn't available for your language. Only the recognized text goes to your computer, as an ordinary message. |
+| On device (the default) | Recognized on your iPhone or Mac with Apple speech, or on your Android phone. Apple's servers may be used when on-device recognition isn't available for your language. On Android, dictation uses the phone's speech service when the phone can't recognize your language itself, and that service may use its provider's servers (Google's on most phones). Only the recognized text goes to your computer, as an ordinary message. |
| OpenAI or Gemini, Realtime mode | Straight from your device to the provider. Your computer gives the device a short-lived credential made from your key. Before the call, the provider also gets the background your computer writes for the voice: the date and time, what your bots remember about you (shared memory and the names of its notes), this bot's settings, routines and memory, the project's git branch, changed files and recent commits, what the bot is working on, the recent messages and calls in the chat, your other bots, and the names of files shared in the chat. When a call reconnects or you switch engine mid-call, it also gets what was said on the call so far. During the call it gets the messages and results the voice reads. Your computer keeps the call's written transcript, in the chat. |
| OpenAI or Gemini, Speech mode, and dictation with a provider | Your recording goes to your computer over the encrypted connection, and your computer sends it to the provider with your key and the names of the bots on the computer as spelling hints. The provider's spoken replies come back the same way. |
diff --git a/web/content/docs/voice.mdx b/web/content/docs/voice.mdx
index dd473b12..0e1aa4d7 100644
--- a/web/content/docs/voice.mdx
+++ b/web/content/docs/voice.mdx
@@ -90,7 +90,7 @@ The key is stored encrypted in Codync's vault on the computer (with the system k
| You use | Your audio | Your key |
| --- | --- | --- |
-| On device | Stays on your device. Only the recognized text goes to the computer, as a message. Apple's speech recognition may use Apple's servers when on-device recognition isn't available for your language. | Not needed |
+| On device | Stays on your device. Only the recognized text goes to the computer, as a message. Apple's speech recognition may use Apple's servers when on-device recognition isn't available for your language. On Android, calls are always recognized on the phone; dictation uses the phone's speech service when the phone can't recognize your language itself, and that service may use its provider's servers (Google's on most phones). | Not needed |
| Realtime | Streams directly between your device and the provider (OpenAI over WebRTC, Gemini over a WebSocket). It doesn't pass through your computer or the relay. The written transcript of the call is kept on your computer. | Stays on the computer, which gives your device a short-lived credential for each call |
| Speech mode, or dictation with a provider | Recordings go to your computer over the encrypted connection, and the computer sends them to the provider, with the names of the bots on the computer as spelling hints. The spoken replies come back the same way. | Stays on the computer |
@@ -106,7 +106,7 @@ While it listens, the microphone becomes a recording pill with a stop button, th
The small arrow beside the microphone (**Dictation engine**) chooses **On device**, **OpenAI** or **Gemini**. It's kept on this device, separate from the call engine.
-- **On device:** words appear as they're recognized, in the language set for calls. On the iPhone, stop keeps what was recognized so far. In the desktop app, dictation keeps listening through pauses until you press stop.
+- **On device:** words appear as they're recognized, in the language set for calls. On the iPhone and Android, stop keeps what was recognized so far. In the desktop app, dictation keeps listening through pauses until you press stop.
- **OpenAI or Gemini:** Codync first checks that the computer has the provider's key (if not, voice settings open so you can configure it before anything is recorded). The pill appears once the microphone is open, so nothing you say is lost. Nothing is typed while you record. When you press stop, the pill shows "Transcribing…" and the text lands in the box when it arrives. It uses the **Speech to text** model from Voice chat settings, and the recording counts toward that provider's minutes this month.
If dictation uses a provider that your calls don't, Voice chat settings show a separate section for it ("For dictation in the message box.") with its key status and speech-to-text model.