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.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat(android): several computers, memory, dictation and handoffs as on the iPhone
leepokaiaf71e7062295
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.ktindex 40c9329f..58fa19f4 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@@ -6,7 +6,8 @@ import androidx.compose.runtime.CompositionLocalProviderimport androidx.compose.runtime.mutableStateOfimport androidx.compose.ui.graphics.asAndroidBitmapimport androidx.compose.ui.test.*-import androidx.compose.ui.test.junit4.createComposeRule+import androidx.activity.ComponentActivity+import androidx.compose.ui.test.junit4.createAndroidComposeRuleimport androidx.compose.ui.unit.dpimport androidx.lifecycle.viewmodel.compose.viewModelimport androidx.test.platform.app.InstrumentationRegistry@@ -25,14 +26,16 @@ import kotlinx.coroutines.withContext/** The account sheet, Computer management and the Settings tab. Read-only: no test confirms a sign-out, route, removal or reset. */class AccountScreenTest {- @get:Rule val compose = createComposeRule()+ @get:Rule val compose = createAndroidComposeRule<ComponentActivity>()private val first = SavedAccount("first", "first-session", "[email protected]", null)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 fun fixture(accountState: AccountState = account) = AppState(loading = false,+ 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()) =+ AppState(computer, contextId = "profile-fixture", loading = false, connection = link, actualConnection = link, bots = bots)@Before fun isolatedEmulatorOnly() { assumeTrue(Build.PRODUCT.startsWith("sdk")) }@@ -107,11 +110,11 @@ class AccountScreenTest {compose.onNodeWithText(first.email).assertIsDisplayed()}- @Test fun computerManagementHoldsTheComputersSettingsAndKeepsRemovalBehindAConfirmation() {- val state = fixture().copy(computers = listOf(computer), connection = LinkState.Ready(HostRoute.Direct),- bots = listOf(Bot("hidden", "Hidden scout", hidden = true)))+ @Test fun computerManagementHoldsTheComputersSettingsAndKeepsRemovalBehindAConfirmation() = compose.withPreviewAccounts(computer) { accounts ->+ val state = fixture().copy(computers = listOf(computer))+ val online = paired(LinkState.Ready(HostRoute.Direct), listOf(Bot("hidden", "Hidden scout", hidden = true)))var paired = 0; var extensions = 0- compose.setContent { Hosted { ComputersView(state, viewModel(), { paired++ }, {}, { extensions++ }) } }+ compose.setContent { Hosted { ComputersView(state, listOf(online), accounts, { paired++ }, {}, { extensions++ }) } }compose.onNodeWithText("Computer management").assertIsDisplayed()compose.onNode(hasText(computer.name) and hasClickAction()).assertIsDisplayed()compose.onNodeWithText("1 bot · Wi-Fi/Tailscale").assertIsDisplayed()@@ -138,8 +141,7 @@ class AccountScreenTest {}@Test fun theSettingsTabHoldsOnlyThisPhonesSettingsAndKeepsResetBehindAConfirmation() {- val state = fixture().copy(computers = listOf(computer), connection = LinkState.Ready(HostRoute.Direct),- bots = listOf(Bot("hidden", "Hidden scout", hidden = true)))+ val state = fixture().copy(computers = listOf(computer))compose.setContent { Hosted { SettingsView(state, viewModel(), 0.dp) } }compose.onNodeWithText("Settings").assertIsDisplayed()listOf("Pair a computer", "Hidden scout", "Push notifications", "Voice chat").forEach { compose.onNodeWithText(it).assertDoesNotExist() }@@ -155,24 +157,24 @@ class AccountScreenTest {val cloud = CloudComputer("account-computer", "Account computer", "account-key", online = true)val asked = mutableListOf<CloudComputer>()val state = mutableStateOf(fixture().copy(cloudComputers = listOf(cloud)))- compose.setContent { Hosted { ComputersView(state.value, viewModel(), {}, { asked.add(it) }, {}) } }+ compose.setContent { Hosted { ComputersView(state.value, emptyList(), viewModel(), {}, { asked.add(it) }, {}) } }compose.onNodeWithText("Online · In your account").assertIsDisplayed()compose.onNodeWithText("Ask for access").performClick()assertEquals(listOf(cloud), asked)- compose.runOnUiThread { state.value = state.value.copy(access = AccessTicket("request", Long.MAX_VALUE, "123456", cloud.computerId, cloud.signKey)) }+ compose.runOnUiThread { state.value = state.value.copy(access = mapOf(cloud.computerId to AccessTicket("request", Long.MAX_VALUE, "123456", cloud.computerId, cloud.signKey))) }compose.onNodeWithText("Waiting for your OK on the computer · 123456").assertIsDisplayed()compose.onNodeWithText("Code").performClick()assertEquals(listOf(cloud, cloud), asked)}- @Test fun whileOneComputerIsAskedForAccessTheOthersWait() {+ @Test fun whileAComputerIsAskedForAccessOnlyItWaitsAndTheOthersCanBeAsked() {val asked = CloudComputer("asked-computer", "Asked computer", "asked-key", online = true)val other = CloudComputer("other-computer", "Other computer", "other-key", online = true)- val state = fixture().copy(cloudComputers = listOf(asked, other), askingAccess = asked.computerId)- compose.setContent { Hosted { ComputersView(state, viewModel(), {}, {}, {}) } }+ val state = fixture().copy(cloudComputers = listOf(asked, other), asking = setOf(asked.computerId))+ compose.setContent { Hosted { ComputersView(state, emptyList(), viewModel(), {}, {}, {}) } }val buttons = compose.onAllNodesWithText("Ask for access")- buttons[0].assertIsEnabled()- buttons[1].assertIsNotEnabled()+ buttons[0].assertIsNotEnabled()+ buttons[1].assertIsEnabled()}@Test fun thePendingAccessBannerShowsTheCodeAndCancels() {@@ -184,12 +186,12 @@ class AccountScreenTest {assertTrue(cancelled)}- @Test fun anUnreachableAccountComputerOffersAccessInsteadOfRemoval() {+ @Test fun anUnreachableAccountComputerOffersAccessInsteadOfRemoval() = compose.withPreviewAccounts(computer) { accounts ->val cloud = CloudComputer(computer.id, computer.name, computer.signKey, online = true, access = "granted")- val state = fixture().copy(computers = listOf(computer), cloudComputers = listOf(cloud),- connection = LinkState.Failed("This phone cannot reach the computer.", 403))+ val state = fixture().copy(computers = listOf(computer), cloudComputers = listOf(cloud))+ val unreachable = paired(LinkState.Failed("This phone cannot reach the computer.", 403))var asked: CloudComputer? = null- compose.setContent { Hosted { ComputersView(state, viewModel(), {}, { asked = it }, {}) } }+ compose.setContent { Hosted { ComputersView(state, listOf(unreachable), accounts, {}, { asked = it }, {}) } }compose.onNodeWithText("This phone cannot reach the computer.").assertIsDisplayed()compose.onNodeWithText("Ask for access").performClick()assertEquals(cloud, asked)@@ -199,13 +201,12 @@ class AccountScreenTest {compose.onNodeWithText("Revoke this phone's access").assertIsDisplayed()}- @Test fun aRevokedSavedComputerDoesNotBlockAskingItsReplacement() {+ @Test fun aRevokedSavedComputerDoesNotBlockAskingItsReplacement() = compose.withPreviewAccounts(computer) { accounts ->val old = CloudComputer(computer.id, computer.name, computer.signKey, online = false)val replacement = CloudComputer("replacement", "New computer", "new-key", online = true)- val state = fixture().copy(computers = listOf(computer), cloudComputers = listOf(old, replacement),- connection = LinkState.Failed("Access revoked.", 403))+ val state = fixture().copy(computers = listOf(computer), cloudComputers = listOf(old, replacement))var asked: CloudComputer? = null- compose.setContent { Hosted { ComputersView(state, viewModel(), {}, { asked = it }, {}) } }+ compose.setContent { Hosted { ComputersView(state, listOf(paired(LinkState.Failed("Access revoked.", 403))), accounts, {}, { asked = it }, {}) } }compose.onAllNodesWithText("Ask for access")[1].assertIsEnabled().performClick()assertEquals(replacement, asked)compose.onNodeWithText("Remove this phone's computer to use this one", substring = true).assertDoesNotExist()@@ -214,11 +215,11 @@ class AccountScreenTest {@Test fun anExistingPairingDoesNotPretendANewRequestWasApproved() {val cloud = CloudComputer(computer.id, computer.name, computer.signKey, online = true, access = "granted")val state = mutableStateOf(fixture().copy(computers = listOf(computer), cloudComputers = listOf(cloud),- access = AccessTicket("new-request", Long.MAX_VALUE, "123456", computer.id, computer.signKey), busy = setOf("access")))+ access = mapOf(computer.id to AccessTicket("new-request", Long.MAX_VALUE, "123456", computer.id, computer.signKey)), busy = setOf("access:${computer.id}")))compose.setContent { Hosted { AccessRequestView(state.value, viewModel(), cloud) } }compose.onNodeWithText("123 456").assertIsDisplayed()compose.onNodeWithText("${computer.name} approved this phone").assertDoesNotExist()- compose.runOnUiThread { state.value = state.value.copy(access = null, busy = emptySet(), approvedAccess = mapOf(computer.id to "new-request")) }+ compose.runOnUiThread { state.value = state.value.copy(access = emptyMap(), busy = emptySet(), approvedAccess = mapOf(computer.id to "new-request")) }compose.onNodeWithText("${computer.name} approved this phone").assertIsDisplayed()}@@ -230,49 +231,22 @@ class AccountScreenTest {compose.onNodeWithText("Waiting for approval…").assertDoesNotExist()}- @Test fun anApprovedHandoffWaitsForAnActiveSessionOperation() {- lateinit var store: AppStore+ @Test fun aSessionOperationWhileOneRunsIsDropped() {+ lateinit var store: AccountStoreval release = CompletableDeferred<Unit>()val calls = mutableListOf<String>()compose.setContent { store = viewModel() }compose.runOnUiThread {store.sessionAction { calls.add("first"); release.await(); calls.add("finished") }- store.sessionAction(wait = true) { calls.add("approved") }+ store.sessionAction { calls.add("second") }}- compose.runOnIdle { assertEquals(listOf("first"), calls) }compose.runOnUiThread { release.complete(Unit) }- compose.waitUntil { calls.size == 3 }- compose.runOnIdle { assertEquals(listOf("first", "finished", "approved"), calls) }- }-- @Test fun approvalRemainsVisibleWhileTheComputerHandoffWaits() {- lateinit var store: AppStore- val release = CompletableDeferred<Unit>()- compose.setContent { store = viewModel() }- compose.waitUntil { !store.state.value.loading }- compose.runOnUiThread {- store.mutableState.value = store.state.value.copy(computers = listOf(computer),- access = AccessTicket("approved-request", Long.MAX_VALUE, "123456", "replacement", "new-key"),- busy = setOf("access"))- store.sessionAction { release.await() }- store.useApprovedComputer(Computer("replacement", "New computer", "new-key"), "approved-request")- // The access polling action ends as soon as the cloud confirms approval.- store.mutableState.value = store.state.value.copy(access = null, busy = store.state.value.busy - "access")- }- compose.runOnIdle {- assertEquals("approved-request", store.state.value.approvedAccess["replacement"])- assertEquals(computer, store.state.value.computers.single())- }- // Retire this test's generation so releasing the queue cannot persist a pairing.- compose.runOnUiThread {- store.mutableState.value = store.state.value.copy(generation = store.state.value.generation + 1)- release.complete(Unit)- }- compose.waitUntil { "session" !in store.state.value.busy }+ compose.waitUntil { calls.size == 2 }+ compose.runOnIdle { assertEquals(listOf("first", "finished"), calls) }}@Test fun explicitRenewalReplacesANegotiatingAccessAction() {- lateinit var store: AppStore+ lateinit var store: AccountStorevar cancelled = falseval cleanupStarted = CompletableDeferred<Unit>()val releaseCleanup = CompletableDeferred<Unit>()@@ -281,7 +255,7 @@ class AccountScreenTest {val target = CloudComputer(computer.id, computer.name, computer.signKey, online = true, access = "granted")compose.runOnUiThread {store.cloud = null- store.action("access") {+ store.action("access:${target.computerId}") {try { awaitCancellation() } finally {withContext(NonCancellable) {cleanupStarted.complete(Unit)@@ -297,15 +271,15 @@ class AccountScreenTest {compose.waitUntil { cleanupStarted.isCompleted }compose.runOnIdle {assertFalse(cancelled)- assertTrue("renewAccess" in store.state.value.busy)+ assertTrue("renewAccess:${target.computerId}" in store.state.value.busy)assertNull(store.state.value.error) // Replacement hasn't reached the missing-cloud check.}compose.runOnUiThread { releaseCleanup.complete(Unit) }- compose.waitUntil { cancelled && "access" !in store.state.value.busy && "renewAccess" !in store.state.value.busy }+ compose.waitUntil { cancelled && "access:${target.computerId}" !in store.state.value.busy && "renewAccess:${target.computerId}" !in store.state.value.busy }compose.runOnIdle {// The replacement actually ran; merely cancelling the old job cannot produce this error.assertEquals("Sign in to reach your account.", store.state.value.error)- assertNull(store.state.value.askingAccess)+ assertFalse(target.computerId in store.state.value.asking)}}diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/AgentSettingsScreenTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/AgentSettingsScreenTest.ktindex 6a301789..728ce491 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/AgentSettingsScreenTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/AgentSettingsScreenTest.kt@@ -15,7 +15,7 @@ import java.util.concurrent.atomic.AtomicBooleanclass AgentSettingsScreenTest {@get:Rule val compose = createComposeRule()- private val online = AppState(loading = false, computers = listOf(Computer("fixture", "Fixture computer", "fixture")),+ private val online = AppState(previewComputer, loading = false,actualConnection = LinkState.Ready(HostRoute.Direct))private val model = hasContentDescription("Model:", substring = true)diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/BotEditorTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/BotEditorTest.ktindex 02cb73ae..4a38369a 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/BotEditorTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/BotEditorTest.kt@@ -9,7 +9,6 @@ import androidx.compose.runtime.setValueimport androidx.compose.ui.graphics.asAndroidBitmapimport androidx.compose.ui.test.*import androidx.compose.ui.test.junit4.createComposeRule-import androidx.lifecycle.viewmodel.compose.viewModelimport androidx.test.platform.app.InstrumentationRegistryimport com.codync.android.core.*import com.codync.android.design.AvatarPalette@@ -25,6 +24,7 @@ import java.io.File/** Read-only UI fixtures for the bot settings and the New bot / New group chat dialogs: no test taps Save or Create, so production bots are never changed. */class BotEditorTest {@get:Rule val compose = createComposeRule()+ private val store = previewStore(Computer("fixture", "Fixture computer", "fixture-key"))private val scout = BotDraft(id = "fixture", name = "Scout", avatarShape = "blob", avatarColor = "blue")@Before fun isolatedEmulatorOnly() { assumeTrue(Build.PRODUCT.startsWith("sdk")) }@@ -56,7 +56,7 @@ class BotEditorTest {}@Test fun aNewBotIsItsFaceAndAnOptionalName() {- compose.setContent { Hosted { NewBotView(fixture(), viewModel()) } }+ compose.setContent { Hosted { NewBotView(fixture(), store) } }compose.onNodeWithText("New bot").assertIsDisplayed()compose.onNode(hasSetTextAction() and hasText("Name your bot")).assertIsDisplayed().assertIsFocused()compose.onNodeWithContentDescription("Create").assertIsEnabled()@@ -70,14 +70,14 @@ class BotEditorTest {}@Test fun anOfflineNewBotCannotBeCreated() {- compose.setContent { Hosted { NewBotView(fixture().copy(actualConnection = LinkState.Connecting), viewModel()) } }+ compose.setContent { Hosted { NewBotView(fixture().copy(actualConnection = LinkState.Connecting), store) } }compose.onNodeWithContentDescription("Create").assertIsNotEnabled()compose.onNodeWithText("Connect this computer to create the bot.").assertIsDisplayed()}@Test fun aNewGroupIsNamedAfterThePickedBotsUntilNamed() {val bots = listOf(Bot("a", "Scout", avatarShape = "blob"), Bot("b", "Reviewer", avatarShape = "hex"))- compose.setContent { Hosted { NewGroupView(fixture().copy(bots = bots), viewModel()) } }+ compose.setContent { Hosted { NewGroupView(fixture().copy(bots = bots), store) } }compose.onNodeWithText("New group chat").assertIsDisplayed()compose.onNodeWithContentDescription("Create").assertIsNotEnabled()compose.onNode(hasSetTextAction() and hasText("Name your group")).assertIsDisplayed()@@ -90,7 +90,7 @@ class BotEditorTest {}@Test fun aNewGroupWithoutBotsSaysToCreateOneFirst() {- compose.setContent { Hosted { NewGroupView(fixture(), viewModel()) } }+ compose.setContent { Hosted { NewGroupView(fixture(), store) } }compose.onNodeWithText("No bots yet. Create a bot first.").assertIsDisplayed()compose.onNodeWithContentDescription("Create").assertIsNotEnabled()}@@ -136,14 +136,13 @@ class BotEditorTest {}private fun render(draft: BotDraft, state: AppState = fixture(), close: () -> Unit = {}) {- compose.setContent { Hosted { CompositionLocalProvider(LocalDismissModal provides close) { BotEditor(state, draft, viewModel()) } } }+ compose.setContent { Hosted { CompositionLocalProvider(LocalDismissModal provides close) { BotEditor(state, draft, store) } } }}private fun toggle(title: String) = compose.onNode(hasText(title) and isToggleable())- private fun fixture(): AppState = AppState(loading = false, setupComplete = true,- actualConnection = LinkState.Ready(HostRoute.Direct), plugins = PluginListing(emptyList(), emptyList()),- computers = listOf(Computer("fixture", "Fixture computer", "fixture-key")), hello = buildJsonObject {+ private fun fixture(): AppState = AppState(Computer("fixture", "Fixture computer", "fixture-key"), loading = false,+ actualConnection = LinkState.Ready(HostRoute.Direct), plugins = PluginListing(emptyList(), emptyList()), hello = buildJsonObject {put("backends", buildJsonArray {add(buildJsonObject { put("id", "claude"); put("name", "Claude"); put("available", true) })add(buildJsonObject { put("id", "codex"); put("name", "Codex"); put("available", false); put("installHint", "Install Codex on your computer.") })diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/ChatLayoutTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/ChatLayoutTest.ktindex 4f10bb8e..8840828e 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/ChatLayoutTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/ChatLayoutTest.kt@@ -7,7 +7,6 @@ import androidx.compose.ui.geometry.Offsetimport androidx.compose.ui.graphics.asAndroidBitmapimport androidx.compose.ui.test.*import androidx.compose.ui.test.junit4.createAndroidComposeRule-import androidx.lifecycle.ViewModelProviderimport androidx.test.platform.app.InstrumentationRegistryimport com.codync.android.core.*import kotlinx.serialization.json.*@@ -22,7 +21,7 @@ class ChatLayoutTest {@Test fun oneWayBotMessagesShowAttributionWithoutAStatusLine() {assumeTrue(Build.PRODUCT.startsWith("sdk"))- val store = ViewModelProvider(compose.activity)[AppStore::class.java]+ val store = previewStore()val bot = Bot("handoff-preview", "Dex")val body = "Urgent. Investigate the connection error."val heading = "Message from Miles: $body"@@ -30,7 +29,7 @@ class ChatLayoutTest {val entry = Entry("bot-message", 1, bot.id, rev = 1, kind = "notice", data = buildJsonObject {put("text", "$heading\n$detail"); put("heading", heading); put("delegationId", "request"); put("style", "error")})- val state = AppState(loading = false, selectedBot = bot.id, bots = listOf(bot),+ val state = AppState(previewComputer, loading = false, selectedBot = bot.id, bots = listOf(bot),connection = LinkState.Ready(HostRoute.Direct), actualConnection = LinkState.Ready(HostRoute.Direct),historyComplete = setOf(bot.id), entries = listOf(entry))compose.runOnUiThread { compose.activity.setContent { Hosted { ChatScreen(state, store, {}) } } }@@ -47,7 +46,7 @@ class ChatLayoutTest {@Test fun botRepliesAppearBelowTheRequestInSeparateBubbles() {assumeTrue(Build.PRODUCT.startsWith("sdk"))- val store = ViewModelProvider(compose.activity)[AppStore::class.java]+ val store = previewStore()val bot = Bot("reply-preview", "Dex")val body = "Investigate the connection error."val heading = "Request from Miles: $body"@@ -56,7 +55,7 @@ class ChatLayoutTest {put("text", "$heading\nReply from Dex:\n$answer"); put("heading", heading)put("delegationId", "request"); put("status", "completed")})- val state = AppState(loading = false, selectedBot = bot.id, bots = listOf(bot),+ val state = AppState(previewComputer, loading = false, selectedBot = bot.id, bots = listOf(bot),connection = LinkState.Ready(HostRoute.Direct), actualConnection = LinkState.Ready(HostRoute.Direct),historyComplete = setOf(bot.id), entries = listOf(entry))compose.runOnUiThread { compose.activity.setContent { Hosted { ChatScreen(state, store, {}) } } }@@ -85,12 +84,12 @@ class ChatLayoutTest {@Test fun aShortConversationStaysNearItsComposerAndRetainsContextActions() {assumeTrue(Build.PRODUCT.startsWith("sdk"))- val store = ViewModelProvider(compose.activity)[AppStore::class.java]+ val store = previewStore()val bot = Bot("layout-preview", "Scout", avatarColor = "green", avatarShape = "cloud")val sent = "Add a weekly totals helper and check its tests."val reply = "I added the helper and a test. All four tests pass."val now = System.currentTimeMillis()- val state = AppState(loading = false, selectedBot = bot.id, bots = listOf(bot),+ val state = AppState(previewComputer, loading = false, selectedBot = bot.id, bots = listOf(bot),connection = LinkState.Ready(HostRoute.Direct), actualConnection = LinkState.Ready(HostRoute.Direct),historyComplete = setOf(bot.id), entries = listOf(Entry("user-layout", 1, bot.id, rev = 1, kind = "user", data = buildJsonObject { put("text", sent) }, createdAt = now),@@ -125,9 +124,9 @@ class ChatLayoutTest {@Test fun theTitleOpensTheBotsDetailsOnDetails() {assumeTrue(Build.PRODUCT.startsWith("sdk"))- val store = ViewModelProvider(compose.activity)[AppStore::class.java]+ val store = previewStore()val bot = Bot("details-preview", "Scout")- val state = AppState(loading = false, selectedBot = bot.id, bots = listOf(bot), historyComplete = setOf(bot.id),+ val state = AppState(previewComputer, loading = false, selectedBot = bot.id, bots = listOf(bot), historyComplete = setOf(bot.id),hello = buildJsonObject { put("version", ARTIFACTS_HOST) })compose.runOnUiThread { compose.activity.setContent { Hosted { ChatScreen(state, store, {}) } } }compose.onNode(chatTitle).performClick()diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/ConnectionRequestCardTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/ConnectionRequestCardTest.ktindex 798415fb..5aa4ceba 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/ConnectionRequestCardTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/ConnectionRequestCardTest.kt@@ -4,7 +4,6 @@ import androidx.compose.runtime.mutableStateOfimport androidx.compose.ui.semantics.SemanticsPropertiesimport androidx.compose.ui.test.*import androidx.compose.ui.test.junit4.createComposeRule-import androidx.lifecycle.viewmodel.compose.viewModelimport com.codync.android.core.*import kotlinx.serialization.json.*import org.junit.Assert.*@@ -15,7 +14,8 @@ import org.junit.Testclass ConnectionRequestCardTest {@get:Rule val compose = createComposeRule()private val bot = Bot("bot", "Scout")- private val online = AppState(loading = false, bots = listOf(bot), actualConnection = LinkState.Ready(HostRoute.Direct))+ private val store = previewStore()+ private val online = AppState(previewComputer, loading = false, bots = listOf(bot), actualConnection = LinkState.Ready(HostRoute.Direct))private fun card(request: ConnectionRequest, text: String = "") = Entry("request", 1, bot.id, rev = 1, kind = "connectionRequest",data = buildJsonObject { put("text", text); put("connectionRequest", WireJson.encodeToJsonElement(ConnectionRequest.serializer(), request)) })@@ -24,7 +24,7 @@ class ConnectionRequestCardTest {val state = mutableStateOf(online)// A site without a dot: no favicon to fetch.val entry = card(ConnectionRequest("login", "pending", "Fixture login", bot.id, site = "fixture"))- compose.setContent { Hosted { ConnectionRequestCard(entry, state.value, viewModel(), { _, _ -> fail("Not an app") }, { _, _ -> fail("Not a connector") }) } }+ compose.setContent { Hosted { ConnectionRequestCard(entry, state.value, store, { _, _ -> fail("Not an app") }, { _, _ -> fail("Not a connector") }) } }compose.onNodeWithText("Save").assertIsNotEnabled()compose.onNodeWithContentDescription("Username or email").performTextInput("fixture-user")compose.onNodeWithContentDescription("Password or op:// reference")@@ -38,7 +38,7 @@ class ConnectionRequestCardTest {@Test fun anAppRequestOpensItsSheetForThisRequest() {val opened = mutableListOf<Pair<String, ComposioApp>>()val entry = card(ConnectionRequest("app", "pending", "GitHub", bot.id, toolkit = "github"), "Needs GitHub to open the PR.")- compose.setContent { Hosted { ConnectionRequestCard(entry, online, viewModel(), { id, app -> opened.add(id to app) }, { _, _ -> fail("Not a connector") }) } }+ compose.setContent { Hosted { ConnectionRequestCard(entry, online, store, { id, app -> opened.add(id to app) }, { _, _ -> fail("Not a connector") }) } }compose.onNodeWithText("Needs GitHub to open the PR.").assertIsDisplayed()compose.onNodeWithText("Connect").performClick()compose.waitUntil { opened.isNotEmpty() }@@ -48,7 +48,7 @@ class ConnectionRequestCardTest {@Test fun finishedAndUnknownRequestsNeverLookPending() {val request = mutableStateOf(ConnectionRequest("connection", "ready", "Fixture connector", bot.id, connectorId = "fixture"))- compose.setContent { Hosted { ConnectionRequestCard(card(request.value), online, viewModel(), { _, _ -> }, { _, _ -> }) } }+ compose.setContent { Hosted { ConnectionRequestCard(card(request.value), online, store, { _, _ -> }, { _, _ -> }) } }compose.onNodeWithText("Connected").assertIsDisplayed()compose.onNodeWithText("Connect").assertDoesNotExist()compose.runOnUiThread { request.value = request.value.copy(status = "future-status") }@@ -59,7 +59,7 @@ class ConnectionRequestCardTest {@Test fun aRequestForAnUnknownBotAsksForANewerApp() {val entry = card(ConnectionRequest("secret", "pending", "Fixture key", "elsewhere"))- compose.setContent { Hosted { ConnectionRequestCard(entry, online, viewModel(), { _, _ -> }, { _, _ -> }) } }+ compose.setContent { Hosted { ConnectionRequestCard(entry, online, store, { _, _ -> }, { _, _ -> }) } }compose.onNodeWithText("This connection request needs a newer app.").assertIsDisplayed()compose.onNodeWithText("Connect").assertDoesNotExist()}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.ktindex a2f47646..01982653 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@@ -1,23 +1,24 @@package com.codync.android+import androidx.activity.ComponentActivityimport androidx.compose.runtime.mutableStateOfimport androidx.compose.ui.test.*-import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.junit4.createAndroidComposeRuleimport androidx.compose.ui.unit.dp-import androidx.lifecycle.viewmodel.compose.viewModelimport com.codync.android.core.*import org.junit.Assert.assertTrueimport org.junit.Ruleimport org.junit.Testclass ConnectionUiTest {- @get:Rule val compose = createComposeRule()- private fun fixture(link: LinkState) = AppState(loading = false, setupComplete = true, rosterLoaded = true,- computers = listOf(Computer("fixture", "Fixture computer", "fixture")), connection = link, actualConnection = link)+ @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 fun fixture(link: LinkState) = AppState(computer, loading = false, rosterLoaded = true, connection = link, actualConnection = link)- @Test fun theComputerRowNamesTheActualConnectionState() {+ @Test fun theComputerRowNamesTheActualConnectionState() = compose.withPreviewAccounts(computer) { accounts ->val state = mutableStateOf(fixture(LinkState.Failed("Your access was revoked.", 403)))- compose.setContent { Hosted { ComputersView(state.value, viewModel(), {}, {}, {}) } }+ compose.setContent { Hosted { ComputersView(app, listOf(state.value), accounts, {}, {}, {}) } }compose.onNodeWithText("Your access was revoked.").assertIsDisplayed()compose.onNodeWithText("Extensions").assertDoesNotExist()compose.runOnUiThread { state.value = fixture(LinkState.ComputerOffline(null)) }@@ -27,10 +28,10 @@ class ConnectionUiTest {compose.onNodeWithText("Extensions").assertIsDisplayed()}- @Test fun cachedBotsStayListedWhileOfflineAndAnEmptyRosterOffersTheFirstBot() {+ @Test fun cachedBotsStayListedWhileOfflineAndAnEmptyRosterOffersTheFirstBot() = compose.withPreviewAccounts(computer) { accounts ->val state = mutableStateOf(fixture(LinkState.ComputerOffline(null)).copy(bots = listOf(Bot("bot", "Saved bot"))))var created = false- compose.setContent { Hosted { BotListView(state.value, viewModel(), {}, {}, { created = true }, {}, {}, 0.dp) } }+ compose.setContent { Hosted { BotListView(app, listOf(state.value), accounts, {}, {}, { created = true }, {}, { _, _ -> }, {}, 0.dp) } }compose.onNodeWithText("Saved bot").assertIsDisplayed()compose.onNodeWithText("1 offline").assertIsDisplayed()compose.onNodeWithText("No bots yet").assertDoesNotExist()diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/FixtureHost.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/FixtureHost.ktindex c52287f4..988d600b 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/FixtureHost.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/FixtureHost.kt@@ -1,6 +1,10 @@package com.codync.androidimport android.os.Build+import androidx.activity.ComponentActivity+import androidx.compose.ui.test.junit4.AndroidComposeTestRule+import androidx.compose.ui.test.junit4.ComposeTestRule+import androidx.lifecycle.ViewModelProviderimport androidx.test.platform.app.InstrumentationRegistryimport org.junit.Assert.assertEqualsimport org.junit.Assume.assumeTrue@@ -13,3 +17,14 @@ internal fun requireFixtureHost(computerId: String) {}assertEquals("This suite must use its disposable host", expected, computerId)}++/** The account's ViewModel, the one [activity]'s UI uses. */+internal fun accountStore(activity: ComponentActivity): AccountStore = ViewModelProvider(activity)[AccountStore::class.java]++/** Computer [id]'s store (the first computer's when null), once the account has opened it. */+internal fun ComposeTestRule.computerStore(accounts: AccountStore, id: String? = null): AppStore {+ waitUntil(30_000) { accounts.stores.value.any { id == null || it.id == id } }+ return accounts.stores.value.first { id == null || it.id == id }+}++internal fun AndroidComposeTestRule<*, out ComponentActivity>.computerStore(id: String? = null): AppStore = computerStore(accountStore(activity), id)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.ktindex bcfcaab7..13c94bfc 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@@ -3,12 +3,12 @@ package com.codync.androidimport androidx.compose.runtime.CompositionLocalProviderimport androidx.compose.ui.platform.LocalDensityimport androidx.compose.ui.graphics.asAndroidBitmap-import androidx.lifecycle.viewmodel.compose.viewModelimport androidx.test.platform.app.InstrumentationRegistryimport android.graphics.Bitmapimport java.io.Fileimport androidx.compose.ui.test.*-import androidx.compose.ui.test.junit4.createComposeRule+import androidx.activity.ComponentActivity+import androidx.compose.ui.test.junit4.createAndroidComposeRuleimport androidx.compose.ui.unit.Densityimport com.codync.android.core.*import org.junit.Assert.*@@ -17,17 +17,18 @@ import org.junit.Test/** Read-only roster fixture: nothing here pairs, saves or sends. */class LayoutTest {- @get:Rule val compose = createComposeRule()- private val state = AppState(loading = false, setupComplete = true, rosterLoaded = true,- computers = listOf(Computer("fixture", "Acceptance computer", "fixture")),+ @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 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)})private val computers = hasContentDescription("Computers,", substring = true)private fun tab(title: String) = hasText(title) and isSelectable()- @Test fun theRosterShowsFiveRowsAndKeepsActionsOnDemand() {- compose.setContent { Hosted { CodyncApp(state, viewModel()) } }+ @Test fun theRosterShowsFiveRowsAndKeepsActionsOnDemand() = compose.withPreviewAccounts(computer) { accounts ->+ compose.setContent { Hosted { CodyncApp(app, mapOf(computer.id to state), accounts) } }(1..5).forEach { compose.onNodeWithText("Bot $it").assertIsDisplayed() }compose.onNodeWithText("12").assertIsDisplayed()snapshot("roster")@@ -53,11 +54,11 @@ class LayoutTest {compose.onNodeWithText("Bot 5").assertIsDisplayed()}- @Test fun largerTextKeepsTheHeaderControlsAndUnreadBadgeAccessible() {+ @Test fun largerTextKeepsTheHeaderControlsAndUnreadBadgeAccessible() = compose.withPreviewAccounts(computer) { accounts ->compose.setContent {val density = LocalDensity.currentCompositionLocalProvider(LocalDensity provides Density(density.density, 1.5f)) {- Hosted { CodyncApp(state, viewModel()) }+ Hosted { CodyncApp(app, mapOf(computer.id to state), accounts) }}}val account = compose.onNodeWithContentDescription("Switch account").assertIsDisplayed().fetchSemanticsNode().boundsInRootdiff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveCredentialsTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveCredentialsTest.ktindex e75dc45a..6cffde7c 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveCredentialsTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveCredentialsTest.kt@@ -2,7 +2,6 @@ package com.codync.androidimport androidx.compose.ui.test.*import androidx.compose.ui.test.junit4.createAndroidComposeRule-import androidx.lifecycle.ViewModelProviderimport androidx.test.platform.app.InstrumentationRegistryimport com.codync.android.core.*import kotlinx.coroutines.runBlocking@@ -31,7 +30,7 @@ class LiveCredentialsTest {val site = "android-$suffix.fixture.invalid"val name = "Android credentials $suffix"try {- val store = ViewModelProvider(compose.activity)[AppStore::class.java]+ val store = compose.computerStore()compose.waitUntil(30_000) { !store.state.value.loading && store.state.value.actualConnection is LinkState.Ready }compose.runOnUiThread { store.openBot(null) }compose.openExtensions()@@ -103,7 +102,7 @@ class LiveCredentialsTest {val route = computer.copy(urls = listOf("http://10.0.2.2:29322"), route = ConnectionRoute.DirectOnly)val channel = runBlocking { HostConnector.connect(route, local.identity()) }try {- val store = ViewModelProvider(compose.activity)[AppStore::class.java]+ val store = compose.computerStore()compose.waitUntil(30_000) { store.state.value.bots.any { it.id == botId } && store.state.value.entries.any { it.id == savedRequest } }assertTrue(store.state.value.bots.single { it.id == botId }.name.startsWith("Android credentials acceptance"))compose.runOnUiThread { store.openBot(botId) }diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveDraftTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveDraftTest.ktindex 6640f726..e2dd2e54 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveDraftTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveDraftTest.kt@@ -3,7 +3,6 @@ package com.codync.androidimport androidx.compose.ui.test.*import androidx.compose.ui.test.junit4.createAndroidComposeRuleimport androidx.core.content.FileProvider-import androidx.lifecycle.ViewModelProviderimport androidx.test.platform.app.InstrumentationRegistryimport org.junit.Assert.*import org.junit.Assume.assumeTrue@@ -26,7 +25,7 @@ class LiveDraftTest {assertNull(PushPreferences.activeUser(context))val book = DraftBook(local.directory, computer.id)val metadata = File(context.cacheDir, "draft-acceptance.json")- val store = ViewModelProvider(compose.activity)[AppStore::class.java]+ val store = compose.computerStore()compose.waitUntil(30_000) { store.state.value.bots.any { it.name == "Android chat acceptance" } }val bot = store.state.value.bots.single { it.name == "Android chat acceptance" }compose.runOnUiThread { store.openBot(bot.id) }diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveManagementTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveManagementTest.ktindex a678722d..3a32fcce 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveManagementTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveManagementTest.kt@@ -3,7 +3,6 @@ package com.codync.androidimport android.view.KeyEventimport androidx.compose.ui.test.*import androidx.compose.ui.test.junit4.createAndroidComposeRule-import androidx.lifecycle.ViewModelProviderimport androidx.test.platform.app.InstrumentationRegistryimport com.codync.android.core.*import kotlinx.coroutines.runBlocking@@ -30,7 +29,7 @@ class LiveManagementTest {val result = runBlocking { channel.call("createBot", BotDraft.from(parent).copy(id = null, name = name, permission = "auto").body()) }val member = HostClient.decode(result.jsonObject.getValue("bot").jsonObject)created.add(member.id)- val store = ViewModelProvider(compose.activity)[AppStore::class.java]+ val store = compose.computerStore()compose.waitUntil(30_000) { store.state.value.bots.any { it.id == member.id } }compose.runOnUiThread { store.openBot(null) }compose.onNodeWithContentDescription("New").performClick()diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveMemoryTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveMemoryTest.ktindex 585665da..97228af1 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveMemoryTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveMemoryTest.kt@@ -2,7 +2,6 @@ package com.codync.androidimport androidx.compose.ui.test.*import androidx.compose.ui.test.junit4.createAndroidComposeRule-import androidx.lifecycle.ViewModelProviderimport androidx.test.platform.app.InstrumentationRegistryimport com.codync.android.core.*import kotlinx.coroutines.runBlocking@@ -16,47 +15,30 @@ import org.junit.Testclass LiveMemoryTest {@get:Rule val compose = createAndroidComposeRule<MainActivity>()- @Test fun forgettingFactsAndClearingMemoryPreserveTheConversation() {+ @Test fun theMemoryTabShowsBothLayersAndDreamsReadOnly() {val botId = InstrumentationRegistry.getArguments().getString("memoryBot")assumeTrue(botId != null)val context = InstrumentationRegistry.getInstrumentation().targetContextval local = LocalStore(context)- val computer = local.computers().single().copy(urls = listOf("http://10.0.2.2:29322"), route = ConnectionRoute.DirectOnly)+ val computer = local.computers().first().copy(urls = listOf("http://10.0.2.2:29322"), route = ConnectionRoute.DirectOnly)val channel = runBlocking { HostConnector.connect(computer, local.identity()) }try {- val before = runBlocking { channel.call("history", body("botId" to botId)) }- val store = ViewModelProvider(compose.activity)[AppStore::class.java]+ val memory = WireJson.decodeFromJsonElement<BotMemory>(runBlocking { channel.call("memory", body("botId" to botId)) })+ val store = compose.computerStore()compose.waitUntil(30_000) { store.state.value.bots.any { it.id == botId } }val name = store.state.value.bots.single { it.id == botId }.name- assertTrue(name.startsWith("Android memory acceptance"))- // The memory card is in the whole settings form, the roster's Edit profile.- compose.runOnUiThread { store.openBot(null) }- compose.rosterAction(name, "Edit profile")- val profile = "Android memory profile acceptance"- compose.waitUntil(30_000) { compose.onAllNodesWithText(profile).fetchSemanticsNodes().size == 1 }- compose.onNodeWithText("Android memory history acceptance").performScrollTo().assertIsDisplayed()- // Searching leaves one fact, so its menu is the only one.- val search = hasSetTextAction() and hasText("Search memories")- compose.onNode(search).performScrollTo().performTextInput("profile")- compose.waitUntil(30_000) { compose.onAllNodesWithContentDescription("Memory actions").fetchSemanticsNodes().size == 1 }- compose.onNodeWithContentDescription("Memory actions").performScrollTo().performClick()- compose.onNodeWithText("Forget").performClick()- compose.waitUntil(30_000) { compose.onAllNodesWithText(profile).fetchSemanticsNodes().isEmpty() }- compose.onNode(hasSetTextAction() and hasText("profile")).performTextReplacement("")- compose.waitUntil(30_000) { compose.onAllNodesWithText("Android memory history acceptance").fetchSemanticsNodes().size == 1 }- val left = MemoryListing.decode(runBlocking { channel.call("memory", body("botId" to botId)) }).facts- assertEquals("Android memory history acceptance", left.single().content)- compose.onNodeWithContentDescription("More").performScrollTo().performClick()- compose.onNodeWithText("Forget everything").performClick()- compose.onNodeWithText("Forget everything this bot remembers?").assertIsDisplayed()- compose.onNodeWithText("Forget everything").performClick()- compose.waitUntil(30_000) {- compose.onAllNodesWithText("Nothing yet. Important details are remembered as you chat.").fetchSemanticsNodes().size == 1- }- val after = runBlocking { channel.call("history", body("botId" to botId)) }- assertEquals(before.jsonObject.getValue("entries"), after.jsonObject.getValue("entries"))- val memory = runBlocking { channel.call("memory", body("botId" to botId)) }- assertTrue(MemoryListing.decode(memory).facts.isEmpty())+ compose.runOnUiThread { store.openBot(botId) }+ // The chat's title opens its details; Memory is one of their pages.+ compose.onNodeWithContentDescription("$name, view details").performClick()+ compose.onNodeWithText("Memory").performClick()+ compose.waitUntil(30_000) { compose.onAllNodesWithText("What this bot learned about you", substring = true).fetchSemanticsNodes().isNotEmpty() }+ for (entry in memory.bot.entries) compose.onNodeWithText(entry.text, substring = true).performScrollTo().assertIsDisplayed()+ compose.onNodeWithText("About you").performClick()+ compose.waitUntil(30_000) { compose.onAllNodesWithText("Use what your bots share").fetchSemanticsNodes().isNotEmpty() }+ compose.onNodeWithText("Dreams").performClick()+ compose.waitUntil(30_000) { compose.onAllNodesWithText("Between chats the bot tidies its memory from your own words.").fetchSemanticsNodes().isNotEmpty() }+ // Read-only: nothing here adds, edits or forgets a memory.+ assertTrue(compose.onAllNodesWithContentDescription("Add memory").fetchSemanticsNodes().isEmpty())} finally { channel.close() }}}diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LivePluginsTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LivePluginsTest.ktindex d2e7c025..9da5f91e 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/LivePluginsTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LivePluginsTest.kt@@ -2,7 +2,6 @@ package com.codync.androidimport androidx.compose.ui.test.*import androidx.compose.ui.test.junit4.createAndroidComposeRule-import androidx.lifecycle.ViewModelProviderimport androidx.test.platform.app.InstrumentationRegistryimport com.codync.android.core.*import kotlinx.coroutines.runBlocking@@ -29,7 +28,7 @@ class LivePluginsTest {var connectorId: String? = null; var skillId: String? = nullval name = "Fixture " + UUID.randomUUID().toString().take(8)try {- val store = ViewModelProvider(compose.activity)[AppStore::class.java]+ val store = compose.computerStore()compose.waitUntil(30_000) { !store.state.value.loading && store.state.value.actualConnection is LinkState.Ready }compose.runOnUiThread { store.openBot(null) }compose.openExtensions()diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveRosterTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveRosterTest.ktindex 8afcd263..6aefe113 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveRosterTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveRosterTest.kt@@ -2,7 +2,6 @@ package com.codync.androidimport androidx.test.platform.app.InstrumentationRegistryimport androidx.test.core.app.ActivityScenario-import androidx.lifecycle.ViewModelProviderimport com.codync.android.core.HostClientimport com.codync.android.core.HostConnectorimport kotlinx.coroutines.runBlocking@@ -49,31 +48,32 @@ class LiveRosterTest {val user = PushPreferences.activeUser(instrumentation.targetContext)val expectedContext = LocalStore.referenceId(user ?: "local")ActivityScenario.launch(MainActivity::class.java).use { scenario ->- var model: AppStore? = null+ var model: AccountStore? = nullscenario.onActivity { activity ->- val store = ViewModelProvider(activity)[AppStore::class.java]- model = store+ val accounts = accountStore(activity)+ model = accounts// A locked test phone may stop the Activity while we inspect sync independently.- store.setForeground(true)+ accounts.setForeground(true)}- val store = requireNotNull(model)+ val accounts = requireNotNull(model)try {runBlocking {withTimeout(60_000) {- store.state.first { !it.loading && it.contextId == expectedContext && (user == null || it.account.ready) }+ accounts.state.first { !it.loading && it.contextId == expectedContext && (user == null || it.account.ready) }+ val store = accounts.stores.first { it.isNotEmpty() }.first()val synced = store.state.first { it.rosterLoaded && it.bots.isNotEmpty() }println("Account mirror populated: ${synced.bots.size} bots")if (InstrumentationRegistry.getArguments().getString("inspectCatchup") == "true") {val head = requireNotNull(synced.hello).getValue("rev").jsonPrimitive.longval local = LocalStore(instrumentation.targetContext, user ?: "local")- MirrorDatabase(instrumentation.targetContext, local.directory, synced.computers.first().id).use { mirror ->+ MirrorDatabase(instrumentation.targetContext, local.directory, synced.computer.id).use { mirror ->while (withContext(Dispatchers.IO) { mirror.revision() } < head) delay(100)println("Account mirror committed catch-up through the host head")}}}}- } finally { instrumentation.runOnMainSync { store.setForeground(false) } }+ } finally { instrumentation.runOnMainSync { accounts.setForeground(false) } }}}diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveRoutinesTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveRoutinesTest.ktindex 54f5500b..48c01a73 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveRoutinesTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveRoutinesTest.kt@@ -2,7 +2,6 @@ package com.codync.androidimport androidx.compose.ui.test.*import androidx.compose.ui.test.junit4.createAndroidComposeRule-import androidx.lifecycle.ViewModelProviderimport androidx.test.platform.app.InstrumentationRegistryimport com.codync.android.core.*import kotlinx.coroutines.runBlocking@@ -33,7 +32,7 @@ class LiveRoutinesTest {val response = runBlocking { channel.call("createBot", BotDraft.from(parent).copy(id = null, name = "Routine acceptance " + UUID.randomUUID().toString().take(6), permission = "auto").body()) }val bot = HostClient.decode(response.jsonObject.getValue("bot").jsonObject)clone = bot- val store = ViewModelProvider(compose.activity)[AppStore::class.java]+ val store = compose.computerStore()compose.waitUntil(30_000) { !store.state.value.loading && store.state.value.bots.any { it.id == bot.id } }compose.runOnUiThread { store.refreshUsage(false) }compose.waitUntil(15_000) { "usage" !in store.state.value.busy }diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveRoutingTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveRoutingTest.ktindex ea33070a..2c68557d 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveRoutingTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveRoutingTest.kt@@ -4,7 +4,6 @@ import android.content.Intentimport android.net.Uriimport androidx.test.core.app.ActivityScenarioimport androidx.test.platform.app.InstrumentationRegistry-import androidx.lifecycle.ViewModelProviderimport androidx.compose.ui.test.*import androidx.compose.ui.test.junit4.createEmptyComposeRuleimport com.codync.android.core.*@@ -53,18 +52,22 @@ class LiveRoutingTest {try {val intent = Intent(Intent.ACTION_VIEW, link(), context, MainActivity::class.java)ActivityScenario.launch<MainActivity>(intent).use { scenario ->- var model: AppStore? = null- scenario.onActivity { model = ViewModelProvider(it)[AppStore::class.java] }- val store = requireNotNull(model)- withTimeout(35_000) { store.state.first { !it.loading && it.contextId == "local" && it.selectedBot == bot } }- assertNull(store.state.value.account.userId)- assertNull(store.state.value.error)+ var model: AccountStore? = null+ scenario.onActivity { model = accountStore(it) }+ val accounts = requireNotNull(model)+ val store = withTimeout(35_000) {+ accounts.state.first { !it.loading && it.contextId == "local" }+ accounts.stores.first { stores -> stores.any { it.id == computer.id } }.single { it.id == computer.id }+ }+ withTimeout(35_000) { store.state.first { !it.loading && it.selectedBot == bot } }+ assertNull(accounts.state.value.account.userId)+ assertNull(accounts.state.value.error)suspend fun reject(uri: Uri, message: String) {- instrumentation.runOnMainSync { store.openBot(null); store.clearError(); store.openLink(uri) }- withTimeout(15_000) { store.state.first { it.error?.contains(message) == true } }+ instrumentation.runOnMainSync { accounts.openBot(null); accounts.clearError(); accounts.openLink(uri) }+ withTimeout(15_000) { accounts.state.first { it.error?.contains(message) == true } }assertNull(store.state.value.selectedBot)- assertEquals("local", store.state.value.contextId)- assertNull(store.state.value.account.userId)+ assertEquals("local", accounts.state.value.contextId)+ assertNull(accounts.state.value.account.userId)}reject(link(scope = "a".repeat(64)), "Switch to the account")reject(link(cid = "AAAAAAAAAAAAAAAAAAAAAA"), "computer is no longer paired")@@ -76,15 +79,17 @@ class LiveRoutingTest {compose.onNodeWithContentDescription("Usage limits").performClick()val usage = hasText("Usage") and isHeading()compose.waitUntil(10_000) { compose.onAllNodes(usage).fetchSemanticsNodes().size == 1 }- instrumentation.runOnMainSync { store.openLink(link(id = parent)) }- withTimeout(10_000) { store.state.first { it.selectedBot == parent && it.error == null } }+ instrumentation.runOnMainSync { accounts.openLink(link(id = parent)) }+ withTimeout(10_000) { store.state.first { it.selectedBot == parent } }+ assertNull(accounts.state.value.error)compose.onNode(chatTitle).assertIsDisplayed()// Recreating the Activity must retain the current navigation, not replay its original intent.scenario.recreate()scenario.onActivity { activity ->- val retained = ViewModelProvider(activity)[AppStore::class.java]- assertSame(store, retained)- assertEquals(parent, retained.state.value.selectedBot)+ val retained = accountStore(activity)+ assertSame(accounts, retained)+ assertSame(store, retained.store(computer.id))+ assertEquals(parent, store.state.value.selectedBot)}}} finally { channel.call("deleteBot", body("botId" to bot)); metadata.delete() }diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveSettingsTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveSettingsTest.ktindex 4ea58bee..ef60451e 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveSettingsTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveSettingsTest.kt@@ -4,7 +4,6 @@ import android.os.Buildimport android.view.KeyEventimport androidx.compose.ui.test.*import androidx.compose.ui.test.junit4.createAndroidComposeRule-import androidx.lifecycle.ViewModelProviderimport androidx.test.platform.app.InstrumentationRegistryimport com.codync.android.core.*import kotlinx.coroutines.runBlocking@@ -38,7 +37,7 @@ class LiveSettingsTest {clone = bot.idval listingResponse = runBlocking { channel.call("listDirs", body("path" to "/tmp")) }val listing = WireJson.decodeFromJsonElement<DirListing>(listingResponse)- val store = ViewModelProvider(compose.activity)[AppStore::class.java]+ val store = compose.computerStore()compose.waitUntil(30_000) { !store.state.value.loading && store.state.value.bots.any { it.id == bot.id } && store.state.value.actualConnection is LinkState.Ready }compose.runOnUiThread { store.openBot(null) }compose.rosterAction(bot.name, "Edit profile")diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveTerminalTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveTerminalTest.ktindex 44780772..e01fd0b1 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveTerminalTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveTerminalTest.kt@@ -5,7 +5,6 @@ import android.view.ViewGroupimport android.webkit.WebViewimport androidx.compose.ui.test.*import androidx.compose.ui.test.junit4.createAndroidComposeRule-import androidx.lifecycle.ViewModelProviderimport androidx.test.platform.app.InstrumentationRegistryimport com.codync.android.core.*import kotlinx.coroutines.*@@ -77,7 +76,7 @@ class LiveTerminalTest {} } }} }try {- val store = ViewModelProvider(compose.activity)[AppStore::class.java]+ val store = compose.computerStore()compose.waitUntil(30_000) { !store.state.value.loading && store.state.value.actualConnection is LinkState.Ready }compose.runOnUiThread { store.openBot(null); store.refreshBackends() }compose.waitUntil(15_000) { store.state.value.hello?.get("backends")?.jsonArray?.any { it.jsonObject["id"]?.jsonPrimitive?.content == "android-setup-fixture" } == true }diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveVoiceSpeechTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveVoiceSpeechTest.ktindex c4376c9a..f01b0635 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveVoiceSpeechTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveVoiceSpeechTest.kt@@ -4,7 +4,6 @@ import android.os.Buildimport androidx.compose.ui.test.*import androidx.compose.ui.test.junit4.createAndroidComposeRuleimport androidx.lifecycle.Lifecycle-import androidx.lifecycle.ViewModelProviderimport androidx.test.platform.app.InstrumentationRegistryimport com.codync.android.core.*import java.io.File@@ -44,7 +43,7 @@ class LiveVoiceSpeechTest {val created = runBlocking { channel.call("createBot", draft) }val id = created.jsonObject.getValue("bot").jsonObject.getValue("id").jsonPrimitive.contentbotId = id- val store = ViewModelProvider(compose.activity)[AppStore::class.java]; model = store+ val store = compose.computerStore(); model = storecompose.waitUntil(30_000) { store.state.value.bots.any { it.id == id } && store.state.value.actualConnection is LinkState.Ready }compose.runOnUiThread { store.voiceSettings(VoiceSettings(2_500)); store.openBot(id) }compose.onNodeWithContentDescription("Call").performClick()diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveVoiceTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveVoiceTest.ktindex 19ebae0a..fb5f7dc8 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveVoiceTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/LiveVoiceTest.kt@@ -4,7 +4,6 @@ import android.app.NotificationManagerimport androidx.compose.ui.test.*import androidx.compose.ui.test.junit4.createAndroidComposeRuleimport androidx.lifecycle.Lifecycle-import androidx.lifecycle.ViewModelProviderimport androidx.test.platform.app.InstrumentationRegistryimport com.codync.android.core.*import kotlinx.coroutines.*@@ -39,7 +38,7 @@ class LiveVoiceTest {val created = runBlocking { channel.call("createBot", draft) }val id = created.jsonObject.getValue("bot").jsonObject.getValue("id").jsonPrimitive.contentbotId = id- val store = ViewModelProvider(compose.activity)[AppStore::class.java]; model = store+ val store = compose.computerStore(); model = storecompose.waitUntil(30_000) { store.state.value.bots.any { it.id == id } && store.state.value.actualConnection is LinkState.Ready }compose.runOnUiThread { store.openBot(id) }compose.onNodeWithContentDescription("Call").performClick()diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/MessageActionsMenuTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/MessageActionsMenuTest.ktindex 70aa64ed..3d90e388 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/MessageActionsMenuTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/MessageActionsMenuTest.kt@@ -12,7 +12,6 @@ import androidx.compose.ui.platform.UriHandlerimport androidx.compose.ui.test.*import androidx.compose.ui.test.junit4.createComposeRuleimport androidx.compose.ui.unit.dp-import androidx.lifecycle.viewmodel.compose.viewModelimport androidx.test.platform.app.InstrumentationRegistryimport com.codync.android.core.*import com.codync.android.design.MenuItem@@ -28,6 +27,7 @@ import org.junit.Test/** A message's long-press menu (`Modifier.contextActions`): reactions over copy, reply and trace. */class MessageActionsMenuTest {@get:Rule val compose = createComposeRule()+ private val store = previewStore()private fun back() = InstrumentationRegistry.getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK)@Before fun isolatedEmulatorOnly() { assumeTrue(Build.PRODUCT.startsWith("sdk")) }@@ -36,10 +36,10 @@ class MessageActionsMenuTest {val bot = Bot("message-preview", "Scout")val text = "Checked the connection. The saved route works."val entry = Entry("reply", 1, bot.id, rev = 1, kind = "agent", data = buildJsonObject { put("text", text); put("final", true) })- val initial = AppState(loading = false, selectedBot = bot.id, bots = listOf(bot),+ val initial = AppState(previewComputer, loading = false, selectedBot = bot.id, bots = listOf(bot),connection = LinkState.Ready(HostRoute.Direct), historyComplete = setOf(bot.id), entries = listOf(entry))val state = mutableStateOf(initial)- compose.setContent { Hosted { ChatScreen(state.value, viewModel(), {}) } }+ compose.setContent { Hosted { ChatScreen(state.value, store, {}) } }val bubble = compose.onNode(hasText(text, substring = true) and hasClickAction())bubble.performTouchInput { longClick() }compose.onNodeWithContentDescription("👍").assertIsDisplayed().assertIsNotSelected()@@ -67,9 +67,9 @@ class MessageActionsMenuTest {val quoted = Entry("quoted", 2, bot.id, rev = 2, kind = "user", data = buildJsonObject {put("text", "Ship it"); put("replyTo", buildJsonObject { put("id", reply.id); put("author", bot.id); put("text", text) })})- val state = AppState(loading = false, selectedBot = bot.id, bots = listOf(bot), connection = LinkState.Ready(HostRoute.Direct),+ val state = AppState(previewComputer, loading = false, selectedBot = bot.id, bots = listOf(bot), connection = LinkState.Ready(HostRoute.Direct),historyComplete = setOf(bot.id), entries = listOf(reply, quoted))- compose.setContent { Hosted { ChatScreen(state, viewModel(), {}) } }+ compose.setContent { Hosted { ChatScreen(state, store, {}) } }// The sent reply shows what it quotes.compose.onNodeWithText("“$text”").assertIsDisplayed()compose.onNode(hasText(text) and hasClickAction()).performTouchInput { longClick() }@@ -80,7 +80,7 @@ class MessageActionsMenuTest {compose.onAllNodesWithText("“$text”").assertCountEquals(1)compose.onNodeWithContentDescription("Cancel reply").assertDoesNotExist()// An older host can't quote: no Reply.- compose.setContent { Hosted { ChatScreen(state.copy(hello = buildJsonObject { put("version", "2.20.0") }), viewModel(), {}) } }+ compose.setContent { Hosted { ChatScreen(state.copy(hello = buildJsonObject { put("version", "2.20.0") }), store, {}) } }compose.onNode(hasText(text) and hasClickAction()).performTouchInput { longClick() }compose.onNodeWithText("Copy").assertIsDisplayed()compose.onNodeWithText("Reply").assertDoesNotExist()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.ktindex bb493254..cdf844f6 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@@ -1,16 +1,51 @@package com.codync.android+import android.app.Application+import androidx.activity.ComponentActivityimport androidx.compose.runtime.Composableimport androidx.compose.ui.test.*+import androidx.compose.ui.test.junit4.AndroidComposeTestRuleimport androidx.compose.ui.test.junit4.ComposeTestRule+import androidx.test.platform.app.InstrumentationRegistry+import com.codync.android.core.Computerimport com.codync.android.design.CodyncThemeimport com.codync.android.design.OverlayRoot+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlockinginternal fun SemanticsNodeInteractionsProvider.onControl(label: String) = onNode(hasText(label) or hasContentDescription(label))/** A screen as the app hosts it: the theme, and the overlay its sheets, menus and dialogs draw in. */@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")++/** 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 {+ val application = InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as Application+ return AppStore(application, LocalStore(application), computer, "local", 0, SupervisorJob(), {}, {})+}++/**+ * Runs [block] with the account store the activity's screens get, [computers] opened in it beside the account's own,+ * so a screen rendered on its own finds a store for each computer it shows. They aren't saved, nothing links them+ * while no activity is in the foreground, and closing them afterwards deletes the mirrors they opened.+ */+internal fun AndroidComposeTestRule<*, out ComponentActivity>.withPreviewAccounts(vararg computers: Computer, block: (AccountStore) -> Unit) {+ val activity = activity+ val accounts = runBlocking(Dispatchers.Main) {+ accountStore(activity).also { accounts ->+ accounts.state.first { !it.loading }+ computers.forEach { accounts.open(it) }+ }+ }+ try { block(accounts) }+ finally { runBlocking(Dispatchers.Main) { computers.forEach { accounts.close(it.id) } } }+}+/** The roster header's computers menu ("Computers, 1 connected. Filter conversations"). */internal fun ComposeTestRule.computerAction(label: String) {onNodeWithContentDescription("Computers,", substring = true).performClick()diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/OnboardingTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/OnboardingTest.ktindex b7e19c3b..33501c1c 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/OnboardingTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/OnboardingTest.kt@@ -12,7 +12,7 @@ class OnboardingTest {@get:Rule val compose = createComposeRule()@Test fun welcomeLeadsToInstallAndBackReturnsToWelcome() {- compose.setContent { Hosted { CodyncApp(AppState(loading = false), viewModel()) } }+ compose.setContent { Hosted { CodyncApp(AccountContext(loading = false), emptyMap(), viewModel()) } }compose.onNodeWithText("Your coding agents", substring = true).assertIsDisplayed()compose.onNodeWithText("Get started").performClick()compose.onNodeWithText("Install Codync", substring = true).assertIsDisplayed()@@ -23,7 +23,7 @@ class OnboardingTest {@Test fun installStepsFollowTheComputerAndScanKeepsTheChoice() {var skipped = false- compose.setContent { Hosted { PairingView(AppState(loading = false), viewModel(), onSkip = { skipped = true }) } }+ compose.setContent { Hosted { PairingView(AccountContext(loading = false), viewModel(), onSkip = { skipped = true }) } }compose.onNodeWithText("Mac").assertIsSelected()compose.onNodeWithText("brew install --cask leepokai/codync/codync").performScrollTo().assertIsDisplayed()compose.onNodeWithText("Linux").performClick().assertIsSelected()@@ -46,7 +46,7 @@ class OnboardingTest {}@Test fun macPairingPointsToTheMenuBarApp() {- compose.setContent { Hosted { PairingView(AppState(loading = false), viewModel()) } }+ compose.setContent { Hosted { PairingView(AccountContext(loading = false), viewModel()) } }compose.onNodeWithText("Continue").performClick()compose.onNodeWithText("On your Mac, click Codync in the menu bar, then Pair iPhone. The same code pairs this phone.").assertIsDisplayed()compose.onNodeWithText("codync-host pair").assertDoesNotExist()diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/PushTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/PushTest.ktindex f58e08f7..f3f19152 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/PushTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/PushTest.kt@@ -71,7 +71,7 @@ class PushTest {@Test fun delegatedTasksRejectStaleWrongGenerationAndPostCompletionUpdates() {val local = LocalStore(context, "task-test-${UUID.randomUUID()}")try {- val feed = TaskFeed(local.directory)+ val feed = TaskFeed(local.directory, "computer")val watch = feed.start(Bot("bot", "Reviewer", rev = 1))val now = System.currentTimeMillis() / 1000val data = mapOf("taskId" to watch.taskId, "status" to "needsInput", "timestamp" to now.toString(), "staleDate" to (now + 900).toString(), "event" to "update")@@ -92,7 +92,7 @@ class PushTest {@Test fun aTaskAlreadyRunningWhenItsSendIsAcknowledgedCanFinishLocally() {val local = LocalStore(context, "task-running-test-${UUID.randomUUID()}")try {- val feed = TaskFeed(local.directory)+ val feed = TaskFeed(local.directory, "computer")val started = feed.start(Bot("bot", "Reviewer", status = "needsInput", rev = 5))assertTrue(started.seenRunning)assertEquals("needsInput", started.status)@@ -103,7 +103,7 @@ class PushTest {@Test fun delegatedTaskMarkersAreBoundedAndAnIdleAcknowledgementCannotFinishThem() {val local = LocalStore(context, "task-limit-test-${UUID.randomUUID()}")try {- val feed = TaskFeed(local.directory)+ val feed = TaskFeed(local.directory, "computer")repeat(24) { feed.start(Bot("bot-$it", "Bot", rev = 1)) }assertEquals(16, feed.all().size)assertNull(feed.local(Bot("bot-23", "Bot", status = "idle", rev = 2)))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.ktindex 1fabef08..67811246 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@@ -8,8 +8,8 @@ import androidx.compose.runtime.mutableStateOfimport androidx.compose.ui.platform.LocalDensityimport androidx.compose.ui.unit.Densityimport androidx.compose.ui.test.*-import androidx.compose.ui.test.junit4.createComposeRule-import androidx.lifecycle.viewmodel.compose.viewModel+import androidx.activity.ComponentActivity+import androidx.compose.ui.test.junit4.createAndroidComposeRuleimport androidx.test.platform.app.InstrumentationRegistryimport com.codync.android.core.*import com.codync.android.design.CodyncSheet@@ -22,18 +22,19 @@ import java.io.File/** The real root's sheets and Android Back dispatch, on read-only fixtures. */class ScreenPresentationTest {- @get:Rule val compose = createComposeRule()+ @get:Rule val compose = createAndroidComposeRule<ComponentActivity>()private val bot = Bot("presentation-fixture", "Scout")- private fun fixture() = AppState(contextId = "presentation-fixture", loading = false,- setupComplete = true, rosterLoaded = true, bots = listOf(bot),- computers = listOf(Computer("fixture-computer", "Fixture computer", "fixture-key")),+ private val computer = Computer("fixture-computer", "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),account = AccountState(ready = true, configured = true, multiple = true, userId = "fixture-account",accounts = listOf(SavedAccount("fixture-account", "fixture-session", "[email protected]", null))))@Before fun isolatedEmulatorOnly() { assumeTrue(Build.PRODUCT.startsWith("sdk")) }- @Test fun settingsIsATabAndBackClosesComputerManagementOneLayerAtATime() {- compose.setContent { Hosted { CodyncApp(fixture(), viewModel()) } }+ @Test fun settingsIsATabAndBackClosesComputerManagementOneLayerAtATime() = compose.withPreviewAccounts(computer) { accounts ->+ compose.setContent { Hosted { CodyncApp(fixture(), computers, accounts) } }compose.onNodeWithContentDescription("Switch account").performClick()compose.onNodeWithText("Account").assertIsDisplayed()snapshot("account-sheet")@@ -56,9 +57,9 @@ class ScreenPresentationTest {compose.onNodeWithText(bot.name).assertIsDisplayed()}- @Test fun closingTheEditorDropsItsDraftAndANewGenerationRetiresIt() {+ @Test fun closingTheEditorDropsItsDraftAndANewGenerationRetiresIt() = compose.withPreviewAccounts(computer) { accounts ->val state = mutableStateOf(fixture())- compose.setContent { Hosted { CodyncApp(state.value, viewModel()) } }+ compose.setContent { Hosted { CodyncApp(state.value, computers, accounts) } }compose.rosterAction(bot.name, "Edit profile")compose.onNodeWithContentDescription("Save").assertIsNotEnabled()compose.onNode(hasSetTextAction() and hasText(bot.name)).performTextReplacement("Discard this draft")@@ -71,8 +72,8 @@ class ScreenPresentationTest {compose.onNodeWithContentDescription("Save").assertDoesNotExist()}- @Test fun aBotsTouchAndHoldMenuHasNoNewSession() {- compose.setContent { Hosted { CodyncApp(fixture(), viewModel()) } }+ @Test fun aBotsTouchAndHoldMenuHasNoNewSession() = compose.withPreviewAccounts(computer) { accounts ->+ compose.setContent { Hosted { CodyncApp(fixture(), computers, accounts) } }compose.rosterActions(bot.name)compose.onNodeWithText("Edit profile").assertIsDisplayed()compose.onNodeWithText("New session").assertDoesNotExist()@@ -80,10 +81,11 @@ class ScreenPresentationTest {@Test fun largeTextKeepsSettingsActionsAndCompactOptionsWithinTheSheet() {val draft = BotDraft(id = bot.id, name = bot.name, cwd = "/projects/A-long-project-name")+ val store = previewStore(computer)compose.setContent {val density = LocalDensity.currentCompositionLocalProvider(LocalDensity provides Density(density.density, 1.5f)) {- Hosted { CodyncSheet(true, {}) { BotEditor(fixture(), draft, viewModel()) } }+ Hosted { CodyncSheet(true, {}) { BotEditor(state, draft, store) } }}}val title = compose.onNodeWithText("Settings").assertIsDisplayed().fetchSemanticsNode().boundsInRootdiff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/UsageScreenTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/UsageScreenTest.ktindex baf06501..15f56344 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/UsageScreenTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/UsageScreenTest.kt@@ -16,8 +16,7 @@ class UsageScreenTest {@Test fun unavailableWindowsAndOldReportsNeverBecomeZeroUsage() {val raw = WireJson.parseToJsonElement("""{"providers":[{"id":"future","name":"Future provider","source":"future-source","updatedAt":1,"windows":[{"id":"month","label":"Monthly"}]}]}""")- val state = mutableStateOf(AppState(loading = false, setupComplete = true,- computers = listOf(Computer("fixture", "Acceptance computer", "fixture")), usage = raw.jsonObject,+ val state = mutableStateOf(AppState(Computer("fixture", "Acceptance computer", "fixture"), loading = false, usage = raw.jsonObject,actualConnection = LinkState.ComputerOffline(null)))val refreshes = mutableListOf<Boolean>()var closed = false@@ -44,11 +43,11 @@ class UsageScreenTest {}@Test fun usageExplainsWhenThereIsNoComputerOrNoReportYet() {- val state = mutableStateOf(AppState(loading = false))+ val state = mutableStateOf<AppState?>(null)compose.setContent { Hosted { UsageScreen(state.value, {}, {}) } }compose.onNodeWithText("No computer yet").assertIsDisplayed()compose.onNodeWithText("Usage shows up once a computer is connected.").assertIsDisplayed()- compose.runOnUiThread { state.value = state.value.copy(computers = listOf(Computer("fixture", "Acceptance computer", "fixture"))) }+ compose.runOnUiThread { state.value = AppState(Computer("fixture", "Acceptance computer", "fixture"), loading = false) }compose.onNodeWithText("No usage yet").assertIsDisplayed()compose.onNodeWithText("Your computer reads plan limits from the agents installed on it.").assertIsDisplayed()}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.ktindex fe5b0750..19e9603b 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@@ -14,7 +14,7 @@ import kotlinx.serialization.json.putclass WidgetStoreTest {@Test fun reconnectingDoesNotFreshenCachedActivityUntilTheMirrorCatchesUp() {- val cached = AppState(loading = false, rosterLoaded = true, mirrorRevision = 9,+ val cached = AppState(previewComputer, loading = false, rosterLoaded = true, mirrorRevision = 9,actualConnection = LinkState.Ready(HostRoute.Direct), hello = buildJsonObject { put("rev", 10) })assertFalse(cached.widgetBotsCurrent)val caughtUp = cached.copy(mirrorRevision = 10)@@ -36,14 +36,14 @@ class WidgetStoreTest {try {first.saveComputers(listOf(computer)); second.saveComputers(listOf(computer))val a = WidgetStore.activate(context, first.contextId)- assertTrue(WidgetStore.publish(context, a, computer, listOf(Bot("shared", "Account A", lastMessage = "Private chat")), UsageReport(), true, false))+ assertTrue(WidgetStore.publish(context, a, listOf(WidgetComputer(computer, listOf(Bot("shared", "Account A", lastMessage = "Private chat")), true)), computer, UsageReport(), false))val b = WidgetStore.activate(context, second.contextId)- assertTrue(WidgetStore.publish(context, b, computer, listOf(Bot("shared", "Account B")), UsageReport(), true, false))- assertFalse(WidgetStore.publish(context, a, computer, listOf(Bot("shared", "Late Account A")), UsageReport(), true, false))+ assertTrue(WidgetStore.publish(context, b, listOf(WidgetComputer(computer, listOf(Bot("shared", "Account B")), true)), computer, UsageReport(), false))+ assertFalse(WidgetStore.publish(context, a, listOf(WidgetComputer(computer, listOf(Bot("shared", "Late Account A")), true)), computer, UsageReport(), false))assertEquals("Account B", WidgetStore.feed(context).bots.single().name)val revision = WidgetStore.changes.value- WidgetStore.publish(context, b, computer, listOf(Bot("shared", "Newer Account B")), UsageReport(), true, false)- assertFalse(WidgetStore.publish(context, b, computer, listOf(Bot("shared", "Old background B")), UsageReport(), true, false,+ WidgetStore.publish(context, b, listOf(WidgetComputer(computer, listOf(Bot("shared", "Newer Account B")), true)), computer, UsageReport(), false)+ assertFalse(WidgetStore.publish(context, b, listOf(WidgetComputer(computer, listOf(Bot("shared", "Old background B")), true)), computer, UsageReport(), false,expectedRevision = revision))assertEquals("Newer Account B", WidgetStore.feed(context).bots.single().name)val persisted = File(second.directory, "widget-feed.json").readText()diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/WidgetSystemTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/WidgetSystemTest.ktindex 30d4d153..929206d5 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/WidgetSystemTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/WidgetSystemTest.kt@@ -17,7 +17,6 @@ import androidx.compose.ui.test.assertIsDisplayedimport androidx.compose.ui.test.hasTextimport androidx.compose.ui.test.isHeadingimport androidx.glance.appwidget.GlanceAppWidgetManager-import androidx.lifecycle.ViewModelProviderimport androidx.core.view.drawToBitmapimport androidx.test.platform.app.InstrumentationRegistryimport com.codync.android.core.*@@ -39,8 +38,8 @@ class WidgetSystemTest {assumeTrue(Build.PRODUCT.startsWith("sdk"))val context = instrumentation.targetContextassertNull(PushPreferences.activeUser(context))- val store = ViewModelProvider(compose.activity)[AppStore::class.java]- compose.waitUntil(30_000) { !store.state.value.loading }+ val accounts = accountStore(compose.activity)+ compose.waitUntil(30_000) { !accounts.state.value.loading }val computer = LocalStore(context).computers().single()requireFixtureHost(computer.id)val originalFile = AtomicFile(File(context.noBackupFilesDir, "widget-owner.json"))@@ -55,7 +54,8 @@ class WidgetSystemTest {val owner = WidgetStore.activate(context, local.contextId)val usage = UsageReport(listOf(UsageProvider("claude", "Claude", listOf(UsageWindow("session", "Session", 97.0))),UsageProvider("codex", "Codex", listOf(UsageWindow("daily", "Daily", 24.0)))))- WidgetStore.publish(context, owner, computer, (1..6).map { Bot("sample-$it", "Widget bot $it", status = if (it == 1) "needsInput" else "working") }, usage, true, true)+ WidgetStore.publish(context, owner, listOf(WidgetComputer(computer, (1..6).map { Bot("sample-$it", "Widget bot $it", status = if (it == 1) "needsInput" else "working") }, true)),+ computer, usage, true)instrumentation.runOnMainSync {container = FrameLayout(compose.activity).apply { setPadding(16, 16, 16, 16) }compose.activity.setContentView(container)@@ -118,7 +118,8 @@ class WidgetSystemTest {assumeTrue(Build.PRODUCT.startsWith("sdk"))val context = instrumentation.targetContextassertNull(PushPreferences.activeUser(context))- val store = ViewModelProvider(compose.activity)[AppStore::class.java]+ val accounts = accountStore(compose.activity)+ val store = compose.computerStore(accounts)compose.waitUntil(30_000) { !store.state.value.loading && store.state.value.rosterLoaded }requireFixtureHost(LocalStore(context).computers().single().id)val started = System.currentTimeMillis()@@ -130,8 +131,8 @@ class WidgetSystemTest {assertTrue(feed.bots.any { it.name == "Android chat acceptance" })assertTrue(feed.botsAt > System.currentTimeMillis() - 30_000)val link = requireNotNull(widgetIntent(context, feed, usage = true).data)- compose.runOnUiThread { store.openLink(link) }- compose.waitUntil(10_000) { store.state.value.navigationPage == LinkPage.Usage && store.state.value.selectedBot == null }+ compose.runOnUiThread { accounts.openLink(link) }+ compose.waitUntil(10_000) { accounts.state.value.navigationPage == LinkPage.Usage && store.state.value.selectedBot == null }// The usage sheet's title (it refreshes on its own and on pull).val refresh = hasText("Usage") and isHeading()compose.waitUntil(10_000) { compose.onAllNodes(refresh).fetchSemanticsNodes().size == 1 }@@ -139,12 +140,12 @@ class WidgetSystemTest {compose.activityRule.scenario.recreate()compose.waitUntil(10_000) { compose.onAllNodes(refresh).fetchSemanticsNodes().size == 1 }compose.onNode(refresh).assertIsDisplayed()- val request = store.state.value.navigationRequest+ val request = accounts.state.value.navigationRequestval foreign = Uri.Builder().scheme("codync").authority("usage").appendQueryParameter("scope", "a".repeat(64)).appendQueryParameter("computer", feed.computerId).build()- compose.runOnUiThread { store.openLink(foreign) }- compose.waitUntil(10_000) { store.state.value.error?.contains("Switch to the account") == true }- assertEquals(request, store.state.value.navigationRequest)+ compose.runOnUiThread { accounts.openLink(foreign) }+ compose.waitUntil(10_000) { accounts.state.value.error?.contains("Switch to the account") == true }+ assertEquals(request, accounts.state.value.navigationRequest)}private fun texts(root: View): List<String> {diff --git a/apps/android/app/src/main/AndroidManifest.xml b/apps/android/app/src/main/AndroidManifest.xmlindex dde25203..b77df9fc 100644--- a/apps/android/app/src/main/AndroidManifest.xml+++ b/apps/android/app/src/main/AndroidManifest.xml@@ -12,7 +12,11 @@<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" /><uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" /><uses-feature android:name="android.hardware.microphone" android:required="false" />- <queries><intent><action android:name="android.intent.action.TTS_SERVICE" /></intent></queries>+ <queries>+ <intent><action android:name="android.intent.action.TTS_SERVICE" /></intent>+ <!-- Dictation's recognizer (SpeechRecognizer needs to see the phone's recognition service). -->+ <intent><action android:name="android.speech.RecognitionService" /></intent>+ </queries><uses-feature android:name="android.hardware.camera" android:required="false" /><uses-feature android:name="android.hardware.camera.any" android:required="false" /><uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AccessRequestView.kt b/apps/android/app/src/main/kotlin/com/codync/android/AccessRequestView.ktindex 01f03b6b..52f9990f 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AccessRequestView.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AccessRequestView.kt@@ -34,31 +34,40 @@ import com.kyant.shapes.RoundedRectangleimport com.codync.android.design.*import kotlinx.coroutines.delay-private enum class AccessPhase { Renew, Asking, Code, Approved, Ended }+/** `Failed`: the request didn't reach the computer (try again); `Ended`: the computer showed a code but didn't approve it (ask again). */+private enum class AccessPhase { Renew, Asking, Code, Approved, Failed, Ended }/** Asks an account computer for this phone: the code to check on it, until it answers (iOS `AccessRequestView`). */-@Composable internal fun AccessRequestView(state: AppState, store: AppStore, computer: CloudComputer) {+@Composable internal fun AccessRequestView(state: AccountContext, store: AccountStore, computer: CloudComputer) {val dismiss = LocalDismissModal.current- val ticket = state.access?.takeIf { it.computerId == computer.computerId }+ val ticket = state.access[computer.computerId]var requestId by remember { mutableStateOf(ticket?.requestId) }var confirmRenewal by remember { mutableStateOf(computer.isGranted && ticket == null) }var renewRequest by remember { mutableStateOf(false) }val approved = requestId != null && state.approvedAccess[computer.computerId] == requestId- LaunchedEffect(ticket?.requestId) { ticket?.requestId?.let { requestId = it; renewRequest = false } }- // The request ran and is over without an approval: denied, expired, or it failed.- var asked by remember { mutableStateOf("access" in state.busy) }+ // Whether this request got as far as a code on the computer (iOS `sawTicket`).+ var sawTicket by remember { mutableStateOf(ticket != null) }+ LaunchedEffect(ticket?.requestId) { ticket?.requestId?.let { requestId = it; renewRequest = false; sawTicket = true } }+ // The request ran and is over without an approval: denied or expired after its code, or it failed before one.+ val asking = "access:${computer.computerId}" in state.busy+ var asked by remember { mutableStateOf(asking) }var ended by remember { mutableStateOf<String?>(null) }- val asking = "access" in state.busy+ var failed by remember { mutableStateOf<String?>(null) }LaunchedEffect(Unit) { if (!asking && !approved && ticket == null && !confirmRenewal) store.requestAccess(computer) }LaunchedEffect(asking, approved) {if (asking) asked = true- else if (asked && !approved) { ended = state.error ?: "${computer.name} didn't approve this request."; store.clearError(); asked = false }+ else if (asked && !approved) {+ if (sawTicket) ended = state.error ?: "${computer.name} didn't approve this request."+ else failed = state.error ?: "Something went wrong"+ store.clearError(); asked = false+ }}LaunchedEffect(approved) { if (approved) { delay(1000); dismiss() } }val phase = when {confirmRenewal -> AccessPhase.Renewapproved -> AccessPhase.Approvedticket != null -> AccessPhase.Code+ failed != null -> AccessPhase.Failedended != null -> AccessPhase.Endedelse -> AccessPhase.Asking}@@ -93,12 +102,16 @@ private enum class AccessPhase { Renew, Asking, Code, Approved, Ended }Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {Spinner()Text("Waiting for approval…", style = Type.subheadline, color = Palette.secondary)- IconButton("Cancel request", "xmark.circle.fill") { store.cancelAccess(); dismiss() }+ IconButton("Cancel request", "xmark.circle.fill") { store.cancelAccess(computer.computerId); dismiss() }}}+ AccessPhase.Failed -> {+ Text(failed.orEmpty(), style = Type.body, color = Palette.danger, textAlign = TextAlign.Center)+ SecondaryButton("Try again") { failed = null; store.requestAccess(computer, renew = renewRequest) }+ }AccessPhase.Ended -> {Text(ended.orEmpty(), style = Type.body, color = Palette.secondary, textAlign = TextAlign.Center)- SecondaryButton("Ask again") { ended = null; store.requestAccess(computer, renew = renewRequest) }+ SecondaryButton("Ask again") { ended = null; sawTicket = false; store.requestAccess(computer, renew = renewRequest) }}AccessPhase.Asking -> Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(10.dp)) {Spinner()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.ktnew file mode 100644index 00000000..f40dcac2--- /dev/null+++ b/apps/android/app/src/main/kotlin/com/codync/android/AccountStore.kt@@ -0,0 +1,272 @@+package com.codync.android++import android.app.Application+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.codync.android.core.*+import java.util.UUID+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.coroutines.*+import kotlinx.coroutines.flow.*++/**+ * The ViewModel the UI talks to (iOS `AccountStore`): the active account, its computers with one+ * [AppStore] each, and the one writer of [AccountContext]. This file holds the account context's+ * lifecycle (load, retire) and the computers' list; signing in, pairing, access and links are+ * `AccountStore` extensions in the `AccountStore*.kt` files beside it.+ */+class AccountStore(application: Application) : AndroidViewModel(application) {+ internal val activityOwnerId: String = UUID.randomUUID().toString()+ internal var local = LocalStore(application)+ private var contextJob = SupervisorJob(viewModelScope.coroutineContext[Job])+ internal var contextScope = CoroutineScope(contextJob + Dispatchers.Main.immediate)+ internal val transitions = Mutex()+ /** One change to the saved computers at a time. */+ private val computerChanges = Mutex()+ internal var cloud: CloudClient? = null+ private var sessionJob: Job? = null+ internal var linkJob: Job? = null+ internal var pairingJob: Job? = null+ internal val actions = mutableMapOf<String, Job>()+ internal val mutableState = MutableStateFlow(AccountContext())+ val state = mutableState.asStateFlow()+ private val mutableStores = MutableStateFlow<List<AppStore>>(emptyList())+ /** One store per computer, in the order the computers show. */+ val stores = mutableStores.asStateFlow()+ /** Every computer's state, by computer ID. */+ @OptIn(ExperimentalCoroutinesApi::class)+ val computerStates: StateFlow<Map<String, AppState>> = mutableStores.flatMapLatest { stores ->+ if (stores.isEmpty()) flowOf(emptyMap()) else combine(stores.map { it.state }) { states -> states.associateBy { it.computer.id } }+ }.stateIn(viewModelScope, SharingStarted.Eagerly, emptyMap())+ internal var foreground = false+ internal var widgetOwner: WidgetOwner? = null++ init {+ viewModelScope.launch {+ withContext(Dispatchers.IO) { PushPreferences.splitSwitch(getApplication()) }+ transitions.withLock { loadContext(null) }+ NativeAccounts.observe(viewModelScope) { account ->+ mutableState.update { it.copy(account = account) }+ if (account.ready) transitions.withLock {+ // Read the latest state after a concurrent logout/reset finishes.+ val current = state.value.account+ val desired = current.userId ?: "local"+ if (desired != local.contextId) {+ retireContext()+ loadContext(current.userId)+ } else if (cloud == null && current.userId != null) {+ configureCloud(current.userId)+ refreshCloud()+ }+ }+ }+ }+ }++ fun store(id: String?): AppStore? = id?.let { wanted -> stores.value.firstOrNull { it.id == wanted } }++ internal suspend fun loadContext(userId: String?) {+ try {+ WidgetRefreshWorker.stop(getApplication())+ local = LocalStore(getApplication(), userId ?: "local")+ widgetOwner = withContext(Dispatchers.IO) { WidgetStore.activate(getApplication(), local.contextId) }+ PushDelivery.activate(getApplication(), userId)+ val computers = withContext(Dispatchers.IO) { local.computers() }+ val complete = withContext(Dispatchers.IO) { local.setupComplete() }+ val last = withContext(Dispatchers.IO) { local.lastComputer() }+ 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)+ // 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)+ mutableState.update { it.copy(loading = false) }+ observeWidgets(requireNotNull(widgetOwner))+ refreshCloud()+ } catch (error: CancellationException) { throw error }+ catch (error: Exception) { showError(error) }+ }++ private suspend fun configureCloud(userId: String) {+ val identity = withContext(Dispatchers.IO) { local.identity() }+ cloud = CloudClient(BuildConfig.CLOUD_URL, identity) { NativeAccounts.token(userId) }+ }++ /** Join every writer before closing a context's databases or replacing its identity. */+ internal suspend fun retireContext() = withContext(NonCancellable) {+ mutableState.update { it.copy(loading = true) }+ withContext(Dispatchers.IO) { WidgetStore.retire(getApplication(), widgetOwner) }+ widgetOwner = null+ WidgetRefreshWorker.stop(getApplication())+ try { CodyncWidgets.update(getApplication()) } catch (_: Exception) { }+ val writers = actions.values.toList()+ writers.forEach { it.cancel() }; writers.forEach { it.join() }+ PushDelivery.retire(getApplication())+ val retiring = stores.value+ mutableStores.value = emptyList()+ retiring.forEach { it.retire() }+ contextJob.cancelAndJoin()+ AccountImages.retire()+ pairingJob = null+ actions.clear(); cloud = null+ withContext(Dispatchers.IO) { ConnectorOAuthBook(local.directory).clear() }+ contextJob = SupervisorJob(viewModelScope.coroutineContext[Job])+ contextScope = CoroutineScope(contextJob + Dispatchers.Main.immediate)+ }++ /** 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 ->+ for (other in stores.value) if (other !== opened) other.openBot(null)+ noteActive(opened.id)+ }+ store.usageRead = ::publishUsage+ store.open()+ mutableStores.update { list -> list.filter { it.id != computer.id } + store }+ sortStores()+ if (foreground) store.setForeground(true)+ }++ /** Forgets [id] here: its link, mirror and drafts; its bots and chats stay on the computer. */+ internal suspend fun close(id: String) {+ val store = store(id) ?: return+ mutableStores.update { list -> list.filter { it.id != id } }+ store.retire()+ computerChanges.withLock {+ 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() }+ }+ mutableState.update { it.copy(computers = computers) }+ }+ }++ /** Saves a computer's latest copy among the others (a new one goes last), then shows the list. */+ internal suspend fun saveComputer(computer: Computer) = computerChanges.withLock {+ val saved = state.value.computers+ val computers = if (saved.any { it.id == computer.id }) saved.map { if (it.id == computer.id) computer else it } else saved + computer+ withContext(Dispatchers.IO) { local.saveComputers(computers) }+ mutableState.update { it.copy(computers = computers) }+ }++ /**+ * Shows the computers (with their bots) in the order of [ids], on this phone only (iOS `AccountStore.move`);+ * computers [ids] leaves out keep their places after it.+ */+ fun orderComputers(ids: List<String>) = action("orderComputers") {+ computerChanges.withLock {+ val saved = state.value.computers+ val computers = ids.mapNotNull { wanted -> saved.firstOrNull { it.id == wanted } } + saved.filter { it.id !in ids }+ if (computers == saved) return@withLock+ withContext(Dispatchers.IO) { local.saveComputers(computers) }+ mutableState.update { it.copy(computers = computers) }+ }+ sortStores()+ }++ private fun sortStores() {+ val order = state.value.computers.map { it.id }+ mutableStores.update { list -> list.sortedBy { store -> order.indexOf(store.id).let { if (it < 0) Int.MAX_VALUE else it } } }+ }++ /** The computer a chat was opened or sent on: the Usage sheet and widget follow it (iOS `lastComputerId`). */+ internal fun noteActive(id: String) {+ if (state.value.lastComputerId == id) return+ mutableState.update { it.copy(lastComputerId = id) }+ contextScope.launch(Dispatchers.IO) { local.saveLastComputer(id) }+ }++ /** Opens a chat on its computer, closing the one open on another; null closes it. */+ fun openBot(ref: BotDestination?) {+ for (store in stores.value) store.openBot(if (store.id == ref?.computerId) ref.botId else null)+ }++ fun setForeground(active: Boolean) {+ foreground = active+ PushDelivery.foreground = active || stores.value.any { it.state.value.voice != null }+ for (store in stores.value) store.setForeground(active)+ if (active && !state.value.loading) refreshCloud()+ if (!active) pairingJob?.cancel()+ }++ /** Signing in or out, removing a computer, starting over: one at a time, a second while one runs is dropped. */+ internal fun sessionAction(operation: suspend () -> Unit) {+ if (sessionJob?.isActive == true) return+ sessionJob = viewModelScope.launch {+ mutableState.update { it.copy(busy = it.busy + "session", error = null) }+ try { operation() }+ catch (error: CancellationException) { throw error }+ catch (error: Exception) { showError(error) }+ finally { mutableState.update { it.copy(busy = it.busy - "session") } }+ }+ }++ /** Runs [operation] as [key], its error shown; not while loading or while [key] still runs. Whether it started. */+ internal fun action(key: String, operation: suspend () -> Unit): Boolean {+ if (state.value.loading || key in state.value.busy) return false+ mutableState.update { it.copy(busy = it.busy + key, error = null) }+ val job = contextScope.launch(start = CoroutineStart.LAZY) {+ try { operation() }+ catch (error: CancellationException) { throw error }+ catch (error: Exception) { showError(error) }+ finally { actions.remove(key); mutableState.update { it.copy(busy = it.busy - key) } }+ }+ actions[key] = job+ job.start()+ return true+ }++ internal fun showError(error: Exception) { mutableState.update { it.copy(loading = false, error = error.message ?: "Couldn't complete the action.") } }++ /** Every computer registers (or drops) this phone's push again, after the permission changed. */+ fun syncPush() { for (store in stores.value) store.syncPush() }++ /** The account's error and every computer's: the one dialog shows the first, OK clears them all. */+ fun clearError() {+ mutableState.update { it.copy(error = null) }+ for (store in stores.value) store.clearError()+ }++ private data class WidgetSource(val computers: List<Computer>, val states: List<AppState>, val current: String?)++ /** The Bots widgets show every computer's bots; Usage the last active computer's (iOS `BotsEntry`, `UsageTimeline`). */+ @OptIn(FlowPreview::class)+ private fun observeWidgets(owner: WidgetOwner) {+ 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) }+ .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)+ }+ if (!accepted) return@collect+ WidgetRefreshWorker.schedule(getApplication(), source.computers.isNotEmpty())+ CodyncWidgets.update(getApplication())+ } catch (cancelled: CancellationException) { throw cancelled }+ catch (_: Exception) { mutableState.update { it.copy(error = "Couldn't update widgets. Open State and try again.") } }+ }+ }+ }++ /** A usage read just finished on [store]: the Usage widget shows it as fresh when that's its computer. */+ private suspend fun publishUsage(store: AppStore) {+ val owner = widgetOwner ?: return+ if (state.value.currentComputerId != store.id) return+ val current = store.state.value+ withContext(Dispatchers.IO) { WidgetStore.publishUsage(getApplication(), owner, current.computer, UsageReport.decode(current.usage), true) }+ CodyncWidgets.update(getApplication())+ }++ override fun onCleared() {+ for (store in stores.value) store.close(CoroutineScope(Dispatchers.IO))+ super.onCleared()+ }+}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreAccount.kt b/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreAccount.ktsimilarity index 68%rename from apps/android/app/src/main/kotlin/com/codync/android/AppStoreAccount.ktrename to apps/android/app/src/main/kotlin/com/codync/android/AccountStoreAccount.ktindex 45ffa31b..1a4d166a 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreAccount.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreAccount.kt@@ -8,11 +8,10 @@ import kotlinx.coroutines.sync.withLockimport com.codync.android.core.*import kotlinx.coroutines.*import kotlinx.coroutines.flow.*-import kotlinx.serialization.json.*// Accounts, account computers and starting over: what the account sheet, Computer management and Settings ask for.-internal fun AppStore.signIn(provider: SignInProvider) = sessionAction {+internal fun AccountStore.signIn(provider: SignInProvider) = sessionAction {Analytics.capture(AnalyticsEvent.SignInStarted(provider))try {if (provider == SignInProvider.Hosted) NativeAccounts.hostedSignIn() else NativeAccounts.signIn(apple = provider == SignInProvider.Apple)@@ -24,9 +23,9 @@ internal fun AppStore.signIn(provider: SignInProvider) = sessionAction {// Clerk holds the new session already, so this counts toward the account.Analytics.capture(AnalyticsEvent.SignedIn(provider))}-fun AppStore.switchAccount(account: SavedAccount) = sessionAction { NativeAccounts.switch(account) }-fun AppStore.retryAccounts() { NativeAccounts.retry() }-fun AppStore.signOut() = sessionAction {+fun AccountStore.switchAccount(account: SavedAccount) = sessionAction { NativeAccounts.switch(account) }+fun AccountStore.retryAccounts() { NativeAccounts.retry() }+fun AccountStore.signOut() = sessionAction {val old = state.value.account.accounts.firstOrNull { it.userId == state.value.account.userId } ?: return@sessionAction// Sent first so it still counts toward the account.Analytics.capture(AnalyticsEvent.SignedOut)@@ -44,7 +43,7 @@ fun AppStore.signOut() = sessionAction {}}-fun AppStore.refreshCloud() = action("cloud") {+fun AccountStore.refreshCloud() = action("cloud") {val client = cloud ?: return@actiontry {client.registerDevice(Build.MODEL.take(100))@@ -61,29 +60,40 @@ fun AppStore.refreshCloud() = action("cloud") {}/** A pull to refresh: the account's computers, joining a refresh already under way. */-suspend fun AppStore.refreshComputers() { refreshCloud(); actions["cloud"]?.join() }+suspend fun AccountStore.refreshComputers() { refreshCloud(); actions["cloud"]?.join() }-fun AppStore.requestAccess(target: CloudComputer, renew: Boolean = false) {+/** The roster's pull to refresh: every computer reconnects, and the account's computers are asked for again (iOS `refreshable`). */+suspend fun AccountStore.refreshRoster() {+ for (store in stores.value) store.reconnect()+ refreshComputers()+}++/**+ * Asks [target] for access; the code arrives in `access`, where it must match the one the computer shows.+ * Asking again while it runs joins it; [renew] revokes this phone's earlier grant and asks anew (iOS `requestAccess`).+ */+fun AccountStore.requestAccess(target: CloudComputer, renew: Boolean = false) {+ val key = "access:" + target.computerIdif (renew) {- action("renewAccess") {+ action("renewAccess:" + target.computerId) {// Await cancellation cleanup before replacing this phone's grant and request.- actions["access"]?.cancelAndJoin()+ actions[key]?.cancelAndJoin()startAccess(target, renew = true)}} else startAccess(target, renew = false)}-private fun AppStore.startAccess(target: CloudComputer, renew: Boolean) = action("access") {- mutableState.update { it.copy(askingAccess = target.computerId) }- try { askForAccess(target, renew) } finally { mutableState.update { it.copy(askingAccess = null) } }+private fun AccountStore.startAccess(target: CloudComputer, renew: Boolean) = action("access:" + target.computerId) {+ mutableState.update { it.copy(asking = it.asking + target.computerId) }+ try { askForAccess(target, renew) } finally { mutableState.update { it.copy(asking = it.asking - target.computerId) } }}-private suspend fun AppStore.askForAccess(target: CloudComputer, renew: Boolean) {+private suspend fun AccountStore.askForAccess(target: CloudComputer, renew: Boolean) {val client = requireNotNull(cloud) { "Sign in to reach your account." }if (renew) client.revokeAccess(target.computerId)val ticket = client.requestAccess(target.computerId, target.signKey)Analytics.capture(AnalyticsEvent.AccessRequested)- mutableState.update { it.copy(access = ticket) }+ mutableState.update { it.copy(access = it.access + (ticket.computerId to ticket)) }try {while (currentCoroutineContext().isActive) {if (System.currentTimeMillis() >= ticket.expiresAt) throw CloudError(410, "requestExpired")@@ -97,8 +107,8 @@ private suspend fun AppStore.askForAccess(target: CloudComputer, renew: Boolean)// Pin only the key used in the SAS. The first authenticated hello supplies addresses and box key.val previous = state.value.computers.firstOrNull { it.id == ticket.computerId && it.signKey == ticket.signKey }val computer = Computer(ticket.computerId, target.name, ticket.signKey, cloud = BuildConfig.CLOUD_URL)- .copy(urls = previous?.urls.orEmpty(), boxKey = previous?.boxKey,- color = previous?.color, route = previous?.route ?: ConnectionRoute.Automatic)+ .copy(urls = previous?.urls.orEmpty(), boxKey = previous?.boxKey)+ .keepingDevicePicks(previous)computer.validate()Analytics.capture(AnalyticsEvent.ComputerPaired(PairedVia.Account, computer.id))useApprovedComputer(computer, ticket.requestId)@@ -120,37 +130,32 @@ private suspend fun AppStore.askForAccess(target: CloudComputer, renew: Boolean)} catch (error: CloudError) {if (error.code == "requestExpired") Analytics.capture(AnalyticsEvent.AccessRequestFailed(AccessFailure.Expired))throw error- } finally { mutableState.update { it.copy(access = null) } }+ } finally { mutableState.update { it.copy(access = it.access - ticket.computerId) } }}-/** Switch only after approval, retiring the old channel and its writers before replacing its mirror. */-internal fun AppStore.useApprovedComputer(approved: Computer, requestId: String) {- val computer = approved.keepingDevicePicks(state.value.computers.firstOrNull { it.id == approved.id && it.signKey == approved.signKey })- // Approval is already confirmed by the cloud, even when switching must wait.+/** The approved computer joins this phone's computers (or replaces its older pairing), then connects. */+private suspend fun AccountStore.useApprovedComputer(computer: Computer, requestId: String) {+ // Approval is already confirmed by the cloud.mutableState.update { it.copy(approvedAccess = it.approvedAccess + (computer.id to requestId)) }- val contextId = state.value.contextId- val generation = state.value.generation- sessionAction(wait = true) {- transitions.withLock {- if (state.value.contextId != contextId || state.value.generation != generation) return@withLock- val userId = state.value.account.userId- retireContext()- try {- withContext(Dispatchers.IO) { local.saveComputers(listOf(computer)); local.completeSetup() }- } finally {- loadContext(userId)- }- mutableState.update { it.copy(approvedAccess = it.approvedAccess + (computer.id to requestId)) }- }- }+ transitions.withLock { addComputer(computer) }+ withContext(Dispatchers.IO) { local.completeSetup() }+ mutableState.update { it.copy(setupComplete = true) }+ refreshCloud()+}++/** Saves [computer] (a new one goes last, a known one keeps its place) and opens its store afresh. */+internal suspend fun AccountStore.addComputer(computer: Computer) {+ store(computer.id)?.retire()+ saveComputer(computer)+ open(computer)}-fun AppStore.cancelAccess() {- val ticket = state.value.access+fun AccountStore.cancelAccess(computerId: String) {+ val ticket = state.value.access[computerId]val client = cloud- val request = actions["access"]+ val request = actions["access:$computerId"]if (ticket != null) Analytics.capture(AnalyticsEvent.AccessRequestFailed(AccessFailure.Cancelled))- action("cancelAccess") {+ action("cancelAccess:$computerId") {request?.cancelAndJoin()if (ticket != null && client != null) client.cancelAccess(ticket.requestId)}@@ -160,52 +165,42 @@ fun AppStore.cancelAccess() {* Takes back this phone's account access to a computer (its grants) and forgets the computer here.* Also the way out when an earlier install was approved but this one never checked the code.*/-fun AppStore.revokeAccess(computerId: String) = action("revoke") {+fun AccountStore.revokeAccess(computerId: String) = action("revoke:$computerId") {requireNotNull(cloud) { "Sign in to reach your account." }.revokeAccess(computerId)- if (state.value.computers.firstOrNull()?.id == computerId) forgetComputer() else refreshCloud()+ if (store(computerId) != null) transitions.withLock { close(computerId) }+ refreshCloud()}-/** The computer's badge color, picked on this phone (an `AvatarPalette` id). */-fun AppStore.setColor(color: String) = action("color") { changeComputer { it.copy(color = color) } }-/*** Remove: forgets the computer here. Approved through the account, its grant goes too (as on iOS), or it* would come straight back as an account row; a failed revoke still forgets it, and its error shows.*/-fun AppStore.removeComputer() = sessionAction {- val id = state.value.computers.firstOrNull()?.id ?: return@sessionAction- val granted = state.value.cloudComputers.any { it.computerId == id && it.isGranted }- val failure = if (!granted) null else try { requireNotNull(cloud) { "Sign in to reach your account." }.revokeAccess(id); null }+fun AccountStore.removeComputer(computerId: String) = sessionAction {+ val granted = state.value.cloudComputers.any { it.computerId == computerId && it.isGranted }+ val failure = if (!granted) null else try { requireNotNull(cloud) { "Sign in to reach your account." }.revokeAccess(computerId); null }catch (error: CancellationException) { throw error }catch (error: Exception) { error }- forget()- // Thrown after the context reloads, which clears the error shown.+ transitions.withLock { close(computerId) }+ if (granted) refreshCloud()failure?.let { throw it }}-fun AppStore.forgetComputer() = sessionAction { forget() }--private suspend fun AppStore.forget() {- transitions.withLock {- val userId = state.value.account.userId- retireContext()- withContext(Dispatchers.IO) {- local.saveComputers(emptyList())- local.directory.listFiles()?.filter { it.name.startsWith("mirror-") || it.name.startsWith("drafts-") }?.forEach { it.delete() }- }- loadContext(userId)- }-}--fun AppStore.skipSetup() = action("setup") {+fun AccountStore.skipSetup() = action("setup") {withContext(Dispatchers.IO) { local.completeSetup() }mutableState.update { it.copy(setupComplete = true) }Analytics.completeOnboarding(OnboardingVia.Skipped)}-fun AppStore.clearError() { mutableState.update { it.copy(error = null) } }+fun AccountStore.taskNotifications(enabled: Boolean) = action("taskSettings") {+ PushPreferences.tasks(getApplication(), enabled)+ mutableState.update { it.copy(tasks = enabled) }+ Analytics.capture(AnalyticsEvent.SettingChanged(PhoneSetting.LiveActivities, enabled))+ if (!enabled) NotificationDisplay.cancel(getApplication(), 2)+ for (store in stores.value) store.syncPush()+ PushDelivery.schedule(getApplication())+}-fun AppStore.startOver() = sessionAction {+fun AccountStore.startOver() = sessionAction {transitions.withLock {retireContext()withContext(NonCancellable) {diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreLinks.kt b/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreLinks.ktnew file mode 100644index 00000000..6b7c280c--- /dev/null+++ b/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreLinks.kt@@ -0,0 +1,108 @@+package com.codync.android++import android.net.Uri+import android.os.Build+import androidx.lifecycle.viewModelScope+import com.codync.android.core.*+import kotlinx.coroutines.*+import kotlinx.coroutines.flow.*+import kotlinx.coroutines.sync.withLock++// Pairing and the links notifications, widgets and other apps open.++/** Pairs with the computer in a `codync://pair` link: scanned or pasted ([PairedVia.Qr]) or opened from outside ([PairedVia.Link]). */+internal fun AccountStore.pair(text: String, via: PairedVia) {+ if (pairingJob?.isActive == true) return+ pairingJob = contextScope.launch {+ state.first { !it.loading }+ mutableState.update { it.copy(pairing = true, error = null) }+ try {+ val pairing = Pairing.parse(text, BuildConfig.URL_SCHEME)+ val old = state.value.computers.firstOrNull { it.id == pairing.computer.id }+ require(old == null || old.signKey == pairing.computer.signKey) { "This computer's identity changed. Start over before pairing again." }+ val identity = withContext(Dispatchers.IO) { local.identity() }+ // Picked on this phone: pairing again keeps them (iOS `AccountStore.pair`).+ val computer = HostConnector.pair(pairing, identity, Build.MODEL.take(100)).keepingDevicePicks(old)+ transitions.withLock { addComputer(computer) }+ withContext(Dispatchers.IO) { local.completeSetup() }+ mutableState.update { it.copy(setupComplete = true) }+ Analytics.capture(AnalyticsEvent.ComputerPaired(via, computer.id))+ Analytics.completeOnboarding(OnboardingVia.Paired)+ } catch (error: CancellationException) { throw error }+ catch (error: Exception) {+ Analytics.capture(AnalyticsEvent.PairingFailed(PairingFailure.of(error)))+ showError(error)+ }+ finally { mutableState.update { it.copy(pairing = false) } }+ }+}++/** The state once the signed-in (or local) account has loaded: where a link can be opened. */+internal suspend fun AccountStore.activated(): AccountContext = state.first { current -> !current.loading &&+ (current.account.ready || !current.account.configured || current.account.error != null) &&+ current.contextId == LocalStore.referenceId(current.account.userId ?: "local") }++/** Closes what's open, then shows [page] over the roster. */+private fun AccountStore.navigate(page: LinkPage) {+ openBot(null)+ mutableState.update { it.copy(error = null, navigationRequest = it.navigationRequest + 1, navigationPage = page) }+}++/** A notification's or widget's `codync://bot` or `codync://usage` link: its bot's chat, or that computer's usage. */+fun AccountStore.openLink(uri: Uri) {+ linkJob?.cancel()+ linkJob = viewModelScope.launch {+ val completed = withTimeoutOrNull(30_000) {+ val activated = activated()+ val usage = uri.host == "usage"+ val destination = try {+ if (usage) { val target = UsageDestination.parse(uri.toString(), BuildConfig.URL_SCHEME); BotDestination(target.scope, target.computerId, "") }+ else BotDestination.parse(uri.toString(), BuildConfig.URL_SCHEME)+ }+ catch (_: Exception) { mutableState.update { it.copy(error = "This notification has an invalid destination.") }; return@withTimeoutOrNull true }+ if (destination.scope != activated.contextId) {+ mutableState.update { it.copy(error = "Switch to the account used by this notification to open its bot.") }+ return@withTimeoutOrNull true+ }+ val store = store(destination.computerId)+ if (store == null) {+ mutableState.update { it.copy(error = "This notification's computer is no longer paired here.") }+ return@withTimeoutOrNull true+ }+ val generation = activated.generation+ if (usage) {+ if (state.value.generation == generation) { noteActive(store.id); navigate(LinkPage.Usage) }+ return@withTimeoutOrNull true+ }+ if (store.state.value.bots.none { it.id == destination.botId }) {+ // A cold cache or a newly created bot needs an authoritative current roster.+ // The query belongs to that computer's runtime; retiring it joins the query.+ val request = store.contextScope.async { store.loadRoster() }+ try { request.await() }+ catch (cancelled: CancellationException) { throw cancelled }+ catch (_: Exception) {+ if (state.value.generation == generation) mutableState.update { it.copy(error = "Reconnect to this computer and try opening the notification again.") }+ return@withTimeoutOrNull true+ } finally { request.cancel() }+ }+ if (state.value.generation != generation || state.value.contextId != destination.scope) return@withTimeoutOrNull true+ if (store.state.value.bots.any { it.id == destination.botId && !it.deleted }) {+ navigate(LinkPage.Bots)+ store.openBot(destination.botId)+ }+ else mutableState.update { it.copy(error = "This notification's bot is no longer available on the computer.") }+ true+ }+ if (completed == null) mutableState.update { it.copy(error = "Couldn't open this notification yet. Reconnect and try again.") }+ }+}++/** `codync://computers` and `codync://plugins`: Computer management, or the last active computer's extensions, over the roster. */+fun AccountStore.openPage(page: LinkPage) {+ linkJob?.cancel()+ linkJob = viewModelScope.launch {+ val ready = withTimeoutOrNull(30_000) { activated() } ?: return@launch+ if (page == LinkPage.Extensions && ready.computers.isEmpty()) return@launch+ navigate(page)+ }+}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AccountSwitcherView.kt b/apps/android/app/src/main/kotlin/com/codync/android/AccountSwitcherView.ktindex 814c82db..590ad34b 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AccountSwitcherView.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AccountSwitcherView.kt@@ -43,7 +43,7 @@ import com.kyant.shapes.Capsuleimport com.kyant.shapes.RoundedRectangle/** Who you're signed in as, and the other accounts on this phone (iOS `AccountSwitcherView`). */-@Composable internal fun AccountSwitcherView(state: AppState, store: AppStore, pair: () -> Unit) {+@Composable internal fun AccountSwitcherView(state: AccountContext, store: AccountStore, pair: () -> Unit) {val account = state.accountval current = account.accounts.firstOrNull { it.userId == account.userId }val busy = "session" in state.busy@@ -94,7 +94,7 @@ import com.kyant.shapes.RoundedRectangle}/** Every account on this phone as a face; tap one to switch, + to add another. */-@Composable private fun Switcher(state: AppState, store: AppStore, busy: Boolean, add: () -> Unit) {+@Composable private fun Switcher(state: AccountContext, store: AccountStore, busy: Boolean, add: () -> Unit) {Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(horizontal = 4.dp),horizontalArrangement = Arrangement.spacedBy(14.dp, Alignment.CenterHorizontally), verticalAlignment = Alignment.CenterVertically) {for (item in state.account.accounts) {@@ -123,7 +123,7 @@ import com.kyant.shapes.RoundedRectangle}/** The account face of the roster's top bar. */-@Composable internal fun AccountAvatar(state: AppState, size: Dp) {+@Composable internal fun AccountAvatar(state: AccountContext, size: Dp) {val current = state.account.accounts.firstOrNull { it.userId == state.account.userId }if (!state.account.ready || "session" in state.busy) {Box(Modifier.size(size), contentAlignment = Alignment.Center) { ThinkingOrb(size = size * 0.6f) }diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AgentModelPicker.kt b/apps/android/app/src/main/kotlin/com/codync/android/AgentModelPicker.ktindex 0805bc77..c985dc08 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AgentModelPicker.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AgentModelPicker.kt@@ -47,7 +47,7 @@ private enum class PickerStage { Closed, Agents, Models, Settings }var loading by remember(backend) { mutableStateOf(false) }var failure by remember(backend) { mutableStateOf<String?>(null) }var retry by remember(backend) { mutableIntStateOf(0) }- LaunchedEffect(state.computers.firstOrNull()?.id, backend, online, retry) {+ LaunchedEffect(state.computer.id, backend, online, retry) {failure = null; loading = falseif (backend == "custom") return@LaunchedEffectif (!online) { failure = "Connect to this computer to load its models. You can still enter a model ID."; return@LaunchedEffect }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.ktindex 6176e928..bcf3ead5 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@@ -8,22 +8,45 @@ import kotlinx.serialization.json.longOrNull/** Where a link lands once everything open is closed: the roster, or a sheet over it. */enum class LinkPage { Bots, Usage, Computers, Extensions }-/** Everything the UI renders for the active account and its computer; `AppStore` owns the only writer. */-data class AppState(- val icons: Map<String, CustomIcon> = emptyMap(),+/**+ * The active account as the UI renders it (iOS `AccountStore`): its computers, each with its own+ * [AppStore], the account's other computers and what's waiting on them. `AccountStore` owns the only writer.+ */+data class AccountContext(val contextId: String = "local",val generation: Int = 0,val account: AccountState = AccountState(),val cloudComputers: List<CloudComputer> = emptyList(),- val access: AccessTicket? = null,+ /** Access requests waiting for approval on the computer, with the code to check, by computer ID. */+ val access: Map<String, AccessTicket> = emptyMap(),+ /** The request each computer was approved through most recently. */val approvedAccess: Map<String, String> = emptyMap(),- /** The account computer an access request is running for: one at a time. */- val askingAccess: String? = null,+ /** Account computers an access request is being sent to. */+ val asking: Set<String> = emptySet(),val tasks: Boolean = true,val setupComplete: Boolean = false,val loading: Boolean = true,val pairing: Boolean = false,+ /** This phone's computers, in the order it shows them. */val computers: List<Computer> = emptyList(),+ /** The computer the Usage sheet and widget show: the last one a chat was opened or sent on. */+ val lastComputerId: String? = null,+ val navigationRequest: Int = 0,+ val navigationPage: LinkPage = LinkPage.Bots,+ val busy: Set<String> = emptySet(),+ 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+}++/** One computer as the UI renders it (iOS `BotStore`); its `AppStore` owns the only writer. */+data class AppState(+ val computer: Computer,+ val icons: Map<String, CustomIcon> = emptyMap(),+ val contextId: String = "local",+ val generation: Int = 0,+ val loading: Boolean = true,val bots: List<Bot> = emptyList(),val rosterLoaded: Boolean = false,val mirrorRevision: Long = 0,@@ -37,9 +60,8 @@ data class AppState(val hello: JsonObject? = null,val connection: LinkState = LinkState.Connecting,val actualConnection: LinkState = LinkState.Connecting,+ /** The chat open on this computer; at most one computer has one (`AccountStore.openBot`). */val selectedBot: String? = null,- val navigationRequest: Int = 0,- val navigationPage: LinkPage = LinkPage.Bots,val trace: Boolean = false,val busy: Set<String> = emptySet(),val historyComplete: Set<String> = emptySet(),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.ktindex 0e63e6d5..5bef9416 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@@ -1,45 +1,49 @@package com.codync.androidimport android.app.Application-import androidx.lifecycle.AndroidViewModel-import androidx.lifecycle.viewModelScopeimport com.codync.android.core.*import java.io.IOException-import java.util.UUIDimport java.util.concurrent.ConcurrentHashMapimport kotlinx.coroutines.sync.Mutex-import kotlinx.coroutines.sync.withLockimport kotlinx.coroutines.*import kotlinx.coroutines.flow.*import kotlinx.serialization.json.*/**- * The ViewModel the UI talks to: the active account's state and the one writer of it. This file holds- * the account context's lifecycle (load, retire), the mirror refresh and the helpers every feature- * uses; the features themselves are `AppStore` extensions in the `AppStore*.kt` files beside it.+ * One computer's store (iOS `BotStore`): its encrypted link, its mirror and the one writer of its [AppState].+ * `AccountStore` makes one for each computer of the account and retires them with it. This file holds the+ * store's lifecycle (open, retire), the mirror refresh and the helpers every feature uses; the features+ * themselves are `AppStore` extensions in the `AppStore*.kt` files beside it.*/-class AppStore(application: Application) : AndroidViewModel(application) {- internal val activityOwnerId: String = UUID.randomUUID().toString()- internal var local = LocalStore(application)- private var contextJob = SupervisorJob(viewModelScope.coroutineContext[Job])- internal var contextScope = CoroutineScope(contextJob + Dispatchers.Main.immediate)- internal val transitions = Mutex()- /** One change to the paired computer's saved copy at a time (`changeComputer`). */+class AppStore internal constructor(+ private val application: Application,+ internal val local: LocalStore,+ computer: Computer,+ contextId: String,+ generation: Int,+ parent: Job,+ /** Saves this computer's latest copy among the account's computers. */+ 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,+) {+ 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`). */internal val computerChanges = Mutex()internal val screenTakeovers = Mutex()- internal var cloud: CloudClient? = null- private var sessionJob: Job? = null- internal var linkJob: Job? = null- internal var attachments = AttachmentFiles(application, local.directory)+ internal val attachments = AttachmentFiles(application, local.directory)internal val downloadLocks = ConcurrentHashMap<String, Mutex>()- internal val mutableState = MutableStateFlow(AppState())+ internal val mutableState = MutableStateFlow(AppState(computer, contextId = contextId, generation = generation))val state = mutableState.asStateFlow()+ internal val feed = TaskFeed(local.directory, computer.id)internal var database: MirrorDatabase? = nullinternal var draftBook: DraftBook? = nullinternal var draftWriter: Job? = nullinternal var savedDrafts: Map<String, ComposerDraft> = emptyMap()internal var connectionJob: Job? = null- internal var pairingJob: Job? = nullinternal var graceJob: Job? = nullinternal var channel: EncryptedChannel? = nullinternal var foreground = false@@ -57,73 +61,38 @@ class AppStore(application: Application) : AndroidViewModel(application) {/** Section moves shown but not answered yet, oldest first. */internal val pendingSectionMoves = mutableListOf<SectionMove>()internal var pluginsRefreshAgain = false- internal var widgetOwner: WidgetOwner? = null/** 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 = {}- init {- viewModelScope.launch {- withContext(Dispatchers.IO) { PushPreferences.splitSwitch(getApplication()) }- transitions.withLock { loadContext(null) }- NativeAccounts.observe(viewModelScope) { account ->- mutableState.update { it.copy(account = account) }- if (account.ready) transitions.withLock {- // Read the latest state after a concurrent logout/reset finishes.- val current = state.value.account- val desired = current.userId ?: "local"- if (desired != local.contextId) {- retireContext()- loadContext(current.userId)- } else if (cloud == null && current.userId != null) {- configureCloud(current.userId)- refreshCloud()- }- }- }+ /** 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?.recoverInterrupted()+ val snapshot = requireNotNull(database).snapshot()+ val restored = book.recover(snapshot)+ savedDrafts = restored.associateBy { it.botId }+ mutableState.update { it.copy(drafts = restored.associateBy { draft -> draft.botId }) }}+ draftBook = book+ refresh()+ mutableState.update { it.copy(loading = false) }}- internal suspend fun loadContext(userId: String?) {- try {- WidgetRefreshWorker.stop(getApplication())- local = LocalStore(getApplication(), userId ?: "local")- widgetOwner = withContext(Dispatchers.IO) { WidgetStore.activate(getApplication(), local.contextId) }- PushDelivery.activate(getApplication(), userId)- attachments = AttachmentFiles(getApplication(), local.directory)- val computers = withContext(Dispatchers.IO) { local.computers() }- val complete = withContext(Dispatchers.IO) { local.setupComplete() }- mutableState.update { AppState(contextId = local.referenceId, generation = it.generation + 1,- account = it.account, computers = computers, setupComplete = complete || computers.isNotEmpty() || userId != null) }- mutableState.update { it.copy(tasks = PushPreferences.tasks(getApplication())) }- openMirror()- if (userId != null) configureCloud(userId)- mutableState.update { it.copy(loading = false) }- observeWidgets(requireNotNull(widgetOwner))- if (foreground) connect()- refreshCloud()- } catch (error: CancellationException) { throw error }- catch (error: Exception) { showError(error) }- }-- private suspend fun configureCloud(userId: String) {- val identity = withContext(Dispatchers.IO) { local.identity() }- cloud = CloudClient(BuildConfig.CLOUD_URL, identity) { NativeAccounts.token(userId) }- }+ /** The files this computer's queued messages and drafts still need, so starting up keeps them. */+ internal fun pendingFiles(): List<OutgoingFile> = state.value.pending.flatMap { it.files } + state.value.drafts.values.flatMap { it.files }- /** Join every writer before closing a context's database or replacing its identity. */- internal suspend fun retireContext() = withContext(NonCancellable) {+ /** Joins every writer before the account closes this computer's database or forgets it. */+ internal suspend fun retire(unregister: Boolean = true) = withContext(NonCancellable) {mutableState.update { it.copy(loading = true) }- withContext(Dispatchers.IO) { WidgetStore.retire(getApplication(), widgetOwner) }- widgetOwner = null- WidgetRefreshWorker.stop(getApplication())- try { CodyncWidgets.update(getApplication()) } catch (_: Exception) { }retireVoice()val writers = actions.values.toList()writers.forEach { it.cancel() }; writers.forEach { it.join() }- PushDelivery.retire(getApplication())val retiringChannel = channel?.takeIf { it.state.value is LinkState.Ready }- val feed = TaskFeed(local.directory)- if (retiringChannel != null) withTimeoutOrNull(2_000) {+ if (unregister && retiringChannel != null) withTimeoutOrNull(2_000) {try {retiringChannel.call("unregisterDevice")for (watch in withContext(Dispatchers.IO) { feed.all() }) retiringChannel.call("unregisterActivity", body("botId" to watch.botId))@@ -131,53 +100,25 @@ class AppStore(application: Application) : AndroidViewModel(application) {}// Editing is disabled during retirement; let its last coalesced write finish.draftWriter?.join()- contextJob.cancelAndJoin()+ job.cancelAndJoin()setupTerminals.clear()appConnections.clear()oauthRequestId = null- AccountImages.retire()channel?.close(); channel = null- connectionJob = null; pairingJob = null; graceJob = null- actions.clear(); sends.clear(); downloadLocks.clear(); cloud = null+ connectionJob = null; graceJob = null+ actions.clear(); sends.clear(); downloadLocks.clear()// A cancelled section move never heard back: it would lie over the next mirror for good.pendingSectionMoves.clear(); mirrorBots = emptyList()pluginsRefreshAgain = falserewoundFor = nulldraftWriter = null; draftBook = null; savedDrafts = emptyMap()withContext(Dispatchers.IO) { feed.clear(); database?.close(); database = null }- withContext(Dispatchers.IO) { ConnectorOAuthBook(local.directory).clear() }- contextJob = SupervisorJob(viewModelScope.coroutineContext[Job])- contextScope = CoroutineScope(contextJob + Dispatchers.Main.immediate)- }-- internal fun sessionAction(wait: Boolean = false, operation: suspend () -> Unit) {- val previous = sessionJob- if (previous?.isActive == true && !wait) return- sessionJob = viewModelScope.launch {- previous?.join()- mutableState.update { it.copy(busy = it.busy + "session", error = null) }- try { operation() }- catch (error: CancellationException) { throw error }- catch (error: Exception) { showError(error) }- finally { mutableState.update { it.copy(busy = it.busy - "session") } }- }}- internal suspend fun openMirror() {- val computer = state.value.computers.firstOrNull() ?: return- val book = DraftBook(local.directory, computer.id)- withContext(Dispatchers.IO) {- database?.close()- database = MirrorDatabase(getApplication(), local.directory, computer.id)- database?.recoverInterrupted()- val snapshot = requireNotNull(database).snapshot()- val restored = book.recover(snapshot)- savedDrafts = restored.associateBy { it.botId }- mutableState.update { it.copy(drafts = restored.associateBy { draft -> draft.botId }) }- attachments.retainPending(snapshot.pending.flatMap { it.files } + restored.flatMap { it.files })- }- draftBook = book- refresh()+ /** Saves the computer's latest copy (`changeComputer`), then shows it. */+ internal suspend fun save(computer: Computer) {+ saveComputer(computer)+ mutableState.update { it.copy(computer = computer) }}internal suspend fun refresh() {@@ -194,11 +135,10 @@ class AppStore(application: Application) : AndroidViewModel(application) {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())) {- val feed = TaskFeed(local.directory)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, state.value.computers.first().id, watch)+ if (watch != null) NotificationDisplay.task(getApplication(), local.referenceId, id, watch)}}}@@ -231,42 +171,22 @@ class AppStore(application: Application) : AndroidViewModel(application) {return true}- internal fun showError(error: Exception) { mutableState.update { it.copy(loading = false, error = error.message ?: "Couldn't complete the action.") } }-- private data class WidgetSource(val computer: Computer?, val bots: List<Bot>, val usage: JsonObject, val fresh: Boolean)- @OptIn(FlowPreview::class)- private fun observeWidgets(owner: WidgetOwner) {- contextScope.launch {- state.filter { !it.loading && it.contextId == owner.scope }- .map { WidgetSource(it.computers.firstOrNull(), it.bots, it.usage, it.widgetBotsCurrent) }- .distinctUntilChanged().debounce(350).collect { source ->- try {- val usage = UsageReport.decode(source.usage)- val accepted = withContext(Dispatchers.IO) { WidgetStore.publish(getApplication(), owner, source.computer, source.bots, usage, source.fresh, false) }- if (!accepted) return@collect- WidgetRefreshWorker.schedule(getApplication(), source.computer != null)- CodyncWidgets.update(getApplication())- } catch (cancelled: CancellationException) { throw cancelled }- catch (_: Exception) { mutableState.update { it.copy(error = "Couldn't update widgets. Open State and try again.") } }- }- }- }+ internal fun showError(error: Exception) { mutableState.update { it.copy(error = error.message ?: "Couldn't complete the action.") } }- override fun onCleared() {+ /** 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) }voiceBinding?.engine?.end()channel?.close()val old = database- val retiring = contextJobval book = draftBookval drafts = state.value.drafts.values.toList()- CoroutineScope(Dispatchers.IO).launch {- retiring.cancelAndJoin()+ scope.launch {+ job.cancelAndJoin()try { book?.save(drafts) }catch (_: Exception) { /* An already closing activity cannot report a storage error. */ }finally { old?.close() }}- super.onCleared()}}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.ktindex 8ab98c8c..8c6bdcb2 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@@ -61,7 +61,8 @@ fun AppStore.saveBot(draft: BotDraft, onSaved: () -> Unit) = action("editor") {val bot = HostClient.decode(result.jsonObject.getValue("bot").jsonObject)withContext(Dispatchers.IO) { requireNotNull(database).receive(bot) }refresh()- openBot(bot.id)+ // A new bot or group opens its chat; an edit stays where it was made (iOS `BotEditorView.save`).+ if (draft.id == null) openBot(bot.id)onSaved()}@@ -75,7 +76,8 @@ fun AppStore.saveGroup(draft: GroupDraft, onSaved: () -> Unit) = action("editor"val bot = HostClient.decode(result.jsonObject.getValue("bot").jsonObject)withContext(Dispatchers.IO) { requireNotNull(database).receive(bot) }refresh()- openBot(bot.id)+ // A new bot or group opens its chat; an edit stays where it was made (iOS `BotEditorView.save`).+ if (draft.id == null) openBot(bot.id)onSaved()}@@ -157,12 +159,7 @@ fun AppStore.refreshUsage(force: Boolean = true) = action("usage") {UsageReport.decode(response)withContext(Dispatchers.IO) { requireNotNull(database).apply(MirrorEvent.Usage(response)) }refresh()- widgetOwner?.let { owner ->- val current = state.value- withContext(Dispatchers.IO) { WidgetStore.publish(getApplication(), owner, current.computers.firstOrNull(),- current.bots, UsageReport.decode(current.usage), false, true) }- CodyncWidgets.update(getApplication())- }+ usageRead(this)}suspend fun AppStore.selectWorkspace(path: String): String {return hostQuery("selectWorkspace", body("path" to path)).jsonObject["path"]?.jsonPrimitive?.contentdiff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.ktindex 4b5c9b07..45e6a638 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@@ -10,9 +10,11 @@ import kotlinx.serialization.json.*// Conversations: opening a bot, history, sending and its retries.+/** Opens a chat on this computer (the account closes any other computer's) or, with null, closes it. */fun AppStore.openBot(id: String?) {+ if (id == null && state.value.selectedBot == null) returnmutableState.update { it.copy(selectedBot = id, trace = false) }- if (id != null) acknowledgeVisible()+ if (id != null) { opened(this); acknowledgeVisible() }}fun AppStore.showTrace(show: Boolean) { mutableState.update { it.copy(trace = show) } }@@ -114,8 +116,8 @@ internal suspend fun AppStore.deliver(send: PendingSend) {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()) {- val watch = withContext(Dispatchers.IO) { TaskFeed(local.directory).start(bot) }- NotificationDisplay.task(getApplication(), local.referenceId, state.value.computers.first().id, watch)+ val watch = withContext(Dispatchers.IO) { feed.start(bot) }+ NotificationDisplay.task(getApplication(), local.referenceId, id, watch)syncPush(); PushDelivery.schedule(getApplication())}} catch (error: CancellationException) {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.ktindex 3d336ced..17ed2e78 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@@ -11,18 +11,22 @@ import kotlinx.serialization.json.*// Pairing, the encrypted link to the computer and the mirror's event stream.fun AppStore.setRoute(route: ConnectionRoute) = action("route") {- changeComputer { it.copy(route = route) } ?: return@action+ changeComputer { it.copy(route = route) }reconnect().join()}+/** The computer's badge color, picked on this phone (an `AvatarPalette` id). */+fun AppStore.setColor(color: String) = action("color") { changeComputer { it.copy(color = color) } }++fun AppStore.clearError() { mutableState.update { it.copy(error = null) } }+/**- * Changes the paired computer's latest copy, saved and then shown, one change at a time: a switch- * flipped while a link's `hello` runs isn't undone by the copy that link saves.+ * Changes this computer's latest copy, saved and then shown, one change at a time: a switch flipped+ * while a link's `hello` runs isn't undone by the copy that link saves.*/-internal suspend fun AppStore.changeComputer(change: (Computer) -> Computer): Computer? = computerChanges.withLock {- val changed = change(state.value.computers.firstOrNull() ?: return@withLock null)- withContext(Dispatchers.IO) { local.saveComputers(listOf(changed)) }- mutableState.update { it.copy(computers = listOf(changed)) }+internal suspend fun AppStore.changeComputer(change: (Computer) -> Computer): Computer = computerChanges.withLock {+ val changed = change(state.value.computer)+ save(changed)changed}@@ -32,6 +36,13 @@ internal suspend fun AppStore.changeComputer(change: (Computer) -> Computer): Co*/fun AppStore.reconnect(): Job = contextScope.launch { connectionJob?.cancelAndJoin(); connect() }+/** The computer's current roster, asked for outright (a link to a bot this phone hasn't seen yet). */+internal suspend fun AppStore.loadRoster() {+ val bots = HostClient.bots(ready())+ withContext(Dispatchers.IO) { requireNotNull(database).receive(bots) }+ refresh()+}+/** A pull to refresh in a chat: reconnect, and hold until the link is back or has failed (the header says why). */suspend fun AppStore.refreshConnection() {reconnect().join()@@ -41,55 +52,19 @@ suspend fun AppStore.refreshConnection() {fun AppStore.setForeground(active: Boolean) {foreground = activeforegroundState.value = active- PushDelivery.foreground = transportRequiredif (active && !state.value.loading) {connect()acknowledgeVisible()- refreshCloud()- }- if (!active) {- pairingJob?.cancel()- if (!transportRequired) {- connectionJob?.cancel()- graceJob?.cancel()- channel?.close()- }}-}--/** Pairs with the computer in a `codync://pair` link: scanned or pasted ([PairedVia.Qr]) or opened from outside ([PairedVia.Link]). */-internal fun AppStore.pair(text: String, via: PairedVia) {- if (pairingJob?.isActive == true) return- pairingJob = contextScope.launch {- state.first { !it.loading }- mutableState.update { it.copy(pairing = true, error = null) }- try {- val pairing = Pairing.parse(text, BuildConfig.URL_SCHEME)- val old = state.value.computers.firstOrNull()- require(old == null || old.id == pairing.computer.id) { "Remove this phone's computer in Computer management to pair a different one." }- require(old == null || old.signKey == pairing.computer.signKey) { "This computer's identity changed. Start over before pairing again." }- val identity = withContext(Dispatchers.IO) { local.identity() }- // Picked on this phone: re-pairing keeps them (iOS `AccountStore.pair`).- val paired = HostConnector.pair(pairing, identity, Build.MODEL.take(100))- val computer = paired.keepingDevicePicks(old)- withContext(Dispatchers.IO) { local.saveComputers(listOf(computer)); local.completeSetup() }- mutableState.update { it.copy(computers = listOf(computer), setupComplete = true) }- Analytics.capture(AnalyticsEvent.ComputerPaired(via, computer.id))- Analytics.completeOnboarding(OnboardingVia.Paired)- if (database == null) openMirror()- connect()- } catch (error: CancellationException) { throw error }- catch (error: Exception) {- Analytics.capture(AnalyticsEvent.PairingFailed(PairingFailure.of(error)))- showError(error)- }- finally { mutableState.update { it.copy(pairing = false) } }+ if (!active && !transportRequired) {+ connectionJob?.cancel()+ graceJob?.cancel()+ channel?.close()}}fun AppStore.connect() {if (connectionJob?.isActive == true || !transportRequired) return- val computer = state.value.computers.firstOrNull() ?: returnval previous = connectionJobconnectionJob = contextScope.launch {previous?.cancelAndJoin()@@ -99,7 +74,7 @@ fun AppStore.connect() {try {showConnection(LinkState.Connecting)val identity = withContext(Dispatchers.IO) { local.identity() }- val target = state.value.computers.firstOrNull { it.id == computer.id } ?: return@launch+ val target = state.value.computerval active = HostConnector.connect(target, identity)connected = activechannel = active@@ -122,7 +97,7 @@ fun AppStore.connect() {reconcileMailbox(active)}if (link is LinkState.Ready) {- val fromHost = HostClient.hello(active, state.value.computers.firstOrNull { it.id == target.id } ?: target)+ val fromHost = HostClient.hello(active, state.value.computer)val hello = active.call("hello").jsonObject// This phone's picks (color, route, push) may have changed during those calls.changeComputer { current -> if (current.id == fromHost.id) fromHost.keepingDevicePicks(current) else current }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.ktindex 208e980c..fd99f833 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@@ -16,7 +16,7 @@ fun AppStore.connectorSignIn(id: String, requestId: String? = null) = action("oaoauthRequestId = requestIdval response = hostQuery("connectorSignIn", body("id" to id), 60_000)val plan = WireJson.decodeFromJsonElement<ConnectorSignIn>(response)- val computer = requireNotNull(state.value.computers.firstOrNull())+ val computer = state.value.computerexternalHttps(plan.url)if (plan.callback == "app") {val pending = PendingConnectorOAuth.create(plan, id, computer.id, System.currentTimeMillis()).copy(requestId = requestId)@@ -57,25 +57,21 @@ internal suspend fun AppStore.cancelOAuthPending(requestId: String?) {oauthRequestId = nullrefreshPlugins()}-fun AppStore.finishConnectorSignIn(uri: Uri) {+/** The browser came back with a connector sign-in: it finishes on the computer that started it. */+fun AccountStore.finishConnectorSignIn(uri: Uri) {linkJob?.cancel()linkJob = viewModelScope.launch {var expectedGeneration: Int? = nulltry {val back = OAuthReturn.parse(uri.toString(), BuildConfig.URL_SCHEME)- val activated = deadline(35_000, "This account didn't finish opening.") { state.first { !it.loading && it.account.ready &&- it.contextId == LocalStore.referenceId(it.account.userId ?: "local") } }- val generation = activated.generation- expectedGeneration = generation+ val activated = deadline(35_000, "This account didn't finish opening.") { activated() }+ expectedGeneration = activated.generationval directory = local.directoryval pending = withContext(Dispatchers.IO) { ConnectorOAuthBook(directory).read() }?: throw IOException("No connector sign-in is pending for this account. Start sign-in again.")- pending.validate(back, activated.computers.firstOrNull()?.id.orEmpty(), System.currentTimeMillis())- val response = hostQuery("connectorSignInFinish", body("state" to back.state, "code" to back.code, "error" to back.error), 60_000, generation)- val connector = WireJson.decodeFromJsonElement<InstalledConnector>(response.jsonObject.getValue("connector"))- pending.requestId?.let { finishConnectionRequest(it, connectorId = connector.id, expectedGeneration = generation) }- withContext(Dispatchers.IO) { ConnectorOAuthBook(directory).clear() }- if (state.value.generation == generation) { oauthRequestId = null; refreshPlugins(); mutableState.update { it.copy(error = null) } }+ val store = requireNotNull(store(pending.computerId)) { "The computer that started this sign-in is no longer paired here." }+ pending.validate(back, store.id, System.currentTimeMillis())+ store.finishConnectorSignIn(back, pending, directory)} catch (cancelled: CancellationException) { throw cancelled }catch (_: Exception) {mutableState.update {@@ -85,3 +81,12 @@ fun AppStore.finishConnectorSignIn(uri: Uri) {}}}++private suspend fun AppStore.finishConnectorSignIn(back: OAuthReturn, pending: PendingConnectorOAuth, directory: java.io.File) {+ val generation = state.value.generation+ val response = hostQuery("connectorSignInFinish", body("state" to back.state, "code" to back.code, "error" to back.error), 60_000, generation)+ val connector = WireJson.decodeFromJsonElement<InstalledConnector>(response.jsonObject.getValue("connector"))+ pending.requestId?.let { finishConnectionRequest(it, connectorId = connector.id, expectedGeneration = generation) }+ withContext(Dispatchers.IO) { ConnectorOAuthBook(directory).clear() }+ oauthRequestId = null; refreshPlugins(); mutableState.update { it.copy(error = null) }+}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.ktindex f5eb41c1..a5020267 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@@ -10,7 +10,7 @@ import kotlinx.serialization.json.*internal fun AppStore.setIcon(target: String, file: Uri? = null, url: String? = null, tinted: Boolean? = null, remove: Boolean = false) {action("icon:$target") {- require((file == null && url == null) || state.value.account.userId != null) { "Sign in to use custom images." }+ 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 output = java.io.ByteArrayOutputStream()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.ktindex 2a72bec6..a15c4eff 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@@ -1,7 +1,5 @@package com.codync.android-import android.net.Uri-import androidx.lifecycle.viewModelScopeimport com.codync.android.core.*import kotlinx.coroutines.*import kotlinx.coroutines.flow.*@@ -11,92 +9,15 @@ import kotlinx.serialization.json.*fun AppStore.syncPush() = action("push") {val active = channel?.takeIf { it.state.value is LinkState.Ready } ?: return@action- val computer = state.value.computers.firstOrNull() ?: return@action- try { PushDelivery.sync(getApplication(), local, computer, active) }+ try { PushDelivery.sync(getApplication(), local, state.value.computer, active) }catch (error: CancellationException) { throw error }catch (_: Exception) { PushDelivery.schedule(getApplication()) }}+/** Saved with the computer on this phone (iOS `AccountStore.setNotifications`). */fun AppStore.notifications(enabled: Boolean) = action("notificationSettings") {- changeComputer { it.copy(notifications = enabled) } ?: return@action+ changeComputer { it.copy(notifications = enabled) }Analytics.capture(AnalyticsEvent.SettingChanged(PhoneSetting.Push, enabled))- if (!enabled) NotificationDisplay.cancel(getApplication(), 1)- syncPush(); PushDelivery.schedule(getApplication())-}-fun AppStore.taskNotifications(enabled: Boolean) = action("taskSettings") {- PushPreferences.tasks(getApplication(), enabled)- mutableState.update { it.copy(tasks = enabled) }- Analytics.capture(AnalyticsEvent.SettingChanged(PhoneSetting.LiveActivities, enabled))- if (!enabled) NotificationDisplay.cancel(getApplication(), 2)+ if (!enabled) NotificationDisplay.cancel(getApplication(), 1, "${local.referenceId}/$id/")syncPush(); PushDelivery.schedule(getApplication())}-/** The state once the signed-in (or local) account has loaded: where a link can be opened. */-internal suspend fun AppStore.activated(): AppState = state.first { current -> !current.loading &&- (current.account.ready || !current.account.configured || current.account.error != null) &&- current.contextId == LocalStore.referenceId(current.account.userId ?: "local") }--fun AppStore.openLink(uri: Uri) {- linkJob?.cancel()- linkJob = viewModelScope.launch {- val completed = withTimeoutOrNull(30_000) {- val activated = activated()- val usage = uri.host == "usage"- val destination = try {- if (usage) { val target = UsageDestination.parse(uri.toString(), BuildConfig.URL_SCHEME); BotDestination(target.scope, target.computerId, "") }- else BotDestination.parse(uri.toString(), BuildConfig.URL_SCHEME)- }- catch (_: Exception) { mutableState.update { it.copy(error = "This notification has an invalid destination.") }; return@withTimeoutOrNull true }- if (destination.scope != activated.contextId) {- mutableState.update { it.copy(error = "Switch to the account used by this notification to open its bot.") }- return@withTimeoutOrNull true- }- if (destination.computerId != activated.computers.firstOrNull()?.id) {- mutableState.update { it.copy(error = "This notification's computer is no longer paired here.") }- return@withTimeoutOrNull true- }- val generation = activated.generation- if (usage) {- if (state.value.generation == generation) {- openBot(null)- mutableState.update { it.copy(error = null, navigationRequest = it.navigationRequest + 1, navigationPage = LinkPage.Usage) }- }- return@withTimeoutOrNull true- }- if (activated.bots.none { it.id == destination.botId }) {- // A cold cache or a newly created bot needs an authoritative current roster.- // The query belongs to the activated runtime; account retirement joins it.- val request = contextScope.async {- val active = ready()- val bots = HostClient.bots(active)- withContext(Dispatchers.IO) { requireNotNull(database).receive(bots) }- refresh()- }- try { request.await() }- catch (cancelled: CancellationException) { throw cancelled }- catch (_: Exception) {- if (state.value.generation == generation) mutableState.update { it.copy(error = "Reconnect to this computer and try opening the notification again.") }- return@withTimeoutOrNull true- } finally { request.cancel() }- }- if (state.value.generation != generation || state.value.contextId != destination.scope) return@withTimeoutOrNull true- if (state.value.bots.any { it.id == destination.botId && !it.deleted }) {- mutableState.update { it.copy(error = null, navigationRequest = it.navigationRequest + 1, navigationPage = LinkPage.Bots) }- openBot(destination.botId)- }- else mutableState.update { it.copy(error = "This notification's bot is no longer available on the computer.") }- true- }- if (completed == null) mutableState.update { it.copy(error = "Couldn't open this notification yet. Reconnect and try again.") }- }-}--/** `codync://computers` and `codync://plugins`: Computer management, or the paired computer's extensions, over the roster. */-fun AppStore.openPage(page: LinkPage) {- linkJob?.cancel()- linkJob = viewModelScope.launch {- val ready = withTimeoutOrNull(30_000) { activated() } ?: return@launch- if (page == LinkPage.Extensions && ready.computers.isEmpty()) return@launch- openBot(null)- mutableState.update { it.copy(navigationRequest = it.navigationRequest + 1, navigationPage = page) }- }-}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreScreen.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreScreen.ktindex de5596a9..13434836 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreScreen.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreScreen.kt@@ -22,12 +22,12 @@ fun AppStore.openScreen(watching: String? = null) = mutableState.update { it.copfun AppStore.closeScreen() = mutableState.update { it.copy(screenRequest = null) }-/** `codync://screen`: the paired computer's screen, once the account has loaded. */-fun AppStore.openScreenLink() {+/** `codync://screen`: the last active computer's screen (iOS `currentStore`), once the account has loaded. */+fun AccountStore.openScreenLink() {linkJob?.cancel()linkJob = viewModelScope.launch {- val ready = withTimeoutOrNull(30_000) { activated() }- if (ready?.computers?.isNotEmpty() == true) openScreen()+ val ready = withTimeoutOrNull(30_000) { activated() } ?: return@launch+ store(ready.currentComputerId)?.openScreen()}}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/BotDetailsView.kt b/apps/android/app/src/main/kotlin/com/codync/android/BotDetailsView.ktindex 0c6c4000..aa2ecd55 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/BotDetailsView.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/BotDetailsView.kt@@ -35,11 +35,8 @@ import com.codync.android.core.hasLibraryimport com.codync.android.design.*import kotlinx.coroutines.delay-/**- * The details sheet's pages, as on the desktop inspector; no Memory until the read-only memory screen is ported- * (docs/plans/android-app.md).- */-internal enum class DetailsTab(val title: String) { Details("Details"), Library("Library"), Settings("Settings") }+/** The details sheet's pages, as on the desktop inspector (iOS `BotDetailsView.Tab`). */+internal enum class DetailsTab(val title: String) { Details("Details"), Library("Library"), Memory("Memory"), Settings("Settings") }/*** What to open the details sheet on (iOS `DetailsRequest`): a page, a routine's editor on the Details page, or another bot's@@ -68,7 +65,7 @@ internal data class DetailsRequest(val tab: DetailsTab = DetailsTab.Details, valdelay(600)store.saveSettings(draft)}- val tabs = listOfNotNull(DetailsTab.Details, DetailsTab.Library.takeIf { hasLibrary(state.hello?.text("version")) }, DetailsTab.Settings)+ val tabs = listOfNotNull(DetailsTab.Details, DetailsTab.Library.takeIf { hasLibrary(state.hello?.text("version")) }, DetailsTab.Memory, DetailsTab.Settings)Box(Modifier.fillMaxSize().background(Palette.background)) {Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(start = 20.dp, end = 20.dp, bottom = 24.dp),horizontalAlignment = Alignment.CenterHorizontally) {@@ -84,13 +81,15 @@ internal data class DetailsRequest(val tab: DetailsTab = DetailsTab.Details, valLaunchedEffect(Unit) { routineId = null }}DetailsTab.Library -> LibraryView(bot, state, store, openArtifact)+ DetailsTab.Memory -> MemoryCard(bot.id, state, store)DetailsTab.Settings -> BotSettingsForm(state, store, draft, { draft = it }, FormPart.Rarely)}}}}Row(Modifier.align(Alignment.TopEnd).padding(top = 14.dp, end = 14.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {- CornerButton("Create template", "square.and.arrow.up") { template = draft }+ // The bot as it's saved, as on the iPhone.+ CornerButton("Create template", "square.and.arrow.up") { template = saved }CornerButton("Close details", "xmark", dismiss)}}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.ktindex af9866c9..231fc2e3 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,7 +21,11 @@ import androidx.compose.foundation.layout.widthimport androidx.compose.foundation.layout.widthInimport androidx.compose.foundation.lazy.rememberLazyListStateimport androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.LazyListScopeimport androidx.compose.foundation.lazy.items+import android.content.Context+import androidx.compose.foundation.layout.Column+import androidx.compose.ui.unit.Dpimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.getValue@@ -56,105 +60,169 @@ import kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.putimport kotlinx.serialization.json.putJsonArray-/** The roster, as iOS `BotListView` draws it: every bot is a person you can message. */-@Composable internal fun BotListView(state: AppState, store: AppStore, account: () -> Unit, manage: () -> Unit,- newBot: () -> Unit, newGroup: () -> Unit, edit: (Bot) -> Unit, bottomInset: androidx.compose.ui.unit.Dp) {- var confirmDelete by remember { mutableStateOf<Bot?>(null) }+/** 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) {+ val reorder = RosterReorder()+ val sections = SectionReorder()+ var order by mutableStateOf(SectionOrders.load(context, key))+}++/**+ * The roster, as iOS `BotListView` draws it: every bot on every computer is a person you can message. One+ * computer shows a flat list; more get a heading each, which folds its bots and drags to reorder the computers.+ */+@Composable internal fun BotListView(app: AccountContext, states: List<AppState>, accounts: AccountStore, account: () -> Unit, manage: () -> Unit,+ newBot: (String) -> Unit, newGroup: (String) -> Unit, edit: (String, Bot) -> Unit, extensions: (String) -> Unit, bottomInset: Dp) {+ var confirmDelete by remember { mutableStateOf<Pair<String, Bot>?>(null) }var naming by remember { mutableStateOf<SectionNaming?>(null) }val context = LocalContext.currentvar folded by remember { mutableStateOf(FoldedSections.load(context)) }- val sectionKey = SectionOrders.key(state.contextId, state.computers.firstOrNull()?.id.orEmpty())+ var hidden by remember { mutableStateOf(RosterComputers.hidden(context)) }+ var collapsed by remember { mutableStateOf(RosterComputers.folded(context)) }val listState = rememberLazyListState()- var sectionOrder by remember(sectionKey) { mutableStateOf(SectionOrders.load(context, sectionKey)) }- val sectionReorder = remember(sectionKey) { SectionReorder() }- sectionReorder.save = { sectionOrder = it; sectionReorder.names = it; SectionOrders.save(context, sectionKey, it) }- sectionReorder.position = { name ->- val key = if (name.isEmpty()) "label:bots" else "section:$name"- listState.layoutInfo.visibleItemsInfo.firstOrNull { it.key == key }?.offset?.toFloat() ?: 0f+ val rosters = remember(app.contextId) { mutableMapOf<String, ComputerRoster>() }+ val shownIds = ComputerSelection(states.map { it.computer.id }, hidden).shown+ val shown = states.filter { it.computer.id in shownIds }+ val grouped = shown.size > 1+ // Computers that can take a new bot once they're connected, and the ones that can right now (iOS `availableStores`, `onlineStores`).+ val available = availableComputers(app, states)+ val online = available.filter { it.actualConnection is LinkState.Ready }+ val computerReorder = remember { SectionReorder() }+ computerReorder.names = shown.map { it.computer.id }+ computerReorder.save = { ids -> accounts.orderComputers(ids) }+ computerReorder.position = { id -> listState.layoutInfo.visibleItemsInfo.firstOrNull { it.key == "computer:$id" }?.offset?.toFloat() ?: 0f }+ // 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+ }}// 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 = { from: String, to: String? ->- val orderBefore = sectionOrder- val orderAfter = renamedSectionOrder(sectionReorder.names, from, to)- sectionReorder.save(orderAfter)+ val renameSection = { roster: ComputerRoster, store: AppStore, from: String, to: String? ->+ val orderBefore = roster.order+ val orderAfter = renamedSectionOrder(roster.sections.names, from, to)+ roster.sections.save(orderAfter)val before = foldedval renamed = foldsAfterRename(before, from, to)folded = renamedFoldedSections.save(context, renamed)store.renameSection(from, to) {- if (SectionOrders.load(context, sectionKey) == orderAfter) sectionReorder.save(orderBefore)+ if (SectionOrders.load(context, roster.key) == orderAfter) roster.sections.save(orderBefore)folded = foldsAfterRefusal(FoldedSections.load(context), renamed, before).also { FoldedSections.save(context, it) }}}- val roster = roster(state.bots)- val sectionNames = sectionNames(roster.filterNot { it.pinned })- sectionReorder.names = orderedSections(sectionNames + if (roster.any { !it.pinned && it.section == null }) listOf("") else emptyList(), sectionOrder)- val sections = menuSections(state.bots)- val reorder = remember { RosterReorder() }- reorder.roster = roster- val online = state.actualConnection is LinkState.Ready- // A computer that turned this phone away, or this computer's older identity, counts as none (iOS `availableStores`).- val usable = state.computers.isNotEmpty() && !state.isStale+ val toggleSection = { name: String -> folded = if (name in folded) folded - name else folded + name; FoldedSections.save(context, folded) }val top = WindowInsets.statusBars.asPaddingValues().calculateTopPadding()GlassStage(Modifier.fillMaxSize().background(Palette.background), chrome = {ScrollEdge(Edge.Top, top + 64.dp)Row(Modifier.fillMaxWidth().statusBarsPadding().padding(top = 6.dp).padding(horizontal = 16.dp).height(44.dp),verticalAlignment = Alignment.CenterVertically) {- AccountSwitcherButton(state, account)- Box(Modifier.weight(1f), contentAlignment = Alignment.Center) { ComputerFilterHeader(state, store, manage) }- NewMenuButton(enabled = usable, groupEnabled = online, newBot, newGroup)+ AccountSwitcherButton(app, account)+ Box(Modifier.weight(1f), contentAlignment = Alignment.Center) {+ ComputerFilterHeader(states, hidden, { hidden = it; RosterComputers.setHidden(context, it) },+ { for (state in shown) accounts.store(state.computer.id)?.reconnect() }, manage)+ }+ // A new bot starts on the first computer online (its dialog can move it); a group chat gathers one computer's bots.+ NewMenuButton(enabled = available.isNotEmpty(), groupEnabled = online.isNotEmpty(),+ { (online.firstOrNull() ?: available.firstOrNull())?.let { newBot(it.computer.id) } },+ { online.firstOrNull()?.let { newGroup(it.computer.id) } })}}) {- // Pull to refresh reconnects and asks the account for its computers again (iOS `refreshable`).- PullToRefresh({ store.reconnect(); store.refreshComputers() }, Modifier.fillMaxSize(), indicatorTop = top + 50.dp) {+ // Pull to refresh reconnects every computer and asks the account for its computers again (iOS `refreshable`).+ PullToRefresh({ accounts.refreshRoster() }, Modifier.fillMaxSize(), indicatorTop = top + 50.dp) {LazyColumn(Modifier.fillMaxSize(), state = listState, contentPadding = PaddingValues(start = 16.dp, end = 16.dp, top = top + 56.dp, bottom = bottomInset)) {- // A computer waiting for an update has its card instead; its bots may not be readable yet.- state.mismatch?.let { mismatch -> item("update") { UpdateNeededCard(state, mismatch, store::requestHostUpdate, Modifier.padding(vertical = 8.dp)) } }- if (roster.isEmpty() && state.mismatch == null) item {- EmptyRoster(canCreate = usable, hasComputer = usable, create = newBot, showComputers = manage)+ // One computer: its update notice leads the list. A computer waiting for an update has its card instead; its bots may not be readable yet.+ if (!grouped) for (state in shown) state.mismatch?.let { mismatch -> item("update:${state.computer.id}") {+ accounts.store(state.computer.id)?.let { store -> UpdateNeededCard(state, mismatch, store::requestHostUpdate, Modifier.padding(vertical = 8.dp)) }+ } }+ if (shown.all { roster(it.bots).isEmpty() && it.mismatch == null }) item("empty") {+ // Computers that turned this phone away count as none: the way on is in Computers.+ EmptyRoster(canCreate = available.isNotEmpty(), hasComputer = states.any { !app.isStale(it, states) },+ create = { (online.firstOrNull() ?: available.firstOrNull())?.let { newBot(it.computer.id) } }, showComputers = manage)}- items(rosterLines(reorder.shown(roster), folded, sectionReorder.shown, sectionReorder.dragged != null), key = RosterLine::key) { line ->- when (line) {- // Folding drops the section's rows from the list; animateItem fades them out and slides the rest up.- is RosterLine.Header -> SectionHeader(line, toggle = {- folded = if (line.name in folded) folded - line.name else folded + line.name- FoldedSections.save(context, folded)- }, actions = if (state.supportsSections) sectionActions(- rename = { naming = SectionNaming("Rename section", line.name) { renameSection(line.name, it) } },- remove = { renameSection(line.name, null) }) 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()),- 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) }- is RosterLine.Row -> {- val bot = line.bot- val lifted = reorder.dragged == bot.id- Box(Modifier.onSizeChanged { reorder.heights[bot.id] = it.height }- .then(if (lifted) Modifier.zIndex(1f).graphicsLayer { translationY = reorder.offset; scaleX = 1.02f; scaleY = 1.02f }- else Modifier.animateItem())) {- BotRowItem(bot, state, store, reorder.handle(bot.id) { store.reorder(it) }, sections, edit = { edit(bot) },- delete = { confirmDelete = bot },- newSection = { naming = SectionNaming("New section", "") { store.setSection(bot.id, it) } })- }+ for (state in ordered) {+ val id = state.computer.id+ 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)) }}}+ if (grouped && (movingComputer || id in collapsed)) continue+ botLines(state, store, roster, folded, grouped, RosterActions(toggleSection,+ rename = { name -> naming = SectionNaming("Rename section", name) { renameSection(roster, store, name, it) } },+ remove = { name -> renameSection(roster, store, name, null) },+ newSection = { bot -> naming = SectionNaming("New section", "") { store.setSection(bot.id, it) } },+ edit = { bot -> edit(id, bot) }, delete = { bot -> confirmDelete = id to bot }))}}}}- val deleting = confirmDelete+ val deleting = confirmDelete?.secondCodyncDialog("Delete ${deleting?.name ?: "bot"}?", deleting != null, { confirmDelete = null },message = if (deleting?.kind == "group") "Its bots and their own chats stay." else "Files it changed on your computer stay as they are.") {listOf(DialogAction(if (deleting?.kind == "group") "Delete group chat" else "Delete bot and its conversation", destructive = true) {- deleting?.let { store.deleteBot(it) {} }+ confirmDelete?.let { (id, bot) -> accounts.store(id)?.deleteBot(bot) {} }})}SectionNameDialog(naming) { naming = null }}+/** 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)++/** One computer's bots: pinned ones, then each section's heading with its bots (none while folded), then the bots in no section. */+private fun LazyListScope.botLines(state: AppState, store: AppStore, roster: ComputerRoster, folded: Set<String>, grouped: Boolean, actions: RosterActions) {+ val id = state.computer.id+ val sectionReorder = roster.sections+ val reorder = roster.reorder+ val sections = menuSections(state.bots)+ items(rosterLines(reorder.shown(roster(state.bots)), folded, sectionReorder.shown, sectionReorder.dragged != null), key = { "$id:${it.key}" }) { line ->+ when (line) {+ // 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()),+ 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) }+ is RosterLine.Row -> {+ val bot = line.bot+ val lifted = reorder.dragged == bot.id+ Box(Modifier.onSizeChanged { reorder.heights[bot.id] = it.height }+ .then(if (lifted) Modifier.zIndex(1f).graphicsLayer { translationY = reorder.offset; scaleX = 1.02f; scaleY = 1.02f }+ else Modifier.animateItem())) {+ BotRowItem(bot, state, store, reorder.handle(bot.id) { store.reorder(it) }, sections, grouped, edit = { actions.edit(bot) },+ delete = { actions.delete(bot) }, newSection = { actions.newSection(bot) })+ }+ }+ }+ }+}+/*** Drag-to-reorder for the roster (iOS `List.onMove`): long-press a row, then move it. The order* shown follows the finger until the host's synced order catches up.@@ -214,8 +282,8 @@ internal fun moved(roster: List<Bot>, id: String, offset: Int): List<String>? {private fun Bot.movesWith(other: Bot) = band == other.band && (pinned || section == other.section)-@Composable private fun BotRowItem(bot: Bot, state: AppState, store: AppStore, drag: ContextDrag, sections: List<String>, edit: () -> Unit,- delete: () -> Unit, newSection: () -> Unit) {+@Composable private fun BotRowItem(bot: Bot, state: AppState, store: AppStore, drag: ContextDrag, sections: List<String>, grouped: Boolean,+ edit: () -> Unit, delete: () -> Unit, newSection: () -> Unit) {Box(Modifier.fillMaxWidth().contextActions(onClick = { store.openBot(bot.id) }, reorder = drag, preview = {Box(Modifier.padding(horizontal = 8.dp)) { BotRow(bot, state) }}) {@@ -240,7 +308,8 @@ private fun Bot.movesWith(other: Bot) = band == other.band && (pinned || sectionMenuItem("Delete", icon = "trash", destructive = true, action = delete).takeIf { !bot.lead || state.supportsLeadChoice },)}.semantics {- contentDescription = bot.name+ // With several computers, which one it's on.+ contentDescription = if (grouped) "${bot.name}, on ${state.hostName}" else bot.name// TalkBack's way to reorder (the drag needs a touch and hold, then a move).customActions = listOf(-1 to "Move up", 1 to "Move down").map { (offset, title) ->CustomAccessibilityAction(title) { moved(roster(state.bots), bot.id, offset)?.let(store::reorder) != null }@@ -261,6 +330,8 @@ private fun Bot.movesWith(other: Bot) = band == other.band && (pinned || sectionif (bot.pinned) Symbol("pin.fill", size = 13.dp, tint = Palette.tertiary)Text(bot.name, Modifier.weight(1f, fill = false), style = Type.body.semibold, color = Palette.text, maxLines = 1,overflow = TextOverflow.Ellipsis)+ if (state.screen?.agentBot == bot.id) Symbol("cursorarrow.motionlines", size = 14.dp, tint = Palette.accent,+ contentDescription = tr("Using the computer"))}Spacer(Modifier.width(8.dp))if (bot.lastAt > 0) Text(RelativeTime.day(bot.lastAt, yesterday = tr("Yesterday")), style = Type.subheadline,@@ -321,7 +392,7 @@ internal fun messagePreview(text: String): String {}/** The account capsule: who's signed in, opening the account sheet. */-@Composable internal fun AccountSwitcherButton(state: AppState, open: () -> Unit) {+@Composable internal fun AccountSwitcherButton(state: AccountContext, open: () -> Unit) {val (source, pressed) = rememberPress()val email = state.account.accounts.firstOrNull { it.userId == state.account.userId }?.emailRow(Modifier.height(44.dp).glass(Capsule(), pressed = pressed)@@ -333,29 +404,6 @@ internal fun messagePreview(text: String): String {}}-/** The quiet connection summary, with reconnect and the computers on demand. */-@Composable private fun ComputerFilterHeader(state: AppState, store: AppStore, manage: () -> Unit) {- val summary = connectionSummary(state)- DropdownMenu({- listOf(- MenuItem("All computers", icon = "desktopcomputer", selected = true),- *state.computers.map { computer ->- val device = state.cloudComputers.firstOrNull { it.computerId == computer.id }?.device- ?: if (state.computers.size == 1) state.hello?.text("device") else null- MenuItem(computer.name, icon = computerSymbol(device), selected = true,- verbatim = true, detail = connectionLabel(state))- }.toTypedArray(),- MenuItem("Reconnect", icon = "arrow.clockwise", divider = true, enabled = state.computers.isNotEmpty()) { store.reconnect() },- MenuItem("Manage computers", icon = "desktopcomputer", action = manage),- )- }, label = "Computers, $summary. Filter conversations") {- Row(Modifier.padding(vertical = 6.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {- Text(summary, style = Type.system(12f).medium, color = Palette.secondary, maxLines = 1, overflow = TextOverflow.Ellipsis)- Symbol("chevron.down", size = 15.dp, tint = Palette.secondary)- }- }-}-@Composable private fun NewMenuButton(enabled: Boolean, groupEnabled: Boolean, newBot: () -> Unit, newGroup: () -> Unit) {DropdownMenu({listOf(MenuItem("New bot", icon = "plus", action = newBot),diff --git a/apps/android/app/src/main/kotlin/com/codync/android/BotSettingsForm.kt b/apps/android/app/src/main/kotlin/com/codync/android/BotSettingsForm.ktindex 2e16ac0c..be92f8e1 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/BotSettingsForm.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/BotSettingsForm.kt@@ -62,7 +62,6 @@ internal enum class FormPart { All, Often, Rarely }notifyRow(draft, change); computerUseRow(state, draft, change); manageTeamRow(state, draft, change); reachRows(state, draft, change)}Plugins(state, draft, change) { viewingSkill = it }- draft.id?.let { MemoryCard(it, store) }state.error?.let { Text(it, style = Type.footnote, color = Palette.danger) }}FormPart.Often -> {@@ -122,7 +121,7 @@ private fun CardRows.fallbackBanner(state: AppState, store: AppStore, bot: Bot?)private fun CardRows.computerRow(state: AppState, online: Boolean) = row {Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {- ValueRow("Computer", state.computers.firstOrNull()?.name ?: "Your computer")+ ValueRow("Computer", state.hostName)if (!online) OfflineNote()}}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt b/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.ktindex 44e56d68..8ebf8afc 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/ChatRows.kt@@ -136,12 +136,15 @@ internal fun chatItems(entries: List<Entry>, pending: List<PendingSend>): List<C}"permission" -> Column(Modifier.padding(top = 12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {if (group) AuthorLabel(entry.data.text("author"), state)- PermissionCard(entry, state.computers.firstOrNull()?.name.orEmpty(), answering = "permission:" + entry.id in state.busy) {+ PermissionCard(entry, state.hostName, answering = "permission:" + entry.id in state.busy) {store.respond(entry, it)}}else -> if (entry.data["connectionRequest"] is JsonObject) Box(Modifier.padding(top = 12.dp)) {ConnectionRequestCard(entry, state, store, connect.openApp, connect.install)+ } else if (entry.data["handoff"] is JsonObject) Box(Modifier.padding(top = 10.dp)) {+ // A fresh conversation starts at the left, as on the iPhone.+ HandoffCardRow(entry, entry.data["handoff"] as JsonObject, state, store)} else Box(Modifier.padding(top = 10.dp)) {// In a group, the member whose agent failed.val owner = state.bots.firstOrNull { it.id == (entry.data.text("author") ?: entry.botId) && it.kind != "group" }@@ -347,12 +350,6 @@ internal val Entry.botReactions: Map<String, List<String>> get() =}}"agentSwitch" in entry.data -> AgentSwitchLine(text, (entry.data["agentSwitch"] as? JsonObject)?.text("carried"))- // A fresh conversation starts at the left, as on the iPhone.- "handoff" in entry.data -> Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically,- horizontalArrangement = Arrangement.spacedBy(6.dp)) {- Symbol("arrow.triangle.branch", size = 13.dp, tint = Palette.secondary)- Text(text, style = Type.footnote, color = Palette.secondary)- }else -> Text(text, Modifier.fillMaxWidth(), style = Type.footnote, color = Palette.secondary, textAlign = TextAlign.Center)}}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.ktindex 40238918..aa288bfd 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@@ -215,7 +215,8 @@ import com.kyant.shapes.Capsule// A chat shorter than the screen never scrolls, so showing the row is the trigger.LaunchedEffect(Unit) { if ("history" !in state.busy) store.loadHistory() }}- if (items.isEmpty() && !more) item("intro") { IntroCard(bot, state) }+ // Shown while earlier messages may still load, as on the iPhone.+ if (items.isEmpty()) item("intro") { IntroCard(bot, state) }items(items, key = { it.id }) { item ->when (item) {is ChatItem.Separator -> TimeSeparator(item.at)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.ktindex e6ad6671..de1a1f7e 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@@ -14,6 +14,8 @@ import androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.safeDrawingPaddingimport androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.staticCompositionLocalOfimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.key@@ -23,58 +25,71 @@ import androidx.compose.runtime.rememberimport androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.runtime.setValueimport androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dpimport com.codync.android.core.Botimport com.codync.android.core.BotDraftimport com.codync.android.core.CloudComputerimport com.codync.android.core.GroupDraft+import com.codync.android.core.LinkStateimport com.codync.android.design.*private enum class Root { Loading, Welcome, Pairing, Tabs }-/** The app's root, as iOS `RootView`: the welcome and pairing until set up, then the tabs, with every sheet on top. */-@Composable fun CodyncApp(state: AppState, store: AppStore) {+/** A new bot or group chat, on the computer it's made on. */+private data class NewTarget(val group: Boolean, val computerId: String)++/** An editor sheet's draft and the computer its bot lives on. */+private data class Editing<T>(val computerId: String, val draft: T)++/**+ * The app's root, as iOS `RootView`: the welcome and pairing until set up, then the tabs, with every sheet+ * on top. Each computer's screens get that computer's store ([computers] holds their states).+ */+@Composable fun CodyncApp(app: AccountContext, computers: Map<String, AppState>, accounts: AccountStore) {var welcomed by rememberSaveable { mutableStateOf(false) }var showAccount by rememberSaveable { mutableStateOf(false) }var showComputers by rememberSaveable { mutableStateOf(false) }var showPairing by rememberSaveable { mutableStateOf(false) }var showUsage by rememberSaveable { mutableStateOf(false) }- var showMarketplace by rememberSaveable { mutableStateOf(false) }- var creatingBot by rememberSaveable { mutableStateOf(false) }- var creatingGroup by rememberSaveable { mutableStateOf(false) }+ var marketplace by rememberSaveable { mutableStateOf<String?>(null) }+ var creating by remember { mutableStateOf<NewTarget?>(null) }var access by remember { mutableStateOf<CloudComputer?>(null) }- var editor by remember { mutableStateOf<BotDraft?>(null) }- var groupEditor by remember { mutableStateOf<GroupDraft?>(null) }- var handledNavigation by rememberSaveable { mutableIntStateOf(state.navigationRequest) }- var handledGeneration by rememberSaveable { mutableIntStateOf(state.generation) }+ var editor by remember { mutableStateOf<Editing<BotDraft>?>(null) }+ var groupEditor by remember { mutableStateOf<Editing<GroupDraft>?>(null) }+ var handledNavigation by rememberSaveable { mutableIntStateOf(app.navigationRequest) }+ var handledGeneration by rememberSaveable { mutableIntStateOf(app.generation) }fun closeAll() {- showAccount = false; showComputers = false; showPairing = false; showMarketplace = false- creatingBot = false; creatingGroup = false; access = null; editor = null; groupEditor = null+ showAccount = false; showComputers = false; showPairing = false; marketplace = null+ creating = null; access = null; editor = null; groupEditor = null}// A new account or a fresh start drops whatever was open for the old one.- LaunchedEffect(state.generation) { if (handledGeneration != state.generation) { closeAll(); showUsage = false; handledGeneration = state.generation } }+ LaunchedEffect(app.generation) { if (handledGeneration != app.generation) { closeAll(); showUsage = false; handledGeneration = app.generation } }// A notification, widget or link: close everything, then maybe show usage, the computers or extensions.- LaunchedEffect(state.navigationRequest) {- if (handledNavigation != state.navigationRequest) {+ LaunchedEffect(app.navigationRequest) {+ if (handledNavigation != app.navigationRequest) {closeAll()- showUsage = state.navigationPage == LinkPage.Usage- showComputers = state.navigationPage == LinkPage.Computers- showMarketplace = state.navigationPage == LinkPage.Extensions- handledNavigation = state.navigationRequest+ showUsage = app.navigationPage == LinkPage.Usage+ showComputers = app.navigationPage == LinkPage.Computers+ if (app.navigationPage == LinkPage.Extensions) marketplace = app.currentComputerId+ handledNavigation = app.navigationRequest}}- val signedIn = state.account.userId != null+ val signedIn = app.account.userId != null// Signed in, setup counts as complete (`loadContext`): the account's computers are asked for access from Computers.- val onboarding = !state.setupComplete && state.computers.isEmpty() && state.cloudComputers.isEmpty()+ val onboarding = !app.setupComplete && app.computers.isEmpty() && app.cloudComputers.isEmpty()val root = when {- state.loading -> Root.Loading+ app.loading -> Root.Loadingonboarding && !welcomed && !signedIn -> Root.Welcomeonboarding -> Root.Pairingelse -> Root.Tabs}BackHandler(root == Root.Pairing && !signedIn) { welcomed = false }- val edit = { bot: Bot -> if (bot.kind == "group") groupEditor = GroupDraft.from(bot) else editor = BotDraft.from(bot) }- val openMarketplace = { showAccount = false; showComputers = false; showMarketplace = true }- Box(Modifier.fillMaxSize().background(Palette.background)) {+ val states = app.computers.mapNotNull { computers[it.id] }+ val edit = { computerId: String, bot: Bot ->+ 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()))@@ -84,69 +99,113 @@ private enum class Root { Loading, Welcome, Pairing, Tabs }}, label = "Root") { shown ->when (shown) {Root.Loading -> Box(Modifier.fillMaxSize())- Root.Welcome -> WelcomeView(state, store) { welcomed = true }+ Root.Welcome -> WelcomeView(app, accounts) { welcomed = true }Root.Pairing -> Box(Modifier.fillMaxSize().safeDrawingPadding()) {- PairingView(state, store, onSkip = store::skipSetup) {- if (signedIn) AccountSwitcherButton(state) { showAccount = true } else BackButton { welcomed = false }+ PairingView(app, accounts, onSkip = accounts::skipSetup) {+ if (signedIn) AccountSwitcherButton(app) { showAccount = true } else BackButton { welcomed = false }}}- Root.Tabs -> MainTabs(state, store, account = { showAccount = true }, manage = { showComputers = true }, usage = { showUsage = true },- newBot = { creatingBot = true }, newGroup = { creatingGroup = true },- edit = edit) {- ChatScreen(state, store, edit)+ 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) { 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 && (state.setupComplete || signedIn) && !state.loading, { showAccount = false }) {+ } }+ CodyncSheet(showAccount && (app.setupComplete || signedIn) && !app.loading, { showAccount = false }) {AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Account))- AccountSwitcherView(state, store) { showPairing = true }+ AccountSwitcherView(app, accounts) { showPairing = true }}- CodyncSheet(showComputers && !state.loading, { showComputers = false }) {+ CodyncSheet(showComputers && !app.loading, { showComputers = false }) {AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Computers))- ComputersView(state, store, { showPairing = true }, { access = it }, openMarketplace)+ ComputersView(app, states, accounts, { showPairing = true }, { access = it }, openMarketplace)}- CodyncSheet(access, { access = null }) { AccessRequestView(state, store, it) }- CodyncSheet(showPairing && !state.loading, { showPairing = false }) {+ CodyncSheet(access, { access = null }) { AccessRequestView(app, accounts, it) }+ CodyncSheet(showPairing && !app.loading, { showPairing = false }) {AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Pairing))- PairingView(state, store, inModal = true)+ PairingView(app, accounts, inModal = true)}- CodyncSheet(showUsage && !state.loading, { showUsage = false }) {+ CodyncSheet(showUsage && !app.loading, { showUsage = false }) {AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Usage))- UsageScreen(state, store::refreshUsage, store::reloadUsage)+ UsageSheet(app, states, accounts)}- CodyncSheet(showMarketplace && root == Root.Tabs, { showMarketplace = false }) {+ // 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))- MarketplaceView(state, store)+ 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)+ }+ }}- CodyncSheet(creatingBot && !state.loading, { creatingBot = false }) { key(state.contextId, state.generation) { NewBotView(state, store) } }- CodyncSheet(creatingGroup && !state.loading, { creatingGroup = false }) { key(state.contextId, state.generation) { NewGroupView(state, store) } }// 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 { !state.loading }, { groupEditor = null }) { draft ->+ CodyncSheet(groupEditor.takeIf { !app.loading }, { groupEditor = null }) { target ->AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.BotDetails))- key(state.contextId, state.generation, draft.id) { GroupEditor(state, draft, store) }+ 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 { !state.loading }, { editor = null }) { draft ->+ CodyncSheet(editor.takeIf { !app.loading }, { editor = null }) { target ->AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.BotDetails))- key(state.contextId, state.generation, draft.id) { BotEditor(state, draft, store) }+ 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 }++/** 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) }++/** A computer in the new bot's Computer menu, offline ones marked. */+private fun computerChoice(state: AppState): String =+ if (state.actualConnection is LinkState.Ready) state.hostName else "${state.hostName} (offline)"++/** Usage for one computer at a time: the last active one, which the Usage widget shows too (iOS `UsageSheet`). */+@Composable private fun UsageSheet(app: AccountContext, states: List<AppState>, accounts: AccountStore) {+ val state = states.firstOrNull { it.computer.id == app.currentComputerId }+ val store = accounts.store(state?.computer?.id)+ val picker: @Composable () -> Unit = {+ if (state != null && states.size > 1) DropdownMenu({+ states.map { other -> MenuItem(other.computer.name, selected = other.computer.id == state.computer.id, verbatim = true) { accounts.noteActive(other.computer.id) } }+ }, label = "Computer: ${state.computer.name}") { ComputerBadge(state.hello?.text("device"), 28.dp, state.computer.color) }}- // The remote screen opens over the app once its sheets have slid away.- LaunchedEffect(state.screenRequest) { if (state.screenRequest != null) { closeAll(); showUsage = false } }- ScreenLayer(state, store)- // One place for 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 || creatingBot || creatingGroup || editor != null || groupEditor != null- CodyncDialog("Something went wrong", state.error != null && !inline, store::clearError, state.error, cancel = "OK") { emptyList() }+ if (state == null || store == null) UsageScreen(null, {}, {}, picker)+ else key(state.computer.id) { UsageScreen(state, store::refreshUsage, store::reloadUsage, picker) }}-/** The remote screen as a full-window layer that fades in and out (iOS `.codyncOverlay`). */-@Composable private fun ScreenLayer(state: AppState, store: AppStore) {+/** The remote screen as a full-window layer that fades in and out (iOS `.codyncOverlay`); it keeps its computer while fading. */+@Composable private fun ScreenLayer(state: AppState?, store: AppStore?) {val visible = remember { MutableTransitionState(false) }- visible.targetState = state.screenRequest != null+ visible.targetState = state != null && store != null+ var shown by remember { mutableStateOf<Pair<AppState, AppStore>?>(null) }+ if (state != null && store != null) shown = state to storeif (!visible.currentState && !visible.targetState) return+ val (current, owner) = shown ?: returnOverlay {AnimatedVisibility(visible, enter = fadeIn(Motion.layout()), exit = fadeOut(Motion.fade())) {AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.RemoteScreen))- ScreenView(state, store, state.screenRequest?.watching, store::closeScreen)+ key(current.computer.id) { ScreenView(current, owner, current.screenRequest?.watching, owner::closeScreen) }}}}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/CodyncWidgets.kt b/apps/android/app/src/main/kotlin/com/codync/android/CodyncWidgets.ktindex b15eb2e8..ac2cc3a8 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/CodyncWidgets.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/CodyncWidgets.kt@@ -376,7 +376,7 @@ private fun stateWord(bot: WidgetBot): Pair<String, Ink> = when (bot.status) {Column(GlanceModifier.fillMaxWidth()) {for (bot in bots) {val (word, tint) = stateWord(bot)- val open = if (sample) GlanceModifier else GlanceModifier.clickable(actionStartActivity(widgetIntent(context, feed, bot.id)))+ val open = if (sample) GlanceModifier else GlanceModifier.clickable(actionStartActivity(widgetIntent(context, feed, bot)))Row(open.fillMaxWidth().padding(bottom = 8.dp), verticalAlignment = Alignment.CenterVertically) {Face(context, bot.avatarShape, bot.avatarColor, 24.dp, customIcon = bot.customIcon)Spacer(GlanceModifier.width(7.dp))@@ -397,7 +397,7 @@ private fun stateWord(bot: WidgetBot): Pair<String, Ink> = when (bot.status) {Row(GlanceModifier.fillMaxWidth().defaultWeight()) {for ((column, bot) in row.withIndex()) {if (column > 0) Spacer(GlanceModifier.width(8.dp))- val open = if (sample || bot == null) GlanceModifier else GlanceModifier.clickable(actionStartActivity(widgetIntent(context, feed, bot.id)))+ val open = if (sample || bot == null) GlanceModifier else GlanceModifier.clickable(actionStartActivity(widgetIntent(context, feed, bot)))Box(open.defaultWeight().fillMaxHeight().background(tile).cornerRadius(16.dp), contentAlignment = Alignment.Center) {if (bot == null) Face(context, "blob", "gray", 26.dp)else Column(horizontalAlignment = Alignment.CenterHorizontally) {@@ -411,11 +411,12 @@ private fun stateWord(bot: WidgetBot): Pair<String, Ink> = when (bot.status) {}}-internal fun widgetIntent(context: Context, feed: WidgetFeed, bot: String? = null, usage: Boolean = false): Intent {+/** Opens the app: on [bot]'s chat (on its computer), on the usage computer's Usage, or as it is. */+internal fun widgetIntent(context: Context, feed: WidgetFeed, bot: WidgetBot? = null, usage: Boolean = false): Intent {val intent = Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)- val computer = feed.computerId ?: return intent+ val computer = bot?.computerId?.ifEmpty { null } ?: feed.computerId ?: return intentif (bot != null || usage) intent.data = Uri.Builder().scheme(BuildConfig.URL_SCHEME).authority(if (usage) "usage" else "bot")- .apply { if (bot != null) appendPath(bot) }.appendQueryParameter("scope", feed.scope).appendQueryParameter("computer", computer).build()+ .apply { if (bot != null) appendPath(bot.id) }.appendQueryParameter("scope", feed.scope).appendQueryParameter("computer", computer).build()return intent}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.ktnew file mode 100644index 00000000..b32b8d53--- /dev/null+++ b/apps/android/app/src/main/kotlin/com/codync/android/ComputerSection.kt@@ -0,0 +1,157 @@+package com.codync.android++import android.content.Context+import androidx.compose.animation.AnimatedVisibility+import androidx.compose.animation.core.animateFloatAsState+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+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+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.rotate+import androidx.compose.ui.semantics.CustomAccessibilityAction+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.semantics.clearAndSetSemantics+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.customActions+import androidx.compose.ui.semantics.heading+import androidx.compose.ui.semantics.role+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.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(",")) }+}++/**+ * A computer's heading above its bots: badge, name and connection. Tap folds its bots away; touch and hold,+ * then drag, moves the computer (on this device); [extensions] opens its own Extensions while it's reachable.+ */+@Composable internal fun ComputerSection(state: AppState, empty: Boolean, folded: Boolean, stale: Boolean, toggle: () -> Unit,+ move: (Int) -> Unit, extensions: (() -> Unit)?, modifier: Modifier = Modifier, drag: ContextDrag? = null) {+ val translate = translator()+ val turn by animateFloatAsState(if (folded) -90f else 0f, Motion.layout(), label = "Chevron")+ val link = state.connection+ val status = if (stale) computerStatusText(state, true) else statusText(state)+ val offline = (link is LinkState.ComputerOffline || link is LinkState.Failed) && !state.isUpdating+ Column(modifier.fillMaxWidth().padding(top = 22.dp, bottom = 2.dp)) {+ Row(Modifier.fillMaxWidth().contextActions(onClick = toggle, reorder = drag) { emptyList() }+ .clearAndSetSemantics {+ heading()+ contentDescription = "${state.hostName}, ${translate(status)}"+ stateDescription = translate(if (folded) "Collapsed" else "Expanded")+ customActions = listOfNotNull(+ CustomAccessibilityAction(translate(if (folded) "Expand" else "Collapse")) { toggle(); true },+ CustomAccessibilityAction(translate("Move up")) { move(-1); true },+ CustomAccessibilityAction(translate("Move down")) { move(1); true },+ extensions?.let { open -> CustomAccessibilityAction(translate("Extensions")) { open(); true } },+ )+ }.padding(vertical = 4.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {+ ComputerBadge(state.hello?.text("device"), 20.dp, state.computer.color)+ Text(state.hostName, Modifier.weight(1f, fill = false), style = Type.subheadline.semibold, color = Palette.secondary,+ maxLines = 1, overflow = TextOverflow.Ellipsis)+ // The connection sits at the trailing edge, before the heading's buttons.+ Spacer(Modifier.weight(1f).width(8.dp))+ Text(tr(status), style = Type.subheadline, color = if (offline) Palette.warning else Palette.tertiary, maxLines = 1,+ overflow = TextOverflow.Ellipsis)+ if (link is LinkState.Ready) Symbol(if (link.route == HostRoute.Direct) "wifi" else "cloud", size = 15.dp, tint = Palette.tertiary)+ Box(Modifier.size(40.dp), contentAlignment = Alignment.Center) {+ Symbol("chevron.down", Modifier.rotate(turn), size = 14.dp, tint = Palette.tertiary)+ }+ // After the chevron, as on the iPhone and the desktop.+ if (extensions != null) Box(Modifier.size(44.dp, 40.dp).semantics { contentDescription = translate("Extensions"); this.role = Role.Button }+ .plainButton(action = extensions), contentAlignment = Alignment.Center) {+ Symbol("square.grid.2x2", size = 16.dp, tint = Palette.secondary)+ }+ }+ AnimatedVisibility(empty && !folded, enter = fadeIn(Motion.fade()), exit = fadeOut(Motion.fade())) {+ Text(tr("No bots yet"), Modifier.padding(bottom = 4.dp), style = Type.footnote, color = Palette.tertiary)+ }+ }+}++/** The roster's only connection surface: a quiet summary, with the computers to show, reconnect and Computers on demand. */+@Composable internal fun ComputerFilterHeader(states: List<AppState>, hidden: String, setHidden: (String) -> Unit, reconnect: () -> Unit,+ 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()+ DropdownMenu({+ listOf(+ MenuItem("All computers", icon = "desktopcomputer", selected = selection.shown.size == states.size) { setHidden("") },+ *states.map { state ->+ MenuItem(state.hostName, icon = computerSymbol(state.hello?.text("device")), selected = state.computer.id in selection.shown,+ verbatim = true, detail = translate(connectionLabel(state))) { setHidden(selection.toggling(state.computer.id)) }+ }.toTypedArray(),+ *(if (states.size > 1) arrayOf(MenuItem("Show only", children = states.map { state ->+ MenuItem(state.hostName, icon = computerSymbol(state.hello?.text("device")), verbatim = true) { setHidden(selection.only(state.computer.id)) }+ })) else emptyArray()),+ 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") {+ 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)+ 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.ktindex 59f3924c..a5755c9d 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@@ -48,39 +48,46 @@ import com.kyant.shapes.RoundedRectangleimport kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.put-/** Computer management: every computer this phone can use or ask for, and the way to pair another (iOS `ComputersView`). */-@Composable internal fun ComputersView(state: AppState, store: AppStore, pair: () -> Unit, ask: (CloudComputer) -> Unit, extensions: () -> Unit) {- val signedIn = state.account.userId != null- val paired = state.computers.firstOrNull()- var confirmForget by remember { mutableStateOf(false) }+/**+ * Computer management: every computer this phone can use or ask for (paired here and in the account,+ * merged by computer ID), and the way to pair another (iOS `ComputersView`).+ */+@Composable internal fun ComputersView(app: AccountContext, states: List<AppState>, accounts: AccountStore, pair: () -> Unit, ask: (CloudComputer) -> Unit,+ extensions: (String) -> Unit) {+ val signedIn = app.account.userId != null+ var confirmForget by remember { mutableStateOf<AppState?>(null) }var confirmRevoke by remember { mutableStateOf<CloudComputer?>(null) }- var coloring by remember { mutableStateOf(false) }- var voice by remember { mutableStateOf(false) }- var network by remember { mutableStateOf(false) }- LaunchedEffect(state.contextId) { store.refreshCloud() }+ var coloring by remember { mutableStateOf<String?>(null) }+ var voice by remember { mutableStateOf<String?>(null) }+ var network by remember { mutableStateOf<String?>(null) }+ LaunchedEffect(app.contextId) { accounts.refreshCloud() }Column(Modifier.fillMaxSize().background(Palette.background)) {PageHeader("Computer management", icon = "gearshape")// One card per computer, so each one's rows read as its own.- PullToRefresh(store::refreshComputers, Modifier.weight(1f)) { CardForm {- if (paired != null) {- val inAccount = state.cloudComputers.firstOrNull { it.computerId == paired.id }+ PullToRefresh(accounts::refreshComputers, Modifier.weight(1f)) { CardForm {+ for (state in states) {+ val id = state.computer.id+ val store = accounts.store(id) ?: continue+ val inAccount = app.cloudComputers.firstOrNull { it.computerId == id }CardSection {- computerRows(state, store, inAccount != null, ComputerActions(extensions, store::openScreen, voice = { voice = true },- network = { network = true }, color = { coloring = true }, ask = inAccount?.let { c -> { ask(c) } },- revoke = inAccount?.takeIf { it.isGranted }?.let { c -> { confirmRevoke = c } }) { confirmForget = true })+ computerRows(state, store, inAccount != null, app.isStale(state, states), app.access[id]?.code,+ ComputerActions({ extensions(id) }, store::openScreen, voice = { voice = id }, network = { network = id }, color = { coloring = id },+ ask = inAccount?.let { c -> { ask(c) } }, revoke = inAccount?.takeIf { it.isGranted }?.let { c -> { confirmRevoke = c } }) {+ confirmForget = state+ })}}- for (computer in state.cloudComputers.filter { it.computerId != paired?.id }) CardSection {+ // Account computers this phone isn't set up for yet.+ for (computer in app.cloudComputers.filter { c -> app.computers.none { it.id == c.computerId } }) CardSection {row {- if (state.isOlderCopy(computer)) OlderCopyRow(computer)- else AccountComputerRow(computer, state.access?.takeIf { it.computerId == computer.computerId }?.code,- askingAnother = state.askingAccess.let { it != null && it != computer.computerId },- ask = { ask(computer) }, revoke = { confirmRevoke = computer })+ if (app.isOlderCopy(computer)) OlderCopyRow(computer)+ else AccountComputerRow(computer, app.access[computer.computerId]?.code,+ asking = computer.computerId in app.asking, ask = { ask(computer) }, revoke = { confirmRevoke = computer })}}- val hidden = state.bots.filter { it.hidden && !it.deleted }+ val hidden = states.flatMap { state -> state.bots.filter { it.hidden && !it.deleted }.map { state to it } }if (hidden.isNotEmpty()) CardSection("Hidden bots") {- for (bot in hidden) row { HiddenBotRow(state, store, bot) }+ for ((state, bot) in hidden) row { accounts.store(state.computer.id)?.let { HiddenBotRow(state, it, bot) } }}CardSection(footer = if (signedIn) "Computers in your account need your OK on the computer before this phone can use them."else "Each bot runs on its own computer. Sign in to see the computers in your account.") {@@ -94,16 +101,22 @@ import kotlinx.serialization.json.put}} }}- CodyncSheet(voice, { voice = false }) { VoiceChatSettings(state, store) }- CodyncSheet(network, { network = false }) { state.network?.let { NetworkSheet(it, store::refreshNetwork) } }- SwatchPanel(coloring, paired?.color, { coloring = false }, store::setColor)- CodyncDialog(tr("Remove {name}?").replace("{name}", paired?.name ?: "computer"), confirmForget, { confirmForget = false },+ val voiceState = states.firstOrNull { it.computer.id == voice }+ CodyncSheet(voiceState, { voice = null }) { state -> accounts.store(state.computer.id)?.let { VoiceChatSettings(state, it) } }+ val networkState = states.firstOrNull { it.computer.id == network }+ 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) }+ 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.") {- listOf(DialogAction("Remove", destructive = true, action = store::removeComputer))+ listOfNotNull(forgetting?.let { target -> DialogAction("Remove", destructive = true) { accounts.removeComputer(target.computer.id) } })}CodyncDialog("Revoke this phone's access to ${confirmRevoke?.name ?: "the computer"}?", confirmRevoke != null, { confirmRevoke = null },"You can ask for access again; the computer will show a new code to confirm.") {- listOfNotNull(confirmRevoke?.let { target -> DialogAction("Revoke", destructive = true) { store.revokeAccess(target.computerId) } })+ listOfNotNull(confirmRevoke?.let { target -> DialogAction("Revoke", destructive = true) { accounts.revokeAccess(target.computerId) } })}}@@ -117,8 +130,8 @@ private class ComputerActions(val extensions: () -> Unit, val screen: () -> Unit* (saved with the computer, so another account's computer keeps its own), how it's reached, the Codync it runs* (and its update) and, for a stale pairing, Remove (iOS `ComputerRows`).*/-private fun CardRows.computerRows(state: AppState, store: AppStore, inAccount: Boolean, actions: ComputerActions) {- row { ComputerSummary(state, inAccount, actions) }+private fun CardRows.computerRows(state: AppState, store: AppStore, inAccount: Boolean, stale: Boolean, code: String?, actions: ComputerActions) {+ row { ComputerSummary(state, inAccount, stale, code, actions) }if (state.connection is LinkState.Ready) {row { RowLabel("Extensions", "square.grid.2x2", chevron = true, modifier = Modifier.plainButton(action = actions.extensions)) }row { RowLabel("Voice chat", "waveform", chevron = true, modifier = Modifier.plainButton(action = actions.voice)) }@@ -126,23 +139,23 @@ private fun CardRows.computerRows(state: AppState, store: AppStore, inAccount: Bif (state.network?.shown == true) row { RowLabel("Network", NETWORK_ICON, chevron = true, modifier = Modifier.plainButton(action = actions.network)) }}if (BuildConfig.PUSH_CONFIGURED) row {- ComputerNotificationsRow(state.computers.first().notifications, store::notifications)+ ComputerNotificationsRow(state.computer.notifications, store::notifications)}- row { ConnectionRow(state.computers.first(), store) }+ row { ConnectionRow(state.computer, store) }// Kept while an update asked from here restarts the computer: its spinner says it's updating.if ((state.connection is LinkState.Ready || state.isUpdating) && state.hello != null) row { CodyncVersionRow(state, store::requestHostUpdate) }- if (state.isStale && !inAccount) row { RowLabel("Remove", "trash", Palette.danger, modifier = Modifier.plainButton(action = actions.remove)) }+ if (stale && !inAccount) row { RowLabel("Remove", "trash", Palette.danger, modifier = Modifier.plainButton(action = actions.remove)) }}/** Name, connection, and an access request when this phone can't reach the computer; a long press opens its menu. */-@Composable private fun ComputerSummary(state: AppState, inAccount: Boolean, actions: ComputerActions) {- val computer = state.computers.first()+@Composable private fun ComputerSummary(state: AppState, inAccount: Boolean, stale: Boolean, code: String?, actions: ComputerActions) {+ val computer = state.computerval link = state.connectionval online = link is LinkState.Readyval detail = if (link is LinkState.Ready) {val count = state.bots.count { !it.deleted && it.kind != "group" }"$count bot${if (count == 1) "" else "s"} · ${routeLabel(link.route, computer.cloud)}"- } else computerStatusText(state)+ } else computerStatusText(state, stale)Column(Modifier.fillMaxWidth().contextActions(items = {listOfNotNull(MenuItem("Color", icon = "paintpalette", action = actions.color),@@ -162,7 +175,7 @@ private fun CardRows.computerRows(state: AppState, store: AppStore, inAccount: Bval unreachable = (link is LinkState.ComputerOffline || link is LinkState.Failed) && !state.isUpdatingText(detail, style = Type.footnote, color = if (unreachable) Palette.warning else Palette.secondary)if (unreachable && actions.ask != null) {- SecondaryButton(if (state.access?.computerId == computer.id) "Show code" else "Ask for access", action = actions.ask)+ SecondaryButton(if (code != null) "Show code" else "Ask for access", action = actions.ask)}}}@@ -203,8 +216,8 @@ private const val NETWORK_ICON = "codync.network"}}-/** A computer in the account that this phone can't use yet; `askingAnother` while this phone asks a different one. */-@Composable private fun AccountComputerRow(computer: CloudComputer, code: String?, askingAnother: Boolean, ask: () -> Unit,+/** A computer in the account that this phone can't use yet; [asking] while this phone's request is on its way to it. */+@Composable private fun AccountComputerRow(computer: CloudComputer, code: String?, asking: Boolean, ask: () -> Unit,revoke: () -> Unit) {val online = if (computer.online == true) "Online" else "Offline"val detail = when {@@ -222,7 +235,7 @@ private const val NETWORK_ICON = "codync.network"when {code != null -> SecondaryButton("Code", action = ask)computer.isGranted -> SecondaryButton("Revoke", action = revoke)- else -> SecondaryButton("Ask for access", enabled = !askingAnother, action = ask)+ else -> SecondaryButton("Ask for access", enabled = !asking, action = ask)}}}@@ -244,7 +257,7 @@ private const val NETWORK_ICON = "codync.network"BotAvatar(bot, state.bots, 28.dp)Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(1.dp)) {Text(bot.name, style = Type.body, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)- Text(state.hello?.text("name") ?: state.computers.firstOrNull()?.name.orEmpty(), style = Type.caption, color = Palette.tertiary)+ Text(state.hostName, style = Type.caption, color = Palette.tertiary)}IconButton("Unhide", "eye") {store.command("updateBot", buildJsonObject { put("id", bot.id); put("hidden", false) }, "roster:" + bot.id)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.ktindex de3e1ef3..c855e2ce 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@@ -14,7 +14,7 @@ import com.codync.android.core.Pairingprivate val LinkState.unauthorized get() = this is LinkState.Failed && status == 403/** One short line for the computer's connection, next to its name (iOS `BotStore.statusText`). */-internal fun statusText(state: AppState): String = if (state.computers.isEmpty()) "Not paired" else if (state.isUpdating) "Updating…" else when (val link = state.connection) {+internal fun statusText(state: AppState): String = if (state.isUpdating) "Updating…" else when (val link = state.connection) {is LinkState.Ready -> if (state.mismatch != null) "Needs update" else "Online"LinkState.Connecting -> "Connecting…"is LinkState.ComputerOffline -> link.lastSeenAt?.let { "Offline · seen ${RelativeTime.day(it)}" } ?: "Offline"@@ -22,11 +22,11 @@ internal fun statusText(state: AppState): String = if (state.computers.isEmpty()}/** The status line in Computer management: one that's offline while its new identity is around says so. */-internal fun computerStatusText(state: AppState): String =- if (state.isStale && !state.connection.unauthorized) "Older copy of this computer · ${statusText(state)}" else statusText(state)+internal fun computerStatusText(state: AppState, stale: Boolean): String =+ if (stale && !state.connection.unauthorized) "Older copy of this computer · ${statusText(state)}" else statusText(state)/** A word for the link: the computer filter's rows and the chat header. */-internal fun connectionLabel(state: AppState): String = if (state.computers.isEmpty()) "Not paired" else when (val link = state.connection) {+internal fun connectionLabel(state: AppState): String = when (val link = state.connection) {is LinkState.Ready -> if (state.mismatch != null) "Needs update" else "Connected"LinkState.Connecting -> "Connecting…"is LinkState.ComputerOffline -> "Offline"@@ -37,11 +37,10 @@ internal fun connectionLabel(state: AppState): String = if (state.computers.isEminternal fun connectionDescription(state: AppState): String {val link = state.connectionreturn when {- state.computers.isEmpty() -> "Not paired"link == LinkState.Connecting -> "Connecting"link !is LinkState.Ready -> connectionLabel(state)state.mismatch != null -> "Needs update"- link.route == HostRoute.Relay -> connectedThrough(state.computers.firstOrNull()?.cloud)+ link.route == HostRoute.Relay -> connectedThrough(state.computer.cloud)else -> "Connected over Wi-Fi or Tailscale"}}@@ -95,39 +94,41 @@ internal fun pairingLine(cloud: String?): String {internal fun pairingLine(pasted: String, scheme: String): String =pairingLine(runCatching { Pairing.parse(pasted, scheme).computer.cloud }.getOrNull())-/** "1 connected", "Connecting…", "No access": the roster header's summary of its computers. */-internal fun connectionSummary(state: AppState): String = when {- state.computers.isEmpty() -> "Computers"- state.connection is LinkState.Ready -> "${state.computers.size} connected"- state.connection is LinkState.Connecting -> "Connecting…"- state.connection.unauthorized -> "No access"- else -> "${state.computers.size} offline"+/** "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"+ 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"+ }}/**- * The computer this phone uses won't come back as it is: it turned this phone away, or it's offline- * while an account computer with its name that joined after it was last seen is online, the same+ * A computer this phone uses that won't come back as it is: it turned this phone away, or it's offline+ * while a computer with its name that joined the account after it was last seen is online, the same* machine under a new identity (iOS `AccountStore.isStale`). Account computers offer access recovery; only independently paired computers offer removal.*/-internal val AppState.isStale: Boolean get() {- val computer = computers.firstOrNull() ?: return false- return when (val link = connection) {- is LinkState.Failed -> link.unauthorized || renamedCopyOnline(computer)- is LinkState.ComputerOffline -> renamedCopyOnline(computer)+internal fun AccountContext.isStale(state: AppState, others: Collection<AppState>): Boolean {+ val computer = state.computer+ val seen = cloudComputers.firstOrNull { it.computerId == computer.id }?.lastSeenAt ?: (state.connection as? LinkState.ComputerOffline)?.lastSeenAt+ val renamedCopyOnline = others.any { it.computer.id != computer.id && it.computer.name == computer.name && it.connection is LinkState.Ready && replacedBy(it.computer.id, seen) }+ || cloudComputers.any { it.computerId != computer.id && it.name == computer.name && it.online == true && replacedBy(it.computerId, seen) }+ return when (val link = state.connection) {+ is LinkState.Failed -> link.unauthorized || renamedCopyOnline+ is LinkState.ComputerOffline -> renamedCopyOnlineelse -> false}}-private fun AppState.renamedCopyOnline(computer: Computer): Boolean {- val seen = cloudComputers.firstOrNull { it.computerId == computer.id }?.lastSeenAt ?: (connection as? LinkState.ComputerOffline)?.lastSeenAt- return cloudComputers.any { it.computerId != computer.id && it.name == computer.name && it.online == true && replacedBy(it.computerId, seen) }-}-/*** A computer last [seen] no later than account computer [id] joined the account was replaced by it;* seen after, it ran beside it: another machine with the same name. Without both times the name decides.*/-private fun AppState.replacedBy(id: String, seen: Long?): Boolean {+private fun AccountContext.replacedBy(id: String, seen: Long?): Boolean {seen ?: return trueval claimed = cloudComputers.firstOrNull { it.computerId == id }?.claimedAt ?: return truereturn seen <= claimed@@ -137,7 +138,7 @@ private fun AppState.replacedBy(id: String, seen: Long?): Boolean {* An offline account computer named like one this phone uses or sees online, and [replacedBy] it: most* likely the same machine under an earlier identity (its host keys were reset), left behind in the account.*/-internal fun AppState.isOlderCopy(computer: CloudComputer): Boolean {+internal fun AccountContext.isOlderCopy(computer: CloudComputer): Boolean {if (computer.online == true) return falseval seen = computer.lastSeenAt// The current copy may be paired with its code without being listed in the account.diff --git a/apps/android/app/src/main/kotlin/com/codync/android/CustomIconEditor.kt b/apps/android/app/src/main/kotlin/com/codync/android/CustomIconEditor.ktindex ee3804e6..ad4d9e8b 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/CustomIconEditor.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/CustomIconEditor.kt@@ -18,19 +18,21 @@ import com.codync.android.design.*@Composable internal fun CustomIconEditor(target: String, state: AppState, store: AppStore) {if (state.hello?.containsKey("icons") != true) returnvar needsSignIn by remember { mutableStateOf(false) }- val requireAccount: (() -> Unit) -> Unit = { action -> if (state.account.userId != null) action() else needsSignIn = true }+ val accounts = LocalAccounts.current+ val account = accounts?.state?.collectAsState()?.value+ val requireAccount: (() -> Unit) -> Unit = { action -> if (account?.account?.userId != null) action() else needsSignIn = true }var url by remember(target) { mutableStateOf("") }var showURL by remember(target) { mutableStateOf(false) }val icon = state.icons[target]val busy = "icon:$target" in state.busy- val enabled = !busy && state.account.ready && "session" !in state.busy && state.actualConnection is LinkState.Ready+ val enabled = !busy && account?.account?.ready == true && "session" !in account.busy && state.actualConnection is LinkState.Readyval picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->uri?.let { requireAccount { store.setIcon(target, file = it) } }}CodyncDialog("Sign in required", needsSignIn, { needsSignIn = false }, message = "Sign in to use custom images.") {listOf(- DialogAction("Continue with Apple") { store.signIn(SignInProvider.Apple) },- DialogAction("Continue with Google") { store.signIn(SignInProvider.Google) },+ DialogAction("Continue with Apple") { accounts?.signIn(SignInProvider.Apple) },+ DialogAction("Continue with Google") { accounts?.signIn(SignInProvider.Google) },)}Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(12.dp)) {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.ktnew file mode 100644index 00000000..567d1251--- /dev/null+++ b/apps/android/app/src/main/kotlin/com/codync/android/Dictation.kt@@ -0,0 +1,192 @@+package com.codync.android++import android.content.Context+import android.content.Intent+import android.os.Build+import android.os.Bundle+import android.speech.RecognitionListener+import android.speech.RecognizerIntent+import android.speech.SpeechRecognizer+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+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.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.Job+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAll+import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.launch+import kotlinx.coroutines.sync.Semaphore+import kotlinx.coroutines.sync.withPermit++/**+ * 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) {+ var listening by mutableStateOf(false); private set+ /** Recorded for a provider, waiting for its transcript. */+ var transcribing by mutableStateOf(false); private set+ /** When it started listening (`elapsedRealtime`), for the pill's time. */+ var startedAt by mutableLongStateOf(0L); private set+ /** The microphone's level while listening, 0…1. */+ var level by mutableFloatStateOf(0f); private set+ /** Why the last dictation ended early (no network or microphone), until the next. */+ var failure by mutableStateOf<String?>(null)+ /** 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+ /** 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. */+ private var edit: (((String) -> String) -> Unit)? = null+ /** The box when dictation started. */+ private var before = ""+ private var transcription: Job? = null+ /** 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())++ /** 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) {+ 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) }+ }++ /** The pill's stop: on-device speech has already typed its words; a recording gets transcribed. */+ fun finish() {+ val recorded = recording ?: return stop()+ val apply = edit+ stop()+ val pcm = recorded.pcm.toByteArray()+ if (pcm.size < DictationText.MIN_BYTES) return+ val asked = generation+ transcribing = true+ transcription = scope.launch {+ try {+ val said = transcribe(pcm, recorded.provider, recorded.store)+ 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." }+ finally { if (asked == generation) transcribing = false }+ }+ }++ /** Stops now (another chat, a call, a send) and drops anything still on its way. */+ fun stop() {+ generation+++ transcription?.cancel(); transcription = null+ recognizer?.cancel(); recognizer?.destroy(); recognizer = null+ mic?.let { old -> scope.launch { old.stop() } }; mic = null+ recording = null+ transcribing = false+ edit = null+ listening = false+ level = 0f+ }++ 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 }+ // 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)+ val language = VoicePreferences.language(context).ifEmpty { Locale.getDefault().toLanguageTag() }+ engine.setRecognitionListener(Listener(asked, language))+ 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))+ }++ /** 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) {+ try {+ val status = store.voiceStatus()+ store.voiceChoices().remember(status)+ if (asked != generation) return+ if (!status.configured(provider)) { 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)+ 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() } }+ }+ } catch (cancelled: CancellationException) { throw cancelled }+ catch (_: Exception) { if (asked == generation) failure = "The microphone isn't available."; return }+ if (asked != generation) { microphone.stop(); return }+ mic = microphone+ this.edit = edit+ recording = take+ startedAt = android.os.SystemClock.elapsedRealtime()+ 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+ edit?.invoke { DictationText.join(start, text) }+ 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) }+ 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+ // 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."+ else -> "Couldn't hear you. Check the microphone and Android's speech settings."+ }+ stop()+ }+ override fun onReadyForSpeech(params: Bundle?) { }+ override fun onBeginningOfSpeech() { }+ override fun onBufferReceived(buffer: ByteArray?) { }+ override fun onEndOfSpeech() { }+ override fun onEvent(eventType: Int, params: Bundle?) { }+ }+}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.ktnew file mode 100644index 00000000..750edeef--- /dev/null+++ b/apps/android/app/src/main/kotlin/com/codync/android/DictationControls.kt@@ -0,0 +1,111 @@+package com.codync.android++import android.Manifest+import android.content.pm.PackageManager+import android.os.SystemClock+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.animation.AnimatedContent+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.animation.scaleIn+import androidx.compose.animation.togetherWith+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.height+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.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.semantics.Role+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import androidx.core.content.ContextCompat+import com.codync.android.core.VoiceProvider+import com.codync.android.design.*+import com.kyant.shapes.Capsule+import kotlinx.coroutines.delay++/**+ * Dictation beside send / call (iOS `Composer.micButton`): the mic and its engine menu in one light capsule; while it+ * listens or transcribes, the recording pill. A missing provider key opens Voice chat settings; a failure, its dialog.+ */+@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 permission = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->+ if (granted) start() else dictation.failure = "Allow microphone access in Settings to dictate."+ }+ AnimatedContent(dictation.listening || dictation.transcribing, transitionSpec = {+ (fadeIn(Motion.morph()) + scaleIn(Motion.morph(), 0.9f)) togetherWith fadeOut(Motion.morph())+ }, label = "Dictation") { recording ->+ if (recording) RecordingPill(dictation, height)+ else Row(Modifier.height(height).clip(Capsule()).background(Palette.bubbleAgent), verticalAlignment = Alignment.CenterVertically) {+ val (source, pressed) = rememberPress()+ Box(Modifier.size(height).pressScale(pressed).clickable(source, null, role = Role.Button) {+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) start()+ else permission.launch(Manifest.permission.RECORD_AUDIO)+ }.semantics { contentDescription = "Dictate" }, contentAlignment = Alignment.Center) {+ Symbol("mic", size = 18.dp, tint = Palette.secondary)+ }+ DictationEngineMenu(store, height)+ }+ }+ CodyncSheet(dictation.needsKey, { dictation.needsKey = false }) { VoiceChatSettings(state, store) }+ CodyncDialog("Couldn't dictate", dictation.failure != null, { dictation.failure = null }, dictation.failure, cancel = "OK") { emptyList() }+}++/** Beside the mic, in its capsule: which speech dictation uses, on-device or a provider on the user's own key. */+@Composable private fun DictationEngineMenu(store: AppStore, height: Dp) {+ val choices = remember { store.voiceChoices() }+ var engine by remember { mutableStateOf(choices.dictation) }+ DropdownMenu({+ listOf(MenuItem("On device", selected = engine == null) { engine = null; choices.dictation = null }) ++ VoiceProvider.entries.map { provider -> MenuItem(provider.title, selected = engine == provider) { engine = provider; choices.dictation = provider } }+ }, Modifier.height(height).padding(end = 6.dp).width(20.dp), label = "Dictation engine") {+ Symbol("chevron.up", Modifier.align(Alignment.Center), size = 12.dp, tint = Palette.secondary)+ }+}++/**+ * Dictation in progress, in place of the mic (iOS `RecordingPill`): stop, the time since it started and dots that+ * follow the microphone's level; a spinner once a recording waits for its transcript.+ */+@Composable private fun RecordingPill(dictation: Dictation, height: Dp) {+ Row(Modifier.height(height).clip(Capsule()).background(Palette.bubbleAgent).padding(start = 4.dp, end = 10.dp),+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {+ if (dictation.transcribing) {+ Box(Modifier.size(height - 8.dp), contentAlignment = Alignment.Center) { Spinner(14.dp) }+ Text(tr("Transcribing…"), style = Type.subheadline, color = Palette.secondary)+ } else {+ val (source, pressed) = rememberPress()+ Box(Modifier.size(height - 8.dp).pressScale(pressed).clip(Capsule()).clickable(source, null, role = Role.Button, onClick = dictation::finish)+ .semantics { contentDescription = "Stop dictating" }, contentAlignment = Alignment.Center) {+ Symbol("stop.fill", size = 12.dp, tint = Palette.text)+ }+ var now by remember { mutableLongStateOf(SystemClock.elapsedRealtime()) }+ LaunchedEffect(dictation.startedAt) { while (true) { now = SystemClock.elapsedRealtime(); delay(500) } }+ val seconds = ((now - dictation.startedAt) / 1000).coerceAtLeast(0)+ Text("%d:%02d".format(seconds / 60, seconds % 60), style = Type.subheadline.monospacedDigit, color = Palette.text)+ LevelDots(dictation.level, speaking = false, working = false, connecting = false, color = Palette.text,+ modifier = Modifier.size(32.dp, 12.dp).semantics { contentDescription = "Listening" })+ }+ }+}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.ktnew file mode 100644index 00000000..47dfc177--- /dev/null+++ b/apps/android/app/src/main/kotlin/com/codync/android/HandoffRows.kt@@ -0,0 +1,109 @@+package com.codync.android++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.RowScope+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.foundation.text.selection.SelectionContainer+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.unit.dp+import com.codync.android.core.Entry+import com.codync.android.design.*+import com.kyant.shapes.RoundedRectangle+import kotlinx.coroutines.launch+import kotlinx.serialization.json.JsonObject++/**+ * The bot's chat starts over (iOS `HandoffCardRow`): what the new conversation carries, which the user can edit until+ * their next message sends it, or turn down to carry on with this one. Once sent, the line unfolds to what it carried.+ */+@Composable internal fun HandoffCardRow(entry: Entry, card: JsonObject, state: AppState, store: AppStore) {+ var expanded by remember { mutableStateOf(false) }+ var editing by remember { mutableStateOf(false) }+ val carried = card.text("text").orEmpty()+ val label: @Composable RowScope.() -> Unit = {+ Symbol("arrow.triangle.branch", size = 13.dp, tint = Palette.secondary)+ Spacer(Modifier.width(6.dp))+ Text(entry.text, Modifier.weight(1f, fill = false), style = Type.footnote, color = Palette.secondary)+ }+ val what: @Composable () -> Unit = {+ SelectionContainer {+ Text(carried, Modifier.fillMaxWidth(), style = Type.footnote.copy(fontFamily = FontFamily.Monospace), color = Palette.secondary)+ }+ }+ if (card.text("status") == "draft") {+ Column(Modifier.padding(end = 40.dp).clip(RoundedRectangle(14.dp)).background(Palette.bubbleAgent).padding(12.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp)) {+ Row(verticalAlignment = Alignment.CenterVertically, content = label)+ Disclosure(expanded, { expanded = !expanded }, Modifier.fillMaxWidth(), {+ Text(tr("What it carries"), style = Type.footnote.medium, color = Palette.text)+ }) { what() }+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ if ("handoff:${entry.id}" in state.busy) Spinner()+ else {+ SecondaryButton("Keep this conversation") { store.keepConversation(entry) }+ IconButton("Edit what it carries", "pencil") { editing = true }+ }+ }+ }+ CodyncSheet(editing, { editing = false }) { HandoffEditor(entry, carried, store) }+ } else Disclosure(expanded, { expanded = !expanded }, Modifier.fillMaxWidth(), label) { what() }+}++/** Edits what the next conversation starts with (iOS `HandoffEditorView`). */+@Composable private fun HandoffEditor(entry: Entry, initial: String, store: AppStore) {+ var text by remember { mutableStateOf(initial) }+ var saving by remember { mutableStateOf(false) }+ val dismiss = LocalDismissModal.current+ val scope = rememberCoroutineScope()+ val trimmed = text.trim()+ Column {+ ModalHeader("Edit the handoff") {+ if (saving) Spinner()+ else IconButton("Save", "checkmark", enabled = trimmed.isNotEmpty()) {+ saving = true+ scope.launch { if (store.editHandoff(entry, trimmed)) dismiss(); saving = false }+ }+ }+ CardForm {+ CardSection(footer = "Your next message starts a fresh conversation that begins with this.") {+ row {+ val style = Type.footnote.copy(fontFamily = FontFamily.Monospace, color = Palette.text)+ BasicTextField(text, { text = it }, Modifier.fillMaxWidth().heightIn(min = 180.dp), textStyle = style,+ cursorBrush = SolidColor(Palette.accent), decorationBox = { field ->+ if (text.isEmpty()) Text(tr("What the new conversation should know"), style = style, color = Palette.tertiary)+ field()+ })+ }+ }+ }+ }+}++/** 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/LeadBotTile.kt b/apps/android/app/src/main/kotlin/com/codync/android/LeadBotTile.ktindex 03cbcfec..26f1ccee 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/LeadBotTile.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/LeadBotTile.kt@@ -39,7 +39,7 @@ class LeadBotTile : TileService() {override fun onClick() {val feed = WidgetStore.feed(this)// No bot at work: Computer management, as the iPhone's control does.- val intent = mostUrgentBot(feed.bots)?.let { widgetIntent(this, feed, it.id) }+ val intent = mostUrgentBot(feed.bots)?.let { widgetIntent(this, feed, it) }?: widgetIntent(this, feed).setData(Uri.parse("${BuildConfig.URL_SCHEME}://computers"))// A bot's chat is private: the phone unlocks first.unlockAndRun {diff --git a/apps/android/app/src/main/kotlin/com/codync/android/LiveUpdateGallery.kt b/apps/android/app/src/main/kotlin/com/codync/android/LiveUpdateGallery.ktindex 9a8bd60f..ed1c3d22 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/LiveUpdateGallery.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/LiveUpdateGallery.kt@@ -85,7 +85,7 @@ internal object LiveUpdates {* The Live update and Status bar pages: one switch (the chip shows the same Live update), a* sample task in any phase, and what each presentation shows.*/-@Composable internal fun LiveUpdateGallery(state: AppState, store: AppStore?, chip: Boolean) {+@Composable internal fun LiveUpdateGallery(app: AccountContext, accounts: AccountStore?, chip: Boolean) {val context = LocalContext.currentval notifications = rememberOnResume { notificationsAllowed(context) }val promoted = rememberOnResume { LiveUpdates.promoted(context) }@@ -93,7 +93,7 @@ internal object LiveUpdates {val started = remember { System.currentTimeMillis() - 154_000 }Column(Modifier.fillMaxWidth().clip(RoundedRectangle(20.dp)).background(Palette.surface).padding(16.dp),verticalArrangement = Arrangement.spacedBy(10.dp)) {- CodyncSwitch(state.tasks, { store?.taskNotifications(it) }) {+ CodyncSwitch(app.tasks, { accounts?.taskNotifications(it) }) {Text(if (chip) "Show in the status bar" else "Show Live updates", style = Type.subheadline.medium, color = Palette.text)}Text(if (chip) "The status bar chip shows the same Live update as the Lock Screen, so this switch turns off both."diff --git a/apps/android/app/src/main/kotlin/com/codync/android/LocalStore.kt b/apps/android/app/src/main/kotlin/com/codync/android/LocalStore.ktindex 21876911..ae2a9c3b 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/LocalStore.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/LocalStore.kt@@ -73,6 +73,10 @@ class LocalStore(context: Context, val contextId: String = "local") {write(AtomicFile(File(directory, "computers.json")), json.encodeToString(computers).toByteArray())}+ /** The computer a chat was last opened or sent on (iOS `lastComputerId`). */+ fun lastComputer(): String? = File(directory, "last-computer").takeIf { it.exists() }?.readText()?.takeIf { it.isNotBlank() }+ fun saveLastComputer(id: String) = write(AtomicFile(File(directory, "last-computer")), id.toByteArray())+fun setupComplete(): Boolean = File(directory, "setup-complete").exists()fun hasIdentity(): Boolean = File(directory, "identity").exists()fun completeSetup() = write(AtomicFile(File(directory, "setup-complete")), byteArrayOf(1))diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MainActivity.kt b/apps/android/app/src/main/kotlin/com/codync/android/MainActivity.ktindex c5ce7c4d..9808832a 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/MainActivity.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/MainActivity.kt@@ -36,7 +36,7 @@ import kotlinx.coroutines.launchimport okio.Path.Companion.toOkioPathclass MainActivity : ComponentActivity() {- private val store: AppStore by viewModels()+ private val accounts: AccountStore by viewModels()override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)AppearancePreferences.initialize(applicationContext)@@ -49,10 +49,11 @@ class MainActivity : ComponentActivity() {if (savedInstanceState == null) lifecycleScope.launch { CodyncWidgets.publishPreviews(applicationContext) }enableEdgeToEdge()setContent {- val state by store.state.collectAsStateWithLifecycle()+ val state by accounts.state.collectAsStateWithLifecycle()+ val computers by accounts.computerStates.collectAsStateWithLifecycle()val notifications = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->notificationsAnswered(applicationContext, granted, PromptSource.Automatic)- store.syncPush()+ accounts.syncPush()}LaunchedEffect(state.computers.isNotEmpty(), state.contextId) {if (BuildConfig.PUSH_CONFIGURED && state.computers.isNotEmpty() && android.os.Build.VERSION.SDK_INT >= 33 && !PushPreferences.asked(applicationContext)) {@@ -86,22 +87,22 @@ class MainActivity : ComponentActivity() {key(state.contextId, state.generation) {val appearance by AppearancePreferences.mode.collectAsStateWithLifecycle()val dark = appearance.isDark(isSystemInDarkTheme())- val darkBars = dark || state.screenRequest != null+ val darkBars = dark || computers.values.any { it.screenRequest != null }SideEffect {WindowCompat.getInsetsController(window, window.decorView).apply {isAppearanceLightStatusBars = !darkBarsisAppearanceLightNavigationBars = !darkBars}}- CodyncTheme(dark = dark) { OverlayRoot { CodyncApp(state, store); LaunchLayer(state.loading) } }+ CodyncTheme(dark = dark) { OverlayRoot { CodyncApp(state, computers, accounts); LaunchLayer(state.loading) } }}}}// Rotation keeps its ViewModel/navigation; process restoration gets a fresh owner.- if (savedInstanceState?.getString("codync:activityOwner") != store.activityOwnerId) handle(intent)+ if (savedInstanceState?.getString("codync:activityOwner") != accounts.activityOwnerId) handle(intent)}override fun onSaveInstanceState(outState: Bundle) {- outState.putString("codync:activityOwner", store.activityOwnerId)+ outState.putString("codync:activityOwner", accounts.activityOwnerId)super.onSaveInstanceState(outState)}override fun onNewIntent(intent: Intent) {@@ -109,9 +110,9 @@ class MainActivity : ComponentActivity() {setIntent(intent)handle(intent)}- override fun onStart() { super.onStart(); store.setForeground(true); Analytics.becameActive(applicationContext) }+ override fun onStart() { super.onStart(); accounts.setForeground(true); Analytics.becameActive(applicationContext) }override fun onStop() {- store.setForeground(false)+ accounts.setForeground(false)// A rotation isn't a trip to the background.if (!isChangingConfigurations) Analytics.enteredBackground()super.onStop()@@ -124,14 +125,14 @@ class MainActivity : ComponentActivity() {}if (uri.scheme == BuildConfig.URL_SCHEME && uri.host == "pair") {intent.data = null- store.pair(uri.toString(), PairedVia.Link)+ accounts.pair(uri.toString(), PairedVia.Link)}// Retain the scoped, non-secret destination for Activity/process restoration.- if (uri.scheme == BuildConfig.URL_SCHEME && uri.host in setOf("bot", "usage")) store.openLink(uri)- if (uri.scheme == BuildConfig.URL_SCHEME && uri.host == "oauth") { intent.data = null; store.finishConnectorSignIn(uri) }- if (uri.scheme == BuildConfig.URL_SCHEME && uri.host == "screen") { intent.data = null; store.openScreenLink() }- if (uri.scheme == BuildConfig.URL_SCHEME && uri.host == "computers") { intent.data = null; store.openPage(LinkPage.Computers) }- if (uri.scheme == BuildConfig.URL_SCHEME && uri.host == "plugins") { intent.data = null; store.openPage(LinkPage.Extensions) }+ if (uri.scheme == BuildConfig.URL_SCHEME && uri.host in setOf("bot", "usage")) accounts.openLink(uri)+ if (uri.scheme == BuildConfig.URL_SCHEME && uri.host == "oauth") { intent.data = null; accounts.finishConnectorSignIn(uri) }+ if (uri.scheme == BuildConfig.URL_SCHEME && uri.host == "screen") { intent.data = null; accounts.openScreenLink() }+ if (uri.scheme == BuildConfig.URL_SCHEME && uri.host == "computers") { intent.data = null; accounts.openPage(LinkPage.Computers) }+ if (uri.scheme == BuildConfig.URL_SCHEME && uri.host == "plugins") { intent.data = null; accounts.openPage(LinkPage.Extensions) }}}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.ktindex 0da232f8..6cfe5f42 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@@ -11,8 +11,12 @@ import androidx.compose.foundation.layout.asPaddingValuesimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.layout.navigationBarsimport androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Columnimport androidx.compose.runtime.Composableimport androidx.compose.runtime.getValue+import androidx.compose.runtime.key+import androidx.compose.runtime.rememberimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.saveable.rememberSaveableimport androidx.compose.runtime.setValue@@ -33,11 +37,14 @@ private enum class AppTab { Bots, State, Settings }* The system tab bar over Bots, State and Settings, as iOS `RootView.tabs`: every tab stays alive, the bar* floats as glass over their content and hides while a conversation is open.*/-@Composable internal fun MainTabs(state: AppState, store: AppStore, account: () -> Unit, manage: () -> Unit, usage: () -> Unit,- newBot: () -> Unit, newGroup: () -> Unit, edit: (Bot) -> Unit, chat: @Composable () -> Unit) {+@Composable internal fun MainTabs(app: AccountContext, states: List<AppState>, accounts: AccountStore, account: () -> Unit, manage: () -> Unit,+ usage: () -> Unit, newBot: (String) -> Unit, newGroup: (String) -> Unit, edit: (String, Bot) -> Unit, extensions: (String) -> Unit,+ chat: @Composable (AppState) -> Unit) {var tab by rememberSaveable { mutableStateOf(AppTab.Bots) }+ // The open chat, on whichever computer it lives (one at a time).+ val open = states.firstOrNull { it.selectedBot != null }// Opening a bot (notification, widget, link) always lands on the Bots tab.- if (state.selectedBot != null && tab != AppTab.Bots) tab = AppTab.Bots+ if (open != null && tab != AppTab.Bots) tab = AppTab.BotsAnalyticsOnAppear(AnalyticsEvent.ScreenViewed(when (tab) {AppTab.Bots -> AnalyticsScreen.BotsAppTab.State -> AnalyticsScreen.State@@ -46,14 +53,19 @@ private enum class AppTab { Bots, State, Settings }val bottom = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding()val barSpace = bottom + 62.dp + 24.dpGlassStage(Modifier.fillMaxSize(), chrome = {- // An access request still waiting after its sheet closed: the code to check, until the computer answers.- val ticket = state.access- AnimatedVisibility(ticket != null && state.selectedBot == null, Modifier.align(Alignment.BottomCenter).padding(bottom = barSpace - 16.dp),+ // Access requests still waiting after their sheet closed: the code to check, until the computer answers.+ val tickets = app.access.values.sortedBy { it.requestId }+ AnimatedVisibility(tickets.isNotEmpty() && open == null, Modifier.align(Alignment.BottomCenter).padding(bottom = barSpace - 16.dp),enter = fadeIn(Motion.fade()) + slideInVertically(Motion.layoutOffset) { it }, exit = fadeOut(Motion.fade()) + slideOutVertically(Motion.layoutOffset) { it }) {- if (ticket != null) AccessBanner(ticket, state.cloudComputers.firstOrNull { it.computerId == ticket.computerId }?.name ?: "Your computer",- store::cancelAccess)+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+ for (ticket in tickets) key(ticket.computerId) {+ AccessBanner(ticket, app.cloudComputers.firstOrNull { it.computerId == ticket.computerId }?.name ?: "Your computer") {+ accounts.cancelAccess(ticket.computerId)+ }+ }+ }}- AnimatedVisibility(state.selectedBot == null, Modifier.align(Alignment.BottomCenter),+ AnimatedVisibility(open == null, Modifier.align(Alignment.BottomCenter),enter = fadeIn(Motion.fade()) + slideInVertically(Motion.layoutOffset) { it / 2 },exit = fadeOut(Motion.fade()) + slideOutVertically(Motion.layoutOffset) { it / 2 }) {Box(contentAlignment = Alignment.BottomCenter) {@@ -65,13 +77,18 @@ private enum class AppTab { Bots, State, Settings }}}) {Box(Modifier.fillMaxSize().tabLayer(tab == AppTab.Bots)) {- NavStack(listOfNotNull("roster", state.selectedBot), key = { it }, pop = { store.openBot(null) }) { entry ->- if (entry == "roster") BotListView(state, store, account, manage, newBot, newGroup, edit, barSpace)- else chat()+ // A chat's entry names its computer and bot; it keeps its state while sliding away.+ var shown by remember { mutableStateOf<AppState?>(null) }+ if (open != null) shown = open+ NavStack(listOfNotNull("roster", open?.let { "${it.computer.id}/${it.selectedBot}" }), key = { it }, pop = { accounts.openBot(null) }) { entry ->+ if (entry == "roster") BotListView(app, states, accounts, account, manage, newBot, newGroup, edit, extensions, barSpace)+ else (states.firstOrNull { "${it.computer.id}/${it.selectedBot}" == entry } ?: shown)?.let { chat(it) }}}- Box(Modifier.fillMaxSize().tabLayer(tab == AppTab.State)) { StateScreen(state, store, usage, barSpace, active = tab == AppTab.State) }- Box(Modifier.fillMaxSize().tabLayer(tab == AppTab.Settings)) { SettingsView(state, store, barSpace) }+ Box(Modifier.fillMaxSize().tabLayer(tab == AppTab.State)) {+ StateScreen(app, states.firstOrNull { it.computer.id == app.currentComputerId }?.usage, accounts, usage, barSpace, active = tab == AppTab.State)+ }+ Box(Modifier.fillMaxSize().tabLayer(tab == AppTab.Settings)) { SettingsView(app, accounts, barSpace) }}}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MarketActions.kt b/apps/android/app/src/main/kotlin/com/codync/android/MarketActions.ktindex 67e5a7fb..e5090ef5 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/MarketActions.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/MarketActions.kt@@ -59,4 +59,4 @@ internal suspend fun AppStore.signInConnector(id: String, requestId: String? = n}/** The computer's own name (its hello), the one everything here installs on. */-internal val AppState.hostName: String get() = hello?.text("name") ?: computers.firstOrNull()?.name ?: "your computer"+internal val AppState.hostName: String get() = hello?.text("name") ?: computer.namediff --git a/apps/android/app/src/main/kotlin/com/codync/android/MarketplaceView.kt b/apps/android/app/src/main/kotlin/com/codync/android/MarketplaceView.ktindex 1eb01b70..26535dee 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/MarketplaceView.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/MarketplaceView.kt@@ -204,7 +204,7 @@ import kotlinx.coroutines.launchval count = connectors.size + state.plugins?.skills.orEmpty().sizeColumn(modifier.padding(top = 28.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {- ComputerBadge(state.hello?.text("device"), 32.dp, state.computers.firstOrNull()?.color)+ ComputerBadge(state.hello?.text("device"), 32.dp, state.computer.color)Column(Modifier.weight(1f)) {Text(tr("Extensions"), style = Type.title2.semibold, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)Text(state.hostName, style = Type.subheadline, color = Palette.secondary, maxLines = 1, overflow = TextOverflow.Ellipsis)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.ktindex ca4c051e..fb19784e 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@@ -1,18 +1,16 @@package com.codync.android-import androidx.compose.foundation.background+import android.content.res.Configuration+import android.text.format.DateUtilsimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.heightInimport androidx.compose.foundation.layout.padding-import androidx.compose.foundation.layout.size-import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.layout.widthimport androidx.compose.foundation.text.selection.SelectionContainer-import androidx.compose.foundation.verticalScrollimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffect@@ -23,168 +21,227 @@ import androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier-import androidx.compose.ui.layout.onVisibilityChanged+import androidx.compose.ui.platform.LocalConfiguration+import androidx.compose.ui.text.font.FontFamilyimport androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dp-import com.codync.android.core.MemoryDraft-import com.codync.android.core.MemoryFact+import com.codync.android.core.Bot+import com.codync.android.core.BotMemory+import com.codync.android.core.DreamRun+import com.codync.android.core.MemoryEntry+import com.codync.android.core.MemoryFileDetail+import com.codync.android.core.MemoryFilesimport com.codync.android.design.*-import java.text.DateFormat-import java.util.Date+import kotlinx.coroutines.launch+import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.put-private val FILTERS = listOf("all" to "All", "profile" to "About you", "pinned" to "Pinned", "review" to "Needs review")-private enum class Backup { Export, Import }+private enum class MemorySection { Yours, Bot, Dreams, Harness }-/** What a bot remembers, in its settings (iOS `MemoryCard`): search, edit, pin, history, backups. */-@Composable fun MemoryCard(botId: String, store: AppStore) {+/** What an info button explains. */+private enum class MemoryInfo { Harness, Dreams }++/** A note the sheet opens: its name and whose folder holds it. */+private data class MemoryNote(val name: String, val shared: Boolean)++/**+ * A bot's memory, read-only (iOS `MemoryCard`): what all your bots know about you, what this one knows, its dreams,+ * and its harness's own notes when the user kept them on. The user changes memory by telling the bot.+ */+@Composable internal fun MemoryCard(botId: String, state: AppState, store: AppStore) {+ val bot = state.bots.firstOrNull { it.id == botId }+ val memory = remember(botId) { MemoryModel(botId, store) }val scope = rememberCoroutineScope()- val memory = remember(botId) { MemoryModel(botId, store, scope) }- var editor by remember { mutableStateOf<MemoryDraft?>(null) }- var history by remember { mutableStateOf(false) }- var backup by remember { mutableStateOf<Backup?>(null) }- var confirmClear by remember { mutableStateOf(false) }- LaunchedEffect(botId) { memory.load() }- // At the end of bot details: viewed once it scrolls into sight, once per opening.- var viewed by remember(botId) { mutableStateOf(false) }- val seen = Modifier.onVisibilityChanged(minFractionVisible = 0f) { visible ->- if (visible && !viewed) { viewed = true; Analytics.capture(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Memory)) }- }- CardSection("Memory", modifier = seen, accessory = {- IconButton("Add memory", "plus", enabled = !memory.busy) { editor = MemoryDraft.of(botId, null) }- DropdownMenu({ listOf(- MenuItem("Refresh", icon = "arrow.clockwise") { memory.refresh() },- MenuItem("Export", icon = "square.and.arrow.up") { backup = Backup.Export; memory.export() },- MenuItem("Import", icon = "square.and.arrow.down") { backup = Backup.Import },- MenuItem("Forget everything", icon = "trash", destructive = true, divider = true) { confirmClear = true },- ) }, Modifier.size(32.dp), label = "More") { Symbol("ellipsis", size = 20.dp, tint = Palette.secondary) }- }) {- row {- Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {- SearchField(memory.query, { memory.search(it) }, Modifier.weight(1f), "Search memories")- ChoicePicker(memory.filter, FILTERS, { memory.search(memory.query, it) }, fill = Palette.bubbleAgent, label = "Show")+ var section by remember(botId) { mutableStateOf(MemorySection.Bot) }+ var info by remember { mutableStateOf<MemoryInfo?>(null) }+ var note by remember { mutableStateOf<MemoryNote?>(null) }+ // Entries and dreams showing all their lines.+ var unfolded by remember(botId) { mutableStateOf(emptySet<String>()) }+ AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Memory))+ // Memory changes anywhere move the bot's `memoryRev`: fetch again.+ LaunchedEffect(botId, bot?.memoryRev, bot?.sharedMemory, bot?.harnessMemory) { memory.load() }+ val view = memory.memory+ // The harness's tab goes when its memory is turned off (on another device too).+ LaunchedEffect(view?.projectMemory == null) { if (view != null && view.projectMemory == null && section == MemorySection.Harness) section = MemorySection.Bot }+ // A long memory stops at a few lines, fewer when the screen is short (landscape); tapping it shows the rest.+ val short = LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE+ val lines = { key: String -> if (key in unfolded) Int.MAX_VALUE else if (short) 2 else 5 }+ val unfold = { key: String -> unfolded = if (key in unfolded) unfolded - key else unfolded + key }+ val harness = backendName(state, bot?.backend ?: "claude")+ Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(10.dp)) {+ TabChoice(section, listOfNotNull(MemorySection.Yours to "About you", MemorySection.Bot to "This bot", MemorySection.Dreams to "Dreams",+ (MemorySection.Harness to harness).takeIf { view?.projectMemory != null }), { picked ->+ section = picked+ // Claude Code writes its notes outside Codync, so nothing moves `memoryRev`: read them again on the way in.+ if (picked == MemorySection.Harness) scope.launch { memory.load() }+ })+ CardSection {+ memory.error?.let { error -> row { SelectionContainer { Text(tr(error), color = Palette.danger) } } }+ when {+ view == null -> if (memory.error == null) row { Text(tr("Loading memory…"), color = Palette.secondary) }+ section == MemorySection.Yours || section == MemorySection.Bot ->+ layerRows(view, bot, section == MemorySection.Yours, state, store, harness, lines, unfold, { info = MemoryInfo.Harness }) { note = it }+ section == MemorySection.Dreams -> dreamRows(view.dreams, lines, unfold) { info = MemoryInfo.Dreams }+ else -> harnessRows(view.projectMemory)}}- memory.error?.let { row { SelectionContainer { Text(it, style = Type.body, color = Palette.danger) } } }- if (!memory.loaded && memory.error == null) row { Text("Loading memory…", style = Type.body, color = Palette.secondary) }- if (memory.loaded && memory.facts.isEmpty()) row {- Column(Modifier.fillMaxWidth().padding(vertical = 18.dp), horizontalAlignment = Alignment.CenterHorizontally,- verticalArrangement = Arrangement.spacedBy(8.dp)) {- Symbol("brain", size = 24.dp, tint = Palette.tertiary)- Text(if (memory.query.isEmpty() && memory.filter == "all") "Nothing yet. Important details are remembered as you chat." else "No matching memories.",- style = Type.body, color = Palette.secondary, textAlign = TextAlign.Center)- }- }- for (fact in memory.facts) row {- FactRow(fact, memory.busy, { editor = MemoryDraft.of(botId, fact) }) { pick ->- when (pick) {- "history" -> { history = true; memory.inspect(fact) }- else -> memory.action(pick, fact)- }- }+ }+ CodyncSheet(info, { info = null }) { shown ->+ when (shown) {+ MemoryInfo.Harness -> InfoSheet(harnessInfo(harness, when {+ bot?.harnessMemoryShared == true -> HarnessAccess.Shared+ bot?.backend == "claude" -> HarnessAccess.Readable+ else -> HarnessAccess.Hidden+ }))+ MemoryInfo.Dreams -> InfoSheet(DREAMS_INFO)}- if (memory.nextOffset != null) row {- Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {- LinkButton("Load more (${memory.total})", color = Palette.secondary) { memory.refresh(more = true) }- }+ }+ CodyncSheet(note, { note = null }) { MemoryNoteView(memory, it) }+}++/** One layer: its switches, what it holds against its cap, its entries and its notes. */+private fun CardRows.layerRows(view: BotMemory, bot: Bot?, shared: Boolean, state: AppState, store: AppStore, harness: String,+ lines: (String) -> Int, unfold: (String) -> Unit, aboutHarness: () -> Unit, open: (MemoryNote) -> Unit) {+ val layer = if (shared) view.yours else view.bot+ if (shared && bot != null) row {+ CodyncSwitch(bot.sharedMemory ?: view.shared, { store.setSharedMemory(bot, it) }, Modifier.fillMaxWidth()) {+ Text(tr("Use what your bots share"), style = Type.body, color = Palette.text)}}- CodyncSheet(editor, { editor = null }) { MemoryEditor(memory, it) }- CodyncSheet(history, { history = false }) { MemoryHistory(memory) }- CodyncSheet(backup, { backup = null }) { MemoryBackup(memory, it) }- CodyncDialog("Forget everything this bot remembers?", confirmClear, { confirmClear = false }) {- listOf(DialogAction("Forget everything", destructive = true) { memory.action("clearMemory") })+ // The harness's own memory: a switch where Codync can turn it off, "Shared" where every bot on it shares it.+ if (!shared && bot != null && (bot.harnessMemory != null || bot.harnessMemoryShared == true)) row {+ HarnessMemoryRow(bot, harness, store, aboutHarness)+ }+ row {+ Text(tr(if (shared) "Your name, time zone, people and lasting preferences, shared by your bots. {used} of {cap} in use. To change it, tell the bot."+ else "What this bot learned about you. {used} of {cap} in use. To change it, tell the bot.")+ .replace("{used}", "${layer.used}").replace("{cap}", "${layer.cap}"), style = Type.footnote, color = Palette.secondary)}+ if (layer.entries.isEmpty()) row { EmptyMemory("brain", if (shared) "Nothing shared yet." else "Nothing yet. What this bot learns about you shows up here.") }+ for (entry in layer.entries) row { EntryRow(entry, state, lines("entry:${entry.id}")) { unfold("entry:${entry.id}") } }+ view.files?.let { files -> noteRows(files, shared, open) }}-@Composable private fun FactRow(fact: MemoryFact, busy: Boolean, open: () -> Unit, act: (String) -> Unit) {- Row(verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy(8.dp)) {- Column(Modifier.weight(1f).plainButton(action = open), verticalArrangement = Arrangement.spacedBy(4.dp)) {- Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {- if (fact.pinned) Symbol("pin.fill", size = 12.dp, tint = Palette.secondary)- Text(fact.title.ifEmpty { fact.content.take(40) }, style = Type.body.semibold, color = Palette.text)- }- Text(fact.content, style = Type.body, color = Palette.text, maxLines = 3, overflow = TextOverflow.Ellipsis)- Text("${if (fact.kind == "profile") "About you" else fact.memoryType} · ${DateFormat.getDateInstance(DateFormat.MEDIUM).format(Date(fact.createdAt))} · " +- "${fact.revisionCount} revisions", style = Type.caption, color = Palette.secondary)+@Composable private fun HarnessMemoryRow(bot: Bot, harness: String, store: AppStore, about: () -> Unit) {+ val own = tr("{name}'s own memory").replace("{name}", harness)+ Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {+ Text(own, style = Type.body, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)+ IconButton(tr("About {name}'s own memory").replace("{name}", harness), "info.circle", action = about)+ Spacer(Modifier.weight(1f))+ val on = bot.harnessMemory+ if (on != null) CodyncSwitch(on, { store.setHarnessMemory(bot, it) }, Modifier.width(34.dp)) {}+ else Text(tr("Shared"), style = Type.body, color = Palette.secondary, maxLines = 1)+ }+}++@Composable private fun EntryRow(entry: MemoryEntry, state: AppState, lines: Int, unfold: () -> Unit) {+ Column(Modifier.fillMaxWidth().plainButton(action = unfold), verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {+ if (entry.pinned) Symbol("pin.fill", size = 12.dp, tint = Palette.secondary)+ Text(entry.text, style = Type.body, color = if (entry.archived) Palette.tertiary else Palette.text, maxLines = lines, overflow = TextOverflow.Ellipsis)}- DropdownMenu({ buildList {- add(MenuItem(if (fact.pinned) "Unpin" else "Pin", icon = if (fact.pinned) "pin.slash" else "pin") { act("pinMemory") })- add(MenuItem("History", icon = "clock.arrow.circlepath") { act("history") })- if (fact.reviewAfter != null) add(MenuItem("Mark reviewed", icon = "checkmark.circle") { act("reviewMemory") })- add(MenuItem("Forget", icon = "trash", destructive = true, divider = true) { act("forgetMemory") })- } }, Modifier.size(32.dp), enabled = !busy, label = "Memory actions") { Symbol("ellipsis", size = 20.dp, tint = Palette.secondary) }+ val author = when (entry.author) {+ "user" -> tr("You wrote it")+ "bot" -> tr("{name} remembered it").replace("{name}", state.bots.firstOrNull { it.id == entry.authorBot }?.name ?: tr("A bot"))+ "dream" -> tr("Dreaming")+ else -> tr("Moved from the old memory")+ }+ Text("$author · ${relative(entry.updatedAt)}${if (entry.archived) " · " + tr("archived") else ""}", style = Type.caption, color = Palette.secondary)}}-/** Add or edit one memory (iOS `MemoryEditorView`). */-@Composable private fun MemoryEditor(memory: MemoryModel, initial: MemoryDraft) {- val dismiss = LocalDismissModal.current- var draft by remember(initial) { mutableStateOf(initial) }- Column(Modifier.fillMaxSize().background(Palette.background)) {- ModalHeader(if (draft.id == null) "Add memory" else "Edit memory")- Column(Modifier.verticalScroll(rememberScrollState()).padding(20.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {- LabeledBox("Title") { FieldBox(draft.title, { draft = draft.copy(title = it) }, "Title", fill = Palette.surface) }- LabeledBox("Memory") {- Box(Modifier.heightIn(min = 160.dp)) { FieldBox(draft.content, { draft = draft.copy(content = it) }, "", 7, 20, fill = Palette.surface) }- }- Row(horizontalArrangement = Arrangement.spacedBy(14.dp)) {- for ((scope, label) in listOf("project" to "Work", "personal" to "About you", "global" to "General")) {- LinkButton(label, style = if (draft.scope == scope) Type.body.semibold else Type.body) { draft = draft.copy(scope = scope) }- }- }- LabeledBox("Category") { FieldBox(draft.memoryType, { draft = draft.copy(memoryType = it) }, "Category", fill = Palette.surface, capitalize = false) }- LabeledBox("Topic (optional)") { FieldBox(draft.topicKey, { draft = draft.copy(topicKey = it) }, "Topic (optional)", fill = Palette.surface, capitalize = false) }- memory.error?.let { Text(it, style = Type.body, color = Palette.danger) }- PrimaryButton(if (memory.busy) "Saving…" else "Save", enabled = !memory.busy && draft.title.isNotBlank() && draft.content.isNotBlank()) {- memory.save(draft) { dismiss() }+/** One layer's long-form notes under its entries: name, description, size and date, marked past a cap. The bot writes them. */+private fun CardRows.noteRows(files: MemoryFiles, shared: Boolean, open: (MemoryNote) -> Unit) {+ val live = (if (shared) files.yours else files.bot).files.filter { !it.deleted }+ row { Text(tr("Notes"), style = Type.footnote.semibold, color = Palette.secondary) }+ if (live.isEmpty()) row { Text(tr("Longer notes, one topic each. The bot reads one when its topic comes up."), style = Type.footnote, color = Palette.tertiary) }+ else if (live.size > files.folderCap) row {+ Text(tr("{count} notes, over the {cap}-note cap. Ask the bot to merge some.").replace("{count}", "${live.size}").replace("{cap}", "${files.folderCap}"),+ style = Type.footnote, color = Palette.attention)+ }+ for (file in live) row {+ Column(Modifier.fillMaxWidth().plainButton { open(MemoryNote(file.name, shared)) }, verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ Symbol("doc.text", size = 18.dp, tint = Palette.text)+ Text(file.name, style = Type.body, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)}+ file.description?.let { Text(it, style = Type.footnote, color = Palette.secondary, maxLines = 2, overflow = TextOverflow.Ellipsis) }+ val over = file.tokens > files.cap+ Text(tr(if (over) "{tokens} tokens, over the {cap} cap" else "{tokens} tokens").replace("{tokens}", "${file.tokens}")+ .replace("{cap}", "${files.cap}") + " · " + relative(file.updatedAt), style = Type.caption, color = if (over) Palette.attention else Palette.secondary)}}}-@Composable private fun LabeledBox(title: String, content: @Composable () -> Unit) {- Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {- Text(title, style = Type.caption, color = Palette.secondary)- content()+/** What dreaming did. */+private fun CardRows.dreamRows(runs: List<DreamRun>, lines: (String) -> Int, unfold: (String) -> Unit, about: () -> Unit) {+ row {+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ Text(tr("Between chats the bot tidies its memory from your own words."), Modifier.weight(1f), style = Type.footnote, color = Palette.secondary)+ IconButton("About dreaming", "info.circle", action = about)+ }+ }+ if (runs.isEmpty()) row { EmptyMemory("moon", "No dreams yet.") }+ for (run in runs) row {+ val limit = lines("dream:${run.id}")+ Column(Modifier.fillMaxWidth().plainButton { unfold("dream:${run.id}") }, verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Text(relative(run.at) + if (run.undone) " · " + tr("undone") else "", style = Type.body.semibold, color = Palette.text)+ for (change in run.added) Text("+ ${change.text}", style = Type.body, color = Palette.added, maxLines = limit, overflow = TextOverflow.Ellipsis)+ for (change in run.archived) Text("− ${change.text}", style = Type.body, color = Palette.removed, maxLines = limit, overflow = TextOverflow.Ellipsis)+ for (file in run.files.orEmpty()) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {+ Symbol("doc.text", size = 16.dp, tint = Palette.secondary)+ Text(tr("Added to {name}").replace("{name}", file.name), style = Type.body, color = Palette.secondary)+ }+ }}}-/** A memory's earlier versions and the session it came from (iOS `MemoryHistoryView`). */-@Composable private fun MemoryHistory(memory: MemoryModel) {- Column(Modifier.fillMaxSize().background(Palette.background)) {- ModalHeader("Memory history")- Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(20.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {- memory.error?.let { Text(it, style = Type.body, color = Palette.danger) }- val detail = memory.detail- if (detail == null) Text("Loading history…", style = Type.body, color = Palette.secondary)- else {- SelectionContainer { Text(detail.history.result, style = Type.body, color = Palette.text) }- detail.history.cursor?.let { cursor -> LinkButton("Older versions") { memory.inspect(detail.fact, cursor) } }- Text("Session timeline", style = Type.body.semibold, color = Palette.text)- SelectionContainer { Text(detail.timeline.result, style = Type.body, color = Palette.text) }- }+/** Claude Code's own notes, read-only here. */+private fun CardRows.harnessRows(project: BotMemory.Project?) {+ project ?: return+ row {+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Text(tr("Claude Code's own notes, read-only here."), style = Type.footnote, color = Palette.secondary)+ SelectionContainer { Text(project.path, style = Type.caption, color = Palette.tertiary) }}}+ if (project.text.isEmpty()) row { EmptyMemory("brain", "Nothing yet. Claude Code's notes show up here once it saves some.") }+ else row { SelectionContainer { Text(project.text, style = Type.body, color = Palette.text) } }}-/** Copy an Engram backup out, or paste one in (iOS `MemoryBackupView`). */-@Composable private fun MemoryBackup(memory: MemoryModel, mode: Backup) {- val dismiss = LocalDismissModal.current- var text by remember { mutableStateOf("") }- Column(Modifier.fillMaxSize().background(Palette.background)) {- ModalHeader(if (mode == Backup.Export) "Export memories" else "Import memories")- Column(Modifier.verticalScroll(rememberScrollState()).padding(20.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {- Text(if (mode == Backup.Export) "Copy this Engram backup to keep or import your memories."- else "Paste an Engram JSON backup. Import merges memories and preserves newer changes. A backup is saved first.",- style = Type.body, color = Palette.text)- if (mode == Backup.Export) SelectionContainer {- Text(memory.backup.ifEmpty { "Preparing backup…" }, style = Type.caption.monospaced, color = Palette.text)- } else {- Box(Modifier.heightIn(min = 280.dp)) { FieldBox(text, { text = it }, "", 12, 40, style = Type.caption.monospaced, fill = Palette.surface, capitalize = false) }- PrimaryButton("Import", enabled = !memory.busy && text.isNotEmpty()) { memory.importBackup(text) { dismiss() } }- }- memory.error?.let { Text(it, style = Type.body, color = Palette.danger) }+@Composable private fun EmptyMemory(icon: String, text: String) {+ Column(Modifier.fillMaxWidth().padding(vertical = 18.dp), horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(8.dp)) {+ Symbol(icon, size = 24.dp, tint = Palette.tertiary)+ Text(tr(text), style = Type.body, color = Palette.secondary, textAlign = TextAlign.Center)+ }+}++/** One note, to read (iOS `MemoryFileView`). */+@Composable private fun MemoryNoteView(memory: MemoryModel, note: MemoryNote) {+ var detail by remember(note) { mutableStateOf<MemoryFileDetail?>(null) }+ LaunchedEffect(note) { detail = memory.file(note.name, note.shared) }+ Column {+ ModalHeader(note.name)+ CardForm {+ memory.error?.let { error -> CardSection { row { SelectionContainer { Text(tr(error), color = Palette.danger) } } } }+ val shown = detail+ if (shown != null) CardSection(footer = shown.path) {+ row { SelectionContainer { Text(shown.content ?: tr("Deleted."), style = Type.footnote.copy(fontFamily = FontFamily.Monospace), color = Palette.text) } }+ } else CardSection { row { Text(tr("Loading…"), color = Palette.secondary) } }}}}++/** "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/MemoryInfoSheet.kt b/apps/android/app/src/main/kotlin/com/codync/android/MemoryInfoSheet.ktnew file mode 100644index 00000000..dbe483ce--- /dev/null+++ b/apps/android/app/src/main/kotlin/com/codync/android/MemoryInfoSheet.kt@@ -0,0 +1,71 @@+package com.codync.android++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.foundation.layout.padding+import androidx.compose.ui.unit.dp+import com.codync.android.design.*++// The memory screen's info buttons (iOS `MemoryInfoSheet`): what the harness's own memory means for the bot, and what+// dreaming does. The same text as the iPhone's and the desktop app's.++internal class InfoPoint(val icon: String, val title: String, val detail: String)++internal class InfoSheetContent(val title: String, val points: List<InfoPoint>)++/** How the bot reaches its harness's own memory. */+internal enum class HarnessAccess {+ /** A switch, and Codync shows the notes (Claude Code's are a file on the computer). */+ Readable,+ /** A switch only. */+ Hidden,+ /** No switch: one memory every bot on the harness shares (Hermes Agent, Gemini CLI). */+ Shared,+}++/** The harness's name goes in after the sentence is translated, so it stays as written. */+@Composable internal fun harnessInfo(harness: String, access: HarnessAccess): InfoSheetContent {+ val translate = translator()+ val fill = { template: String -> translate(template).replace("{name}", harness) }+ val shared = access == HarnessAccess.Shared+ return InfoSheetContent(fill("{name}'s own memory"), listOfNotNull(+ InfoPoint("brain", "A memory of its own", fill(if (shared) "{name} keeps notes apart from Codync's memory, and Codync can't turn them off for one bot."+ else "{name} keeps notes apart from Codync's memory. It's off by default, so this bot has one memory and you see all of it here.")),+ if (shared) InfoPoint("person.2", "Shared by every bot", fill("Every bot that runs {name} reads and writes the same notes, and so does {name} when you use it outside Codync.")) else null,+ InfoPoint("square.on.square", "Remembered twice", "With both on, the bot may save the same thing twice, and the two can disagree after something changes."),+ InfoPoint("trash", "Forgetting", fill("What the bot forgets in Codync stays in {name}'s notes. Codync can't change them.")),+ InfoPoint("eye", "Where to see it", fill(if (access == HarnessAccess.Readable) "Its notes show read-only under the {name} tab." else "Codync can't show it; look in {name} itself.")),+ if (shared) InfoPoint("gearshape", "Turning it off", fill("Where {name} has a setting for it, that setting turns it off for every session at once.")) else null,+ ))+}++internal val DREAMS_INFO = InfoSheetContent("Dreaming", listOf(+ InfoPoint("moon", "Tidying between chats", "After five quiet minutes or eight messages, or once memory is nearly full, the bot reads what you said since its last run and updates its memory."),+ InfoPoint("plus.circle", "Adds and takes out", "Green lines are memories it added. Red lines are ones it took out because they went out of date or moved into a note. It can also add a line to a note."),+ InfoPoint("text.bubble", "Only your words", "What it adds quotes something you typed yourself; pasted text, the bot's replies and other bots don't count. It never rewrites what you wrote. It may also put a passed date in the past tense, and before memory fills up it moves detail, word for word, into notes by topic, keeping one line per topic that points to its note."),+ InfoPoint("lock.shield", "Kept apart", "It runs in its own session, away from the chat, and fixed checks decide what it may save."),+ InfoPoint("eye", "A record", "This tab only shows what it did. To change a memory, tell the bot."),+))++@Composable internal fun InfoSheet(content: InfoSheetContent) {+ Column {+ ModalHeader(content.title)+ CardForm {+ CardSection {+ for (point in content.points) row {+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ Symbol(point.icon, Modifier.padding(top = 2.dp), size = 20.dp, tint = Palette.secondary)+ Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {+ Text(tr(point.title), style = Type.body, color = Palette.text)+ Text(tr(point.detail), style = Type.footnote, color = Palette.secondary)+ }+ }+ }+ }+ }+ }+}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MemoryModel.kt b/apps/android/app/src/main/kotlin/com/codync/android/MemoryModel.ktindex 81bdd230..340008fa 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/MemoryModel.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/MemoryModel.kt@@ -1,112 +1,41 @@package com.codync.androidimport androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableIntStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.setValue-import com.codync.android.core.MemoryDetail-import com.codync.android.core.MemoryDraft-import com.codync.android.core.MemoryFact-import com.codync.android.core.MemoryListing+import com.codync.android.core.BotMemory+import com.codync.android.core.MemoryFileDetailimport com.codync.android.core.WireJson-import java.util.UUIDimport kotlinx.coroutines.CancellationException-import kotlinx.coroutines.CoroutineScope-import kotlinx.coroutines.Job-import kotlinx.coroutines.delay-import kotlinx.coroutines.launch+import kotlinx.serialization.SerializationExceptionimport kotlinx.serialization.json.buildJsonObject-import kotlinx.serialization.json.contentOrNullimport kotlinx.serialization.json.decodeFromJsonElement-import kotlinx.serialization.json.jsonObject-import kotlinx.serialization.json.jsonPrimitiveimport kotlinx.serialization.json.put-/** One bot's Engram memory on the computer (iOS `MemoryStore`): search, edit, history and backups. */-internal class MemoryModel(private val botId: String, private val store: AppStore, private val scope: CoroutineScope) {- var facts by mutableStateOf(emptyList<MemoryFact>()); private set- var query by mutableStateOf(""); private set- var filter by mutableStateOf("all"); private set- var total by mutableIntStateOf(0); private set- var nextOffset by mutableStateOf<Int?>(null); private set- var loaded by mutableStateOf(false); private set- var busy by mutableStateOf(false); private set+/** One bot's memory, read-only: the bot changes it (iOS `MemoryStore`). */+internal class MemoryModel(private val botId: String, private val store: AppStore) {+ var memory by mutableStateOf<BotMemory?>(null); private setvar error by mutableStateOf<String?>(null)- var detail by mutableStateOf<MemoryDetail?>(null); private set- var backup by mutableStateOf(""); private setprivate var request = 0- private var detailRequest = 0- private var searching: Job? = null- suspend fun load(more: Boolean = false) {+ suspend fun load() {val asked = ++request- val offset = (if (more) nextOffset else 0) ?: return- error = nulltry {- val listing = MemoryListing.decode(store.hostCall("memory", buildJsonObject {- put("botId", botId); put("query", query); put("filter", filter); put("offset", offset)- }))- if (asked != request) return- facts = if (more) facts + listing.facts else listing.facts- total = listing.total; nextOffset = listing.nextOffset; loaded = true+ val value = WireJson.decodeFromJsonElement<BotMemory>(store.hostCall("memory", buildJsonObject { put("botId", botId) }))+ if (asked == request) { memory = value; error = null }} catch (cancelled: CancellationException) { throw cancelled }- catch (failure: Exception) { if (asked == request) error = failure.message ?: "Couldn't load memory." }- }-- fun refresh(more: Boolean = false) = scope.launch { load(more) }-- fun search(text: String, filter: String = this.filter) {- query = text; this.filter = filter; request++- searching?.cancel()- searching = scope.launch { delay(250); load() }- }-- fun action(method: String, fact: MemoryFact? = null) = perform {- store.hostCall(method, buildJsonObject { put("botId", botId); fact?.let { put("id", it.id); put("pinned", !it.pinned) } })- }-- fun save(draft: MemoryDraft, done: () -> Unit) = perform(done) { store.hostCall("saveMemory", draft.body()) }-- fun inspect(fact: MemoryFact, cursor: Int? = null) = scope.launch {- val asked = ++detailRequest- error = null- if (cursor == null) detail = null- try {- val value = WireJson.decodeFromJsonElement<MemoryDetail>(store.hostCall("memoryDetail", buildJsonObject {- put("botId", botId); put("id", fact.id); cursor?.let { put("historyCursor", it) }- }))- if (asked == detailRequest) detail = value- } catch (cancelled: CancellationException) { throw cancelled }- catch (failure: Exception) { if (asked == detailRequest) error = failure.message ?: "Couldn't load the history." }- }-- fun export() = scope.launch {- backup = ""; error = null- try {- val result = store.hostCall("exportMemory", buildJsonObject { put("botId", botId) }).jsonObject- // A big backup comes back as a file to read.- val upload = result["uploadId"]?.jsonPrimitive?.contentOrNull- backup = if (upload != null) store.hostFiles().readText(botId, upload) else result["json"]?.jsonPrimitive?.contentOrNull.orEmpty()- } catch (cancelled: CancellationException) { throw cancelled }- catch (failure: Exception) { error = failure.message ?: "Couldn't export memory." }- }-- fun importBackup(text: String, done: () -> Unit) = perform(done) {- if (text.toByteArray().size > 384 * 1024) {- val id = UUID.randomUUID().toString()- store.hostFiles().uploadText(botId, id, "engram-backup.json", text)- store.hostCall("importMemory", buildJsonObject { put("botId", botId); put("uploadId", id) })- } else store.hostCall("importMemory", buildJsonObject { put("botId", botId); put("json", text) })- }-- private fun perform(done: () -> Unit = {}, work: suspend () -> Unit) {- if (busy) return- busy = true; error = null- scope.launch {- try { work(); load(); done() }- catch (cancelled: CancellationException) { throw cancelled }- catch (failure: Exception) { error = failure.message ?: "Something went wrong." }- finally { busy = false }+ catch (failure: Exception) {+ // A host before 2.18.0 answers with its old memory listing, which has no layers or dreams.+ if (asked == request) error = if (failure is SerializationException || failure is IllegalArgumentException)+ "Update Codync on your computer to see this bot's memory." else failure.message ?: "Couldn't load memory."}}++ /** A long-form note as it is now. */+ suspend fun file(name: String, shared: Boolean): MemoryFileDetail? = try {+ WireJson.decodeFromJsonElement<MemoryFileDetail>(store.hostCall("memoryFile", buildJsonObject {+ put("botId", botId); put("file", name); put("shared", shared)+ }))+ } catch (cancelled: CancellationException) { throw cancelled }+ catch (failure: Exception) { error = failure.message ?: "Couldn't open the note."; null }}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.kt b/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.ktindex 301169f1..0e832bd9 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/MessageComposer.kt@@ -39,6 +39,7 @@ import androidx.compose.foundation.text.input.TextFieldLineLimitsimport androidx.compose.foundation.text.input.rememberTextFieldStateimport androidx.compose.material3.Textimport androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffectimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.remember@@ -106,8 +107,12 @@ private enum class Trailing { Interrupt, Stop, Call, Send }if (external != text.text.toString() && external !in echoes) text.setTextAndPlaceCursorAtEnd(external)}val clipboard = LocalClipboard.current- val clips = LocalContext.current.getSystemService(ClipboardManager::class.java)+ val context = LocalContext.current+ val clips = context.getSystemService(ClipboardManager::class.java)val scope = rememberCoroutineScope()+ // Dictation stops with its chat or draft (another chat, an artifact's box) and when the box goes.+ val dictation = remember(draftKey) { Dictation(context, scope) }+ DisposableEffect(dictation) { onDispose { dictation.stop() } }val photos = rememberLauncherForActivityResult(ActivityResultContracts.PickMultipleVisualMedia(10)) { uris ->if (uris.isNotEmpty()) store.importFiles(uris) { store.addDraftFiles(draftKey, it) }}@@ -160,6 +165,8 @@ private enum class Trailing { Interrupt, Stop, Call, Send }}}fun send() {+ // Words still on their way would land in the emptied box.+ dictation.stop()val command = if (files.isEmpty()) SlashCommands.builtIn(bot, typed, members) else nullif (command != null) run(command) else store.sendDraft(draftKey, bot.id, typed, replyTo) { clear(); cancelReply() }}@@ -210,11 +217,17 @@ private enum class Trailing { Interrupt, Stop, Call, Send }textStyle = Type.body.copy(color = Palette.text), cursorBrush = SolidColor(Palette.accent),lineLimits = TextFieldLineLimits.MultiLine(maxHeightInLines = 8),decorator = { input -> Box { if (text.text.isEmpty()) Text(placeholder, style = Type.body, color = Palette.tertiary, maxLines = 1, overflow = TextOverflow.Ellipsis); input() } })+ Box(Modifier.padding(bottom = 4.dp)) {+ DictationButton(dictation, state, store, 34.dp, { text.text.toString() }) { change ->+ text.setTextAndPlaceCursorAtEnd(change(text.text.toString()))+ }+ }TrailingButton(trailing, canSend, Modifier.padding(bottom = 4.dp)) {when (trailing) {Trailing.Interrupt -> onInterrupt?.invoke()Trailing.Stop -> store.command("stop", body("botId" to bot.id))- Trailing.Call -> onCall?.invoke()+ // The call takes the microphone.+ Trailing.Call -> { dictation.stop(); onCall?.invoke() }Trailing.Send -> send()}}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.ktindex 5ea3759f..70f88fd6 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@@ -41,7 +41,8 @@ import com.codync.android.core.LinkStateimport com.codync.android.design.*/** A new bot from its face and name (iOS `NewBotView`); the rest starts on the defaults and changes later in its Settings. */-@Composable fun NewBotView(state: AppState, store: AppStore) {+/** [computers] (ID, label) can take the bot; with more than one it can move to another before it's created ([choose]). */+@Composable fun NewBotView(state: AppState, store: AppStore, computers: List<Pair<String, String>> = emptyList(), choose: (String) -> Unit = {}) {var draft by remember { mutableStateOf(BotDraft()) }val online = state.actualConnection is LinkState.Readyval dismiss = LocalDismissModal.current@@ -50,7 +51,9 @@ import com.codync.android.design.*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) })- if (!online) Text("Connect this computer to create the bot.", style = Type.caption, color = Palette.warning)+ if (computers.size > 1) ValueRow("Computer") { ChoicePicker(state.computer.id, computers, choose, label = "Computer") }+ if (!online) Text(if (computers.size > 1) "Connect this computer to create the bot, or choose another computer."+ else "Connect this computer to create the bot.", style = Type.caption, color = Palette.warning)}}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/PairingView.kt b/apps/android/app/src/main/kotlin/com/codync/android/PairingView.ktindex 1cc11800..2e3bb316 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/PairingView.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/PairingView.kt@@ -75,7 +75,7 @@ private enum class ComputerOS { Mac, Linux }* Pair with a computer running codync-host, one thing per page: install it, then scan its code* (iOS `PairingView`). In a sheet it has a close button and closes once paired.*/-@Composable internal fun PairingView(state: AppState, store: AppStore, inModal: Boolean = false, onSkip: () -> Unit = {},+@Composable internal fun PairingView(state: AccountContext, store: AccountStore, inModal: Boolean = false, onSkip: () -> Unit = {},leading: @Composable RowScope.() -> Unit = {}) {var step by rememberSaveable { mutableStateOf(Step.Install) }var os by rememberSaveable { mutableStateOf(ComputerOS.Mac) }@@ -192,7 +192,7 @@ private enum class ComputerOS { Mac, Linux }// MARK: - Scan-@Composable private fun ScanPage(state: AppState, store: AppStore, os: ComputerOS, paired: () -> Unit) {+@Composable private fun ScanPage(state: AccountContext, store: AccountStore, os: ComputerOS, paired: () -> Unit) {val uri = LocalUriHandler.currentvar pasted by remember { mutableStateOf("") }var error by remember { mutableStateOf<String?>(null) }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.ktindex 55627c93..50a87e29 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@@ -83,7 +83,7 @@ object PushDelivery {if (!BuildConfig.PUSH_CONFIGURED) returnif (PushPreferences.retired(context) || local.contextId != (PushPreferences.activeUser(context) ?: "local")) returnval permitted = context.getSystemService(NotificationManager::class.java).areNotificationsEnabled()- val feed = TaskFeed(local.directory)+ val feed = TaskFeed(local.directory, computer.id)if (!PushPreferences.tasks(context) || !permitted) {feed.all().forEach { active.call("unregisterActivity", body("botId" to it.botId)) }feed.clear()@@ -122,18 +122,25 @@ object PushDelivery {withContext(Dispatchers.IO) { PushPreferences.splitSwitch(context) }val local = LocalStore(context, PushPreferences.activeUser(context) ?: "local")val computers = withContext(Dispatchers.IO) { local.computers() }- val computer = computers.firstOrNull() ?: return@withLock- if (!local.hasIdentity()) return@withLock- var active: EncryptedChannel? = null- try {- withTimeout(45_000) {- val identity = withContext(Dispatchers.IO) { local.identity() }- val connected = HostConnector.connect(computer, identity)- active = connected- connected.state.firstReady()- syncLocked(context, local, computer, connected)- }- } finally { active?.close() }+ if (computers.isEmpty() || !local.hasIdentity()) return@withLock+ // Every computer gets its turn; the first failure is reported once all were tried.+ var failure: Exception? = null+ for (computer in computers) {+ var active: EncryptedChannel? = null+ try {+ withTimeout(45_000) {+ val identity = withContext(Dispatchers.IO) { local.identity() }+ val connected = HostConnector.connect(computer, identity)+ active = connected+ connected.state.firstReady()+ syncLocked(context, local, computer, connected)+ }+ } catch (error: Exception) {+ if (error is CancellationException && error !is TimeoutCancellationException) throw error+ failure = failure ?: error+ } finally { active?.close() }+ }+ failure?.let { throw it }}const val WORK_NAME = "codync-push-registration"@@ -185,7 +192,7 @@ class PushService : FirebaseMessagingService() {NotificationDisplay.channels(context)if (data["kind"] == "task") {if (!PushPreferences.tasks(context)) return- val watch = TaskFeed(local.directory).remote(data, botId) ?: return+ val watch = TaskFeed(local.directory, computerId).remote(data, botId) ?: returnNotificationDisplay.task(context, scope, computerId, watch)return}@@ -292,8 +299,9 @@ internal object NotificationDisplay {return notification.build()}- fun cancel(context: Context, id: Int) {+ /** Notifications of one kind ([id]); with [prefix], only those whose tag starts with it (one computer's). */+ fun cancel(context: Context, id: Int, prefix: String = "") {val manager = context.getSystemService(NotificationManager::class.java)- manager.activeNotifications.filter { it.id == id }.forEach { manager.cancel(it.tag, it.id) }+ manager.activeNotifications.filter { it.id == id && it.tag.orEmpty().startsWith(prefix) }.forEach { manager.cancel(it.tag, it.id) }}}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/QrViewfinder.kt b/apps/android/app/src/main/kotlin/com/codync/android/QrViewfinder.ktindex ce6cf6f7..69662f53 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/QrViewfinder.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/QrViewfinder.kt@@ -32,7 +32,11 @@ import androidx.lifecycle.Observerimport androidx.lifecycle.compose.LocalLifecycleOwnerimport com.codync.android.core.PairingQrimport com.codync.android.core.PairingScan+import androidx.compose.foundation.gestures.detectTapGestures+import androidx.compose.ui.input.pointer.pointerInputimport java.util.concurrent.Executors+import java.util.concurrent.TimeUnit+import kotlinx.coroutines.delayimport java.util.concurrent.atomic.AtomicBoolean/**@@ -78,9 +82,11 @@ import java.util.concurrent.atomic.AtomicBooleanval main = ContextCompat.getMainExecutor(context)val reader = PairingQr(BuildConfig.URL_SCHEME)val preview = Preview.Builder().build().apply { setSurfaceProvider(view.surfaceProvider) }+ // A pairing code is dense and small on a laptop screen: at 720p it reads only from so close that many+ // main cameras can't focus. 1080p reads it from farther back, where they can.val analysis = ImageAnalysis.Builder().setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST).setResolutionSelector(ResolutionSelector.Builder().setResolutionStrategy(- ResolutionStrategy(Size(1280, 720), ResolutionStrategy.FALLBACK_RULE_CLOSEST_LOWER_THEN_HIGHER)).build()).build()+ ResolutionStrategy(Size(1920, 1080), ResolutionStrategy.FALLBACK_RULE_CLOSEST_LOWER_THEN_HIGHER)).build()).build()var lastFrame = 0Lanalysis.setAnalyzer(executor) { image ->try {@@ -127,8 +133,22 @@ import java.util.concurrent.atomic.AtomicBooleanexecutor.shutdownNow()}}+ // Continuous focus alone hunts on a glowing screen or settles on what's behind the code: focus where the code is+ // (the middle, or where it was tapped) again every couple of seconds until it reads.+ var focusAt by remember { mutableStateOf<MeteringPoint?>(null) }+ LaunchedEffect(camera, focusAt) {+ val active = camera ?: return@LaunchedEffect+ val point = focusAt ?: SurfaceOrientedMeteringPointFactory(1f, 1f).createPoint(0.5f, 0.5f, 0.3f)+ while (true) {+ active.cameraControl.startFocusAndMetering(FocusMeteringAction.Builder(point, FocusMeteringAction.FLAG_AF or FocusMeteringAction.FLAG_AE)+ .setAutoCancelDuration(2, TimeUnit.SECONDS).build())+ delay(2_500)+ }+ }Box(modifier) {- AndroidView(factory = { view }, modifier = Modifier.fillMaxSize())+ AndroidView(factory = { view }, modifier = Modifier.fillMaxSize().pointerInput(Unit) {+ detectTapGestures { focusAt = view.meteringPointFactory.createPoint(it.x, it.y) }+ })if (camera?.cameraInfo?.hasFlashUnit() == true) Box(Modifier.align(Alignment.BottomEnd).padding(12.dp)) {IconButton(if (torch) "Turn flashlight off" else "Turn flashlight on", "bolt", tint = Color.White) {val active = camera ?: return@IconButtondiff --git a/apps/android/app/src/main/kotlin/com/codync/android/RosterSectionViews.kt b/apps/android/app/src/main/kotlin/com/codync/android/RosterSectionViews.ktindex 4e434db9..99d0da91 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/RosterSectionViews.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/RosterSectionViews.kt@@ -99,10 +99,10 @@ import com.codync.android.design.** and none when the bot is in one; [move] puts the bot in a section (null: out of its own).*/internal fun sectionMenu(bot: Bot, sections: List<String>, move: (String?) -> Unit, newSection: () -> Unit): MenuItem {- val others = sections.filter { it != bot.section }.map { name -> MenuItem(name, verbatim = true) { move(name) } }- return MenuItem("Move to section", icon = "arrow.turn.down.right", children = others + listOfNotNull(- MenuItem("New section…", icon = "plus", divider = true, action = newSection),- if (bot.section != null) MenuItem("Remove from section", icon = "xmark.circle") { move(null) } else null,+ val others = sections.filter { it != bot.section }.map { name -> MenuItem(name, icon = "tray", verbatim = true) { move(name) } }+ return MenuItem("Move to section", icon = "tray", children = others + listOfNotNull(+ MenuItem("New section…", icon = "plus", divider = others.isNotEmpty(), action = newSection),+ if (bot.section != null) MenuItem("Remove from section", icon = "minus.circle") { move(null) } else null,))}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.kt b/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.ktindex 6c766b2f..7024902b 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.kt@@ -35,7 +35,7 @@ import com.codync.android.design.** analytics, Start over; iOS `SettingsView`). Each computer's own settings (voice chat, push, connection,* hidden bots) are in Computer management (`ComputersView`).*/-@Composable internal fun SettingsView(state: AppState, store: AppStore, bottomInset: Dp) {+@Composable internal fun SettingsView(state: AccountContext, store: AccountStore, bottomInset: Dp) {val uri = LocalUriHandler.currentvar confirmStartOver by remember { mutableStateOf(false) }var aboutAnalytics by remember { mutableStateOf(false) }diff --git a/apps/android/app/src/main/kotlin/com/codync/android/StateScreen.kt b/apps/android/app/src/main/kotlin/com/codync/android/StateScreen.ktindex 31f25900..4784a0ae 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/StateScreen.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/StateScreen.kt@@ -51,6 +51,7 @@ import androidx.compose.ui.semantics.headingimport androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.semantics.stateDescriptionimport androidx.compose.ui.unit.Dp+import kotlinx.serialization.json.JsonObjectimport androidx.compose.ui.unit.dpimport androidx.core.content.ContextCompatimport androidx.lifecycle.Lifecycle@@ -70,7 +71,7 @@ private enum class Surface { Widget, LiveUpdate, StatusBar }* widgets, Live updates (Android's Live Activity) and the status bar chip (its Dynamic Island).* Usage limits open from the header.*/-@Composable internal fun StateScreen(state: AppState, store: AppStore?, usage: () -> Unit, bottomInset: Dp, active: Boolean = true) {+@Composable internal fun StateScreen(app: AccountContext, report: JsonObject?, accounts: AccountStore?, usage: () -> Unit, bottomInset: Dp, active: Boolean = true) {var surface by rememberSaveable { mutableStateOf(Surface.Widget) }Column(Modifier.fillMaxSize().background(Palette.background).statusBarsPadding()) {ScreenHeader(title = { Text("State", style = Type.body.semibold, color = Palette.text) },@@ -82,9 +83,9 @@ private enum class Surface { Widget, LiveUpdate, StatusBar }Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(start = 18.dp, end = 18.dp, top = 18.dp, bottom = bottomInset),verticalArrangement = Arrangement.spacedBy(24.dp)) {when (shown) {- Surface.Widget -> WidgetGallery(state, store, active) { surface = Surface.LiveUpdate }- Surface.LiveUpdate -> LiveUpdateGallery(state, store, chip = false)- Surface.StatusBar -> LiveUpdateGallery(state, store, chip = true)+ Surface.Widget -> WidgetGallery(app, report, accounts, active) { surface = Surface.LiveUpdate }+ Surface.LiveUpdate -> LiveUpdateGallery(app, accounts, chip = false)+ Surface.StatusBar -> LiveUpdateGallery(app, accounts, chip = true)}}}@@ -115,13 +116,13 @@ internal fun openNotificationSettings(context: Context) = context.startActivity(.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))/** The State tab's Widget page: the installed widgets and these previews share their layouts. */-@Composable private fun WidgetGallery(state: AppState, store: AppStore?, active: Boolean, keepInView: () -> Unit) {+@Composable private fun WidgetGallery(app: AccountContext, usage: JsonObject?, accounts: AccountStore?, active: Boolean, keepInView: () -> Unit) {val context = LocalContext.currentval installed = rememberOnResume { runCatching { CodyncWidgets.installed(context) }.getOrNull() }var asked by remember { mutableIntStateOf(0) }val allowed = rememberOnResume { notificationsAllowed(context) } || asked > 0 && notificationsAllowed(context)val permission = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->- notificationsAnswered(context, granted, PromptSource.Widgets); asked++; store?.syncPush()+ notificationsAnswered(context, granted, PromptSource.Widgets); asked++; accounts?.syncPush()}var kind by rememberSaveable { mutableStateOf("usage") }var provider by rememberSaveable { mutableStateOf("claude") }@@ -142,7 +143,7 @@ internal fun openNotificationSettings(context: Context) = context.startActivity(Column(verticalArrangement = Arrangement.spacedBy(9.dp)) {SectionLabel("Get set up")Column(Modifier.fillMaxWidth().clip(RoundedRectangle(18.dp)).background(Palette.surface)) {- SetupRow("Connect a computer", state.computers.isNotEmpty())+ SetupRow("Connect a computer", app.computers.isNotEmpty())Hairline(Modifier.padding(start = 42.dp))SetupRow("Add a Codync widget", installed?.let { it > 0 } == true, if (installed == null) "Unable to check" else null)Hairline(Modifier.padding(start = 42.dp))@@ -164,7 +165,7 @@ internal fun openNotificationSettings(context: Context) = context.startActivity(Text("Sample data", style = Type.caption2, color = Palette.secondary)}ChoicePicker(kind, listOf("usage" to "Provider usage", "limits" to "Usage limits", "bots" to "Bots", "team" to "Team"), { kind = it })- val report = remember(state.usage) { runCatching { UsageReport.decode(state.usage) }.getOrNull() }+ val report = remember(usage) { usage?.let { runCatching { UsageReport.decode(it) }.getOrNull() } }val providers = (WidgetPreview.usage.providers + report?.providers.orEmpty()).distinctBy { it.id }if (kind == "usage") {if (providers.size <= 3) SegmentedChoice(provider, providers.map { it.id to it.name }, { provider = it })diff --git a/apps/android/app/src/main/kotlin/com/codync/android/TaskFeed.kt b/apps/android/app/src/main/kotlin/com/codync/android/TaskFeed.ktindex eaece763..a7f027df 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/TaskFeed.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/TaskFeed.kt@@ -12,9 +12,9 @@ data class TaskWatch(val taskId: String = java.util.UUID.randomUUID().toString()val seenRunning: Boolean = false, val timestamp: Long = 0, val lastRev: Long = 0, val deadline: Long = System.currentTimeMillis() + 900_000,val startedAt: Long = System.currentTimeMillis(), val avatarShape: String = "blob", val avatarColor: String = "blue", val activity: String = "")-/** Bounded delegation markers; inactive contexts never render or accept these updates. */-class TaskFeed(directory: File) {- private val file = AtomicFile(File(directory, "tasks.json"))+/** One computer's bounded delegation markers; inactive contexts never render or accept these updates. */+class TaskFeed(directory: File, computerId: String) {+ private val file = AtomicFile(File(directory, "tasks-$computerId.json"))fun all(): List<TaskWatch> = synchronized(lock) {if (!file.baseFile.exists()) emptyList() else WireJson.decodeFromString<List<TaskWatch>>(file.readFully().toString(Charsets.UTF_8))}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/UpdateNeededCard.kt b/apps/android/app/src/main/kotlin/com/codync/android/UpdateNeededCard.ktindex 5d7a29d9..7cdaca07 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/UpdateNeededCard.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/UpdateNeededCard.kt@@ -44,7 +44,7 @@ internal val AppState.mismatch: VersionMismatch? get() {/** Says which side has to update, shown instead of the composer and above the computer's bots. */@Composable internal fun UpdateNeededCard(state: AppState, mismatch: VersionMismatch, requestUpdate: () -> Unit, modifier: Modifier = Modifier) {- val host = state.hello?.text("name") ?: state.computers.firstOrNull()?.name ?: "your computer"+ val host = state.hostNameval now = rememberHostUpdateNow(state.hostUpdate)Row(modifier.fillMaxWidth().clip(RoundedRectangle(16.dp)).background(Palette.surface).padding(14.dp),verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy(12.dp)) {diff --git a/apps/android/app/src/main/kotlin/com/codync/android/UsageScreen.kt b/apps/android/app/src/main/kotlin/com/codync/android/UsageScreen.ktindex 9b808ebb..bf9a0810 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/UsageScreen.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/UsageScreen.kt@@ -48,16 +48,17 @@ import kotlin.math.roundToInt* Usage limits, opened from the State tab (iOS `UsageSheet` + `UsageView`): one card per* provider, the tightest limit as a big bar, every limit listed below. Pull down to refresh.*/-@Composable fun UsageScreen(state: AppState, refresh: (force: Boolean) -> Unit, reload: suspend () -> Unit) {+@Composable fun UsageScreen(state: AppState?, refresh: (force: Boolean) -> Unit, reload: suspend () -> Unit,+ trailing: @Composable () -> Unit = {}) {val dismiss = LocalDismissModal.current- val report = remember(state.usage) { runCatching { UsageReport.decode(state.usage) }.getOrNull() ?: UsageReport() }- val online = state.actualConnection is LinkState.Ready+ val report = remember(state?.usage) { state?.let { runCatching { UsageReport.decode(it.usage) }.getOrNull() } ?: UsageReport() }+ val online = state?.actualConnection is LinkState.Ready// Opening Usage asks the computer for a current report (it answers from cache when it can).LaunchedEffect(online) { if (online) refresh(false) }Column(Modifier.fillMaxSize()) {ScreenHeader(leading = { IconButton("Close", "xmark", action = dismiss) },- title = { Text("Usage", style = Type.body.semibold, color = Palette.text) })- if (state.computers.isEmpty()) {+ title = { Text("Usage", style = Type.body.semibold, color = Palette.text) }, trailing = { trailing() })+ if (state == null) {EmptyUsage("No computer yet", "Usage shows up once a computer is connected.")return@Column}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/VoiceChatSettings.kt b/apps/android/app/src/main/kotlin/com/codync/android/VoiceChatSettings.ktindex 33508e39..689ce028 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/VoiceChatSettings.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/VoiceChatSettings.kt@@ -66,6 +66,11 @@ import kotlinx.coroutines.launch}}if (provider != null) key(provider) { ProviderVoiceSettings(provider, speech, state, store, choices) }+ // Dictation on another provider than calls still needs that provider's key and speech-to-text model.+ val dictation = remember { choices.dictation }+ if (dictation != null && dictation != provider) key("dictation-${dictation.id}") {+ ProviderVoiceSettings(dictation, false, state, store, choices, dictationOnly = true)+ }}}}@@ -91,10 +96,13 @@ import kotlinx.coroutines.launch}/**- * One provider: the key the computer keeps, models, voice and this month's minutes. Keys are entered- * on the computer itself (the host takes `setVoiceKey` from loopback only).+ * One provider: the key the computer keeps, models, voice and this month's minutes; [dictationOnly] keeps the key and+ * the speech-to-text model. Keys are entered on the computer itself (the host takes `setVoiceKey` from loopback only).*/-@Composable private fun ProviderVoiceSettings(provider: VoiceProvider, speech: Boolean, state: AppState, store: AppStore, choices: VoiceChoices) {+@Composable private fun ProviderVoiceSettings(provider: VoiceProvider, speech: Boolean, state: AppState, store: AppStore, choices: VoiceChoices,+ dictationOnly: Boolean = false) {+ // Speech mode and dictation with this provider both use its speech-to-text model.+ val transcribes = dictationOnly || speech || choices.dictation == providerval scope = rememberCoroutineScope()val host = state.hostName/** null while the computer hasn't answered yet. */@@ -133,7 +141,11 @@ import kotlinx.coroutines.launchbusy = true; result = nullscope.launch {try {- if (speech) store.voiceSpeak(provider, speechModel, voice, "OK") else store.voiceSession(provider, model, voice)+ when {+ dictationOnly -> store.voiceModels(provider)+ speech -> store.voiceSpeak(provider, speechModel, voice, "OK")+ else -> store.voiceSession(provider, model, voice)+ }result = true to "Key works"loadModels()} catch (cancelled: CancellationException) { throw cancelled }@@ -149,7 +161,7 @@ import kotlinx.coroutines.launch}}- CardSection(provider.title, footer = if (hasKey) null else "Add a key to choose from ${provider.title}'s models.",+ CardSection(provider.title, footer = if (!hasKey) "Add a key to choose from ${provider.title}'s models." else if (dictationOnly) "For dictation in the message box." else null,modifier = Modifier.animateContentSize(Motion.layoutSize)) {if (saved != null || result != null) row {Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {@@ -172,11 +184,12 @@ import kotlinx.coroutines.launch}}}- if (speech) {- row { picker("Speech to text", transcribe, models.transcribe) { transcribe = it; choices.choose(provider, VoiceChoices.Model.Transcribe, it) } }- row { picker("Text to speech", speechModel, models.speech) { speechModel = it; choices.choose(provider, VoiceChoices.Model.Speech, it) } }- } else row { picker("Model", model, models.models) { model = it; choices.choose(provider, VoiceChoices.Model.Realtime, it) } }- row { picker("Voice", voice, provider.voices) { voice = it; choices.voice(provider, it) } }- row { ValueRow("This month", "≈ ${choices.minutes(provider)} min", Modifier.graphicsLayer { alpha = if (hasKey) 1f else .55f }) }+ if (transcribes) row { picker("Speech to text", transcribe, models.transcribe) { transcribe = it; choices.choose(provider, VoiceChoices.Model.Transcribe, it) } }+ if (!dictationOnly) {+ if (speech) row { picker("Text to speech", speechModel, models.speech) { speechModel = it; choices.choose(provider, VoiceChoices.Model.Speech, it) } }+ else row { picker("Model", model, models.models) { model = it; choices.choose(provider, VoiceChoices.Model.Realtime, it) } }+ row { picker("Voice", voice, provider.voices) { voice = it; choices.voice(provider, it) } }+ row { ValueRow("This month", "≈ ${choices.minutes(provider)} min", Modifier.graphicsLayer { alpha = if (hasKey) 1f else .55f }) }+ }}}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/VoiceControls.kt b/apps/android/app/src/main/kotlin/com/codync/android/VoiceControls.ktindex bb43c0b0..16a94d3f 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/VoiceControls.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/VoiceControls.kt@@ -83,7 +83,7 @@ internal fun openAppSettings(context: android.content.Context) =.semantics { contentDescription = if (speaking) "Interrupt" else bot?.name.orEmpty() }) {if (bot != null) BotAvatar(bot, state.bots, 34.dp)}- CallLevelDots(voice.level, speaking, bot?.status == "working", voice.phase.connecting, color,+ LevelDots(voice.level, speaking, bot?.status == "working", voice.phase.connecting, color,Modifier.weight(1f).height(20.dp).semantics { contentDescription = statusText(voice, bot?.status == "working") })// Audio leaves the phone: say where.voice.provider?.let { provider ->@@ -138,7 +138,7 @@ private const val CONNECTING_PERIOD = 2.4f* an indeterminate progress line instead (a short segment gliding back and forth along a faint track,* resting at the left with reduced motion), and fades back to the dots.*/-@Composable private fun CallLevelDots(level: Float, speaking: Boolean, working: Boolean, connecting: Boolean, color: Color, modifier: Modifier) {+@Composable internal fun LevelDots(level: Float, speaking: Boolean, working: Boolean, connecting: Boolean, color: Color, modifier: Modifier) {val still = reduceMotion()var time by remember { mutableFloatStateOf(0f) }if (!still) LaunchedEffect(Unit) { while (true) withFrameNanos { time = it / 1e9f } }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.ktindex 9cbacb47..a2793c2f 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@@ -124,7 +124,7 @@ class VoiceService : Service() {val call = snapshot?.voiceval bot = snapshot?.bots?.firstOrNull { it.id == call?.botId }val url = Uri.Builder().scheme(BuildConfig.URL_SCHEME).authority("bot").appendPath(call?.botId.orEmpty())- .appendQueryParameter("scope", snapshot?.contextId).appendQueryParameter("computer", snapshot?.computers?.firstOrNull()?.id).build()+ .appendQueryParameter("scope", snapshot?.contextId).appendQueryParameter("computer", snapshot?.computer?.id).build()val content = PendingIntent.getActivity(this, NOTIFICATION, Intent(this, MainActivity::class.java).setAction(Intent.ACTION_VIEW).setData(url), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)fun action(kind: String) = PendingIntent.getService(this, kind.hashCode(), Intent(this, VoiceService::class.java)diff --git a/apps/android/app/src/main/kotlin/com/codync/android/WelcomeView.kt b/apps/android/app/src/main/kotlin/com/codync/android/WelcomeView.ktindex 610b3970..6a276f79 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/WelcomeView.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/WelcomeView.kt@@ -54,7 +54,7 @@ import kotlinx.coroutines.delayimport kotlin.math.sin/** First launch, before any setup: who the bots are, a glimpse of talking to one, one way forward (iOS `WelcomeView`). */-@Composable internal fun WelcomeView(state: AppState, store: AppStore, start: () -> Unit) {+@Composable internal fun WelcomeView(state: AccountContext, store: AccountStore, start: () -> Unit) {AnalyticsOnAppear(AnalyticsEvent.OnboardingStepViewed(OnboardingStep.Welcome))val still = reduceMotion()// 0 = nothing yet … 4 = everything shown. Each beat enters in turn.@@ -158,7 +158,7 @@ private val CREW = listOf(}/** Equal access to both account providers at every sign-in entry point (iOS `SignInButtons`). */-@Composable internal fun SignInButtons(state: AppState, store: AppStore) {+@Composable internal fun SignInButtons(state: AccountContext, store: AccountStore) {val busy = "session" in state.busyval enabled = state.account.ready && !busyColumn(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(10.dp)) {diff --git a/apps/android/app/src/main/kotlin/com/codync/android/WidgetConfigurationActivity.kt b/apps/android/app/src/main/kotlin/com/codync/android/WidgetConfigurationActivity.ktindex cd427807..0e6291f6 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/WidgetConfigurationActivity.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/WidgetConfigurationActivity.kt@@ -74,7 +74,7 @@ class WidgetConfigurationActivity : ComponentActivity() {val choices = (feed.usage.providers.map { it.id to it.name } + listOf("claude" to "Claude", "codex" to "Codex")).distinctBy { it.first }ValueRow("Provider") { ChoicePicker(provider, choices, { provider = it }, label = "Provider") }} else for ((spot, label) in listOf("Top left", "Top right", "Bottom left", "Bottom right").withIndex()) row {- val choices = listOf("" to "Automatic") + feed.bots.map { it.id to it.name }+ val choices = listOf("" to "Automatic") + feed.bots.map { it.key to it.name }ValueRow(label) {ChoicePicker(team[spot].orEmpty(), choices, { pick -> team = team.toMutableList().also { it[spot] = pick.ifEmpty { null } } },label = label)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.ktindex 4e1adf24..06f61682 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@@ -6,6 +6,9 @@ import com.codync.android.core.*import java.util.concurrent.TimeUnitimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAll+import kotlinx.coroutines.coroutineScopeimport kotlinx.coroutines.withContextimport kotlinx.coroutines.withTimeoutimport kotlinx.coroutines.TimeoutCancellationException@@ -32,19 +35,40 @@ class WidgetRefreshWorker(context: Context, parameters: WorkerParameters) : Coroval revision = WidgetStore.changes.valuewithTimeout(30_000) {val local = LocalStore(context, owner.context)- val computer = withContext(Dispatchers.IO) { local.computers().firstOrNull() } ?: return@withTimeout false+ 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().idval identity = withContext(Dispatchers.IO) { local.identity() }- val channel = HostConnector.connect(computer, identity)- try {- val current = HostClient.hello(channel, computer)- // The finite roster snapshot includes its authoritative custom icons.- val bots = HostClient.bots(channel)- val response = channel.call("usage", buildJsonObject { put("refresh", false) })- val usage = UsageReport.decode(response)- withContext(Dispatchers.IO) { WidgetStore.publish(context, owner, current, bots, usage, true, true, expectedRevision = revision) }- } finally { channel.close() }+ // 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()+ }+ val previous = withContext(Dispatchers.IO) { WidgetStore.feed(context) }+ val bots = computers.zip(reads).map { (computer, read) ->+ read?.let { WidgetComputer(it.computer, it.bots, true) } ?: WidgetComputer(computer, null, false)+ }+ val usage = reads.firstNotNullOfOrNull { it?.usage }+ val usageComputer = bots.first { it.computer.id == usageId }.computer+ withContext(Dispatchers.IO) {+ WidgetStore.publish(context, owner, bots, usageComputer, usage ?: previous.usage.takeIf { previous.computerId == usageId } ?: UsageReport(),+ usage != null, expectedRevision = revision)+ }}}+ private class Read(val computer: Computer, val bots: List<Bot>, val usage: UsageReport?)++ /** One computer's roster (and, for the last active one, its usage), then the link closes. */+ private suspend fun read(computer: Computer, identity: DeviceIdentity, usage: Boolean): Read {+ val channel = HostConnector.connect(computer, identity)+ try {+ val current = HostClient.hello(channel, computer)+ // The finite roster snapshot includes its authoritative custom icons.+ val bots = HostClient.bots(channel)+ val report = if (usage) UsageReport.decode(channel.call("usage", buildJsonObject { put("refresh", false) })) else null+ return Read(current, bots, report)+ } finally { channel.close() }+ }+suspend fun stop(context: Context) {WorkManager.getInstance(context).cancelUniqueWork(NAME)// Join every reader before account erasure can remove its storage.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.ktindex 3b5e7b3c..e4b9d130 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@@ -10,6 +10,9 @@ import kotlinx.serialization.Serializable@Serializable internal data class WidgetOwner(val context: String, val scope: String, val epoch: String)+/** One computer's bots for the widgets (null: keep the ones shown); [fresh] when they're caught up with the computer. */+internal data class WidgetComputer(val computer: Computer, val bots: List<Bot>?, val fresh: Boolean)+/** Every write checks the original account activation, including background responses. */internal object WidgetStore {val changes = MutableStateFlow(0L)@@ -32,18 +35,27 @@ internal object WidgetStore {@Synchronized fun feed(context: Context): WidgetFeed {val active = owner(context) ?: return WidgetFeed()val saved = read<WidgetFeed>(feedFile(context, active))- val paired = runCatching { LocalStore(context, active.context).computers().firstOrNull()?.id }.getOrNull()- return saved?.takeIf { it.scope == active.scope && it.computerId == paired } ?: WidgetFeed(scope = active.scope)+ val paired = runCatching { LocalStore(context, active.context).computers().map { it.id } }.getOrNull().orEmpty()+ // A computer forgotten since: its bots and usage go with it.+ return saved?.takeIf { it.scope == active.scope && (it.computerId == null || it.computerId in paired) }+ ?.let { it.copy(bots = it.bots.filter { bot -> bot.computerId in paired }) } ?: WidgetFeed(scope = active.scope)}- @Synchronized fun publish(context: Context, expected: WidgetOwner, computer: Computer?, bots: List<Bot>,- usage: UsageReport, freshBots: Boolean, freshUsage: Boolean, now: Long = System.currentTimeMillis(),- expectedRevision: Long? = null): Boolean {+ /**+ * Every computer's bots, and [usage] read on [usageComputer] (the last active one); [freshUsage] when it was+ * just read. Usage from another computer than before replaces it outright.+ */+ @Synchronized fun publish(context: Context, expected: WidgetOwner, computers: List<WidgetComputer>, usageComputer: Computer?,+ usage: UsageReport, freshUsage: Boolean, now: Long = System.currentTimeMillis(), expectedRevision: Long? = null): Boolean {if (owner(context) != expected || expectedRevision != null && changes.value != expectedRevision) return falseval file = feedFile(context, expected)- val previous = read<WidgetFeed>(file)?.takeIf { it.computerId == computer?.id } ?: WidgetFeed(scope = expected.scope)- val next = WidgetFeed(expected.scope, computer?.id, computer?.name.orEmpty().take(256), widgetBots(bots),- if (freshBots) now else previous.botsAt, usage, if (freshUsage) now else+ 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 elseif (usage != previous.usage) usage.providers.mapNotNull { it.updatedAt?.takeIf { time -> time > 0 } }.minOrNull() ?: 0else previous.usageAt)if (previous == next) return true@@ -52,6 +64,20 @@ internal object WidgetStore {return true}+ /** A usage read that just finished on [computer], keeping the bots as they are. */+ @Synchronized fun publishUsage(context: Context, expected: WidgetOwner, computer: Computer, usage: UsageReport, fresh: Boolean,+ now: Long = System.currentTimeMillis()): Boolean {+ if (owner(context) != expected) return false+ val file = feedFile(context, expected)+ val previous = read<WidgetFeed>(file) ?: WidgetFeed(scope = expected.scope)+ val next = previous.copy(computerId = computer.id, computerName = computer.name.take(256), usage = usage,+ usageAt = if (fresh) now else previous.usageAt)+ if (previous == next) return true+ write(file, next)+ changed()+ return true+ }+@Synchronized fun selectProvider(context: Context, widget: Int, provider: String) {require(provider.isNotBlank() && provider.length <= 128 && provider.none(Char::isISOControl))check(context.getSharedPreferences("codync-widgets", Context.MODE_PRIVATE).edit().putString("provider:$widget", provider).commit())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.ktindex d6a446b3..6e0e91f5 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@@ -8,10 +8,12 @@ import org.junit.Testclass ConnectionPresentationTest {private val computer = Computer("fixture", "Studio", "fixture")- private fun state(link: LinkState, cloud: List<CloudComputer> = emptyList(), computers: List<Computer> = listOf(computer)) = AppState(- account = AccountState(configured = false), loading = false, setupComplete = true,- computers = computers, connection = link, actualConnection = link, cloudComputers = cloud)+ private fun state(link: LinkState, computer: Computer = this.computer) = AppState(computer, loading = false, connection = link, actualConnection = link)+ private fun context(cloud: List<CloudComputer> = emptyList(), computers: List<Computer> = listOf(computer)) = AccountContext(+ account = AccountState(configured = false), loading = false, setupComplete = true, computers = computers, cloudComputers = cloud)private fun cloud(id: String, online: Boolean, name: String = "Studio") = CloudComputer(id, name, "key", online = online)+ private fun stale(link: LinkState, cloud: List<CloudComputer> = emptyList(), others: List<AppState> = emptyList()) =+ context(cloud).isStale(state(link), others)@Test fun eachConnectionReadsAsOnIPhone() {val revoked = LinkState.Failed("This device isn't allowed on Studio anymore.", 403)@@ -28,13 +30,9 @@ class ConnectionPresentationTest {assertEquals(words.second, connectionLabel(state(link)))assertEquals(words.third, connectionDescription(state(link)))}- val unpaired = state(LinkState.Connecting, computers = emptyList())- assertEquals("Not paired", statusText(unpaired))- assertEquals("Not paired", connectionLabel(unpaired))- assertEquals("Not paired", connectionDescription(unpaired))val custom = computer.copy(cloud = "https://relay.example.com")- assertEquals("Connected through Private relay (relay.example.com)", connectionDescription(state(LinkState.Ready(HostRoute.Relay), computers = listOf(custom))))- assertEquals("Connected through Cloudflare", connectionDescription(state(LinkState.Ready(HostRoute.Relay), computers = listOf(computer.copy(cloud = "https://api.codync.dev")))))+ assertEquals("Connected through Private relay (relay.example.com)", connectionDescription(state(LinkState.Ready(HostRoute.Relay), custom)))+ assertEquals("Connected through Cloudflare", connectionDescription(state(LinkState.Ready(HostRoute.Relay), computer.copy(cloud = "https://api.codync.dev"))))assertEquals("relay.example.com", relayHost("https://relay.example.com/"))assertEquals(null, relayHost("https://dev-api.codync.dev"))assertEquals("[2001:db8::1]:8443", relayHost("https://[2001:db8::1]:8443"))@@ -69,50 +67,72 @@ class ConnectionPresentationTest {}@Test fun theHeaderSummarizesTheComputers() {- assertEquals("1 connected", connectionSummary(state(LinkState.Ready(HostRoute.Direct))))- assertEquals("Connecting…", connectionSummary(state(LinkState.Connecting)))- assertEquals("No access", connectionSummary(state(LinkState.Failed("Revoked", 403))))- assertEquals("1 offline", connectionSummary(state(LinkState.ComputerOffline(null))))- assertEquals("Computers", connectionSummary(state(LinkState.Connecting, computers = emptyList())))+ 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()))+ 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))))}@Test fun aComputerTurningThisPhoneAwayOrReplacedByANewIdentityIsStale() {- assertTrue(state(LinkState.Failed("Revoked", 403)).isStale)- val offline = state(LinkState.ComputerOffline(null), listOf(cloud("new", online = true)))- assertTrue(offline.isStale)- assertEquals("Older copy of this computer · Offline", computerStatusText(offline))- assertFalse(state(LinkState.ComputerOffline(null), listOf(cloud("new", online = false))).isStale)- assertFalse(state(LinkState.Ready(HostRoute.Direct), listOf(cloud("new", online = true))).isStale)- assertEquals("Revoked", computerStatusText(state(LinkState.Failed("Revoked", 403), listOf(cloud("new", online = true)))))+ assertTrue(stale(LinkState.Failed("Revoked", 403)))+ val offline = state(LinkState.ComputerOffline(null))+ assertTrue(stale(LinkState.ComputerOffline(null), listOf(cloud("new", online = true))))+ assertEquals("Older copy of this computer · Offline", computerStatusText(offline, stale = true))+ assertEquals("Offline", computerStatusText(offline, stale = false))+ assertFalse(stale(LinkState.ComputerOffline(null), listOf(cloud("new", online = false))))+ assertFalse(stale(LinkState.Ready(HostRoute.Direct), listOf(cloud("new", online = true))))+ val revoked = LinkState.Failed("Revoked", 403)+ assertEquals("Revoked", computerStatusText(state(revoked), stale(revoked, listOf(cloud("new", online = true)))))+ }++ @Test fun anOfflineComputerIsStaleWhenAnotherSavedComputerWithItsNameIsOnlineAndJoinedLater() {+ val namesake = Computer("new", "Studio", "new")+ val joined = listOf(cloud("new", online = false).copy(claimedAt = 100))+ // Paired here with its code only: the name decides.+ assertTrue(stale(LinkState.ComputerOffline(null), others = listOf(state(LinkState.Ready(HostRoute.Direct), namesake))))+ assertFalse(stale(LinkState.ComputerOffline(null), others = listOf(state(LinkState.ComputerOffline(null), namesake))))+ assertFalse(stale(LinkState.ComputerOffline(null), others = listOf(state(LinkState.Ready(HostRoute.Direct), namesake.copy(name = "Laptop")))))+ // It was last seen before the namesake joined the account: replaced; after: two machines.+ assertTrue(stale(LinkState.ComputerOffline(50), joined, listOf(state(LinkState.Ready(HostRoute.Direct), namesake))))+ assertFalse(stale(LinkState.ComputerOffline(200), joined, listOf(state(LinkState.Ready(HostRoute.Direct), namesake))))+ // Its own state among the others never makes it stale.+ assertFalse(stale(LinkState.ComputerOffline(null), others = listOf(state(LinkState.Ready(HostRoute.Direct)))))}@Test fun aComputerSeenAfterItsNamesakeJoinedTheAccountRunsBesideItAndIsNotStale() {val namesake = cloud("new", online = true).copy(claimedAt = 100)fun own(seen: Long) = cloud("fixture", online = false).copy(lastSeenAt = seen)// Its own account entry says when it was last seen.- assertFalse(state(LinkState.ComputerOffline(null), listOf(own(200), namesake)).isStale)- assertTrue(state(LinkState.ComputerOffline(null), listOf(own(50), namesake)).isStale)- assertFalse(state(LinkState.Failed("Connection closed."), listOf(own(200), namesake)).isStale)+ assertFalse(stale(LinkState.ComputerOffline(null), listOf(own(200), namesake)))+ assertTrue(stale(LinkState.ComputerOffline(null), listOf(own(50), namesake)))+ assertFalse(stale(LinkState.Failed("Connection closed."), listOf(own(200), namesake)))// Paired with its code only: the relay's last seen decides.- assertFalse(state(LinkState.ComputerOffline(200), listOf(namesake)).isStale)- assertTrue(state(LinkState.ComputerOffline(50), listOf(namesake)).isStale)+ assertFalse(stale(LinkState.ComputerOffline(200), listOf(namesake)))+ assertTrue(stale(LinkState.ComputerOffline(50), listOf(namesake)))// Without the namesake's join time, the name alone.- assertTrue(state(LinkState.ComputerOffline(200), listOf(cloud("new", online = true))).isStale)+ assertTrue(stale(LinkState.ComputerOffline(200), listOf(cloud("new", online = true))))}@Test fun anOfflineAccountComputerNamedLikeTheCurrentOneIsAnOlderCopy() {val old = cloud("old", online = false)- assertTrue(state(LinkState.Connecting, listOf(old)).isOlderCopy(old))- assertFalse(state(LinkState.Connecting, listOf(old.copy(online = true))).isOlderCopy(old.copy(online = true)))- assertFalse(state(LinkState.Connecting, listOf(old), computers = emptyList()).isOlderCopy(old))+ assertTrue(context(listOf(old)).isOlderCopy(old))+ assertFalse(context(listOf(old.copy(online = true))).isOlderCopy(old.copy(online = true)))+ assertFalse(context(listOf(old), computers = emptyList()).isOlderCopy(old))val renamed = cloud("old", online = false, name = "Laptop")- assertFalse(state(LinkState.Connecting, listOf(renamed)).isOlderCopy(renamed))+ assertFalse(context(listOf(renamed)).isOlderCopy(renamed))// Not paired here, but the new identity is online in the account.- val accountOnly = state(LinkState.Connecting, listOf(old, cloud("new", online = true)), computers = emptyList())- assertTrue(accountOnly.isOlderCopy(old))+ assertTrue(context(listOf(old, cloud("new", online = true)), computers = emptyList()).isOlderCopy(old))// Seen after the current one joined the account: two machines that share a name.val seen = old.copy(lastSeenAt = 200)- assertFalse(state(LinkState.Connecting, listOf(seen, cloud("fixture", online = true).copy(claimedAt = 100))).isOlderCopy(seen))- assertTrue(state(LinkState.Connecting, listOf(seen, cloud("fixture", online = true).copy(claimedAt = 300))).isOlderCopy(seen))+ assertFalse(context(listOf(seen, cloud("fixture", online = true).copy(claimedAt = 100))).isOlderCopy(seen))+ assertTrue(context(listOf(seen, cloud("fixture", online = true).copy(claimedAt = 300))).isOlderCopy(seen))+ // Two computers paired here: the older copy of the second one is found too.+ val laptop = Computer("laptop", "Laptop", "laptop")+ assertTrue(context(listOf(renamed), computers = listOf(computer, laptop)).isOlderCopy(renamed))}}diff --git a/apps/android/app/src/test/kotlin/com/codync/android/HostUpdateNoticeTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/HostUpdateNoticeTest.ktindex b29519aa..b12b2b3e 100644--- a/apps/android/app/src/test/kotlin/com/codync/android/HostUpdateNoticeTest.kt+++ b/apps/android/app/src/test/kotlin/com/codync/android/HostUpdateNoticeTest.kt@@ -1,5 +1,6 @@package com.codync.android+import com.codync.android.core.Computerimport com.codync.android.core.VersionMismatchimport kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.put@@ -61,7 +62,7 @@ class HostUpdateNoticeTest {}@Test fun theCodyncRowComparesWithTheLatestReleaseTheComputerFound() {- val state = AppState().copy(hello = buildJsonObject {+ val state = AppState(Computer("fixture", "Studio", "fixture")).copy(hello = buildJsonObject {put("name", "Mini"); put("version", "2.28.0"); put("latestVersion", "2.30.0"); put("canUpdate", true)})assertEquals(HostVersionLine("2.28.0", listOf("Version 2.30.0 is available."), accessory = update), state.hostVersionLine(now))diff --git a/apps/android/app/src/test/kotlin/com/codync/android/ReadingTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/ReadingTest.ktindex 06cb9519..c63dc6c4 100644--- a/apps/android/app/src/test/kotlin/com/codync/android/ReadingTest.kt+++ b/apps/android/app/src/test/kotlin/com/codync/android/ReadingTest.kt@@ -1,6 +1,7 @@package com.codync.androidimport com.codync.android.core.Bot+import com.codync.android.core.Computerimport com.codync.android.core.Entryimport com.codync.android.core.MirrorEventimport kotlinx.serialization.json.buildJsonObject@@ -13,8 +14,8 @@ class ReadingTest {MirrorEvent.EntryChanged(Entry("e", 1, bot, 1, kind, data = buildJsonObject { put("text", "hi") }))@Test fun `the chat stays read under Full conversation`() {- assertEquals(listOf("bot"), AppState(selectedBot = "bot", trace = true).readingChats)- assertEquals(emptyList<String>(), AppState().readingChats)+ assertEquals(listOf("bot"), AppState(Computer("fixture", "Studio", "fixture"), selectedBot = "bot", trace = true).readingChats)+ assertEquals(emptyList<String>(), AppState(Computer("fixture", "Studio", "fixture")).readingChats)}@Test fun `a message is read where it lands, and a bot counting unread reads all it shows`() {diff --git a/apps/android/app/src/test/kotlin/com/codync/android/RosterSectionsTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/RosterSectionsTest.ktindex 7e5fb797..c34203ba 100644--- a/apps/android/app/src/test/kotlin/com/codync/android/RosterSectionsTest.kt+++ b/apps/android/app/src/test/kotlin/com/codync/android/RosterSectionsTest.kt@@ -1,6 +1,7 @@package com.codync.androidimport com.codync.android.core.Bot+import com.codync.android.core.Computerimport kotlinx.serialization.json.JsonNullimport kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.put@@ -136,7 +137,7 @@ class RosterSectionsTest {}@Test fun sectionControlsWaitForAHostThatKeepsSections() {- fun host(version: String?) = AppState(hello = version?.let { buildJsonObject { put("version", it) } })+ fun host(version: String?) = AppState(Computer("fixture", "Studio", "fixture"), hello = version?.let { buildJsonObject { put("version", it) } })assertFalse(host("2.31.2").supportsSections)assertTrue(host("2.32.0").supportsSections)assertTrue(host("2.32.1-dev").supportsSections)@@ -144,7 +145,7 @@ class RosterSectionsTest {}@Test fun leadChoiceWaitsForAHostThatLetsTheLeadChange() {- fun host(version: String?) = AppState(hello = version?.let { buildJsonObject { put("version", it) } })+ fun host(version: String?) = AppState(Computer("fixture", "Studio", "fixture"), hello = version?.let { buildJsonObject { put("version", it) } })assertFalse(host("2.32.9").supportsLeadChoice)assertTrue(host("2.33.0").supportsLeadChoice)assertFalse(host(null).supportsLeadChoice)diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/DictationText.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/DictationText.ktnew file mode 100644index 00000000..27aec63b--- /dev/null+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/DictationText.kt@@ -0,0 +1,30 @@+package com.codync.android.core++/** Dictation's arithmetic (iOS `Dictation`'s statics): where its words go in the box, and a recording's pieces. */+object DictationText {+ private const val BYTES_PER_SECOND = Pcm.RATE * 2+ /** A transcription request has to fit one channel message once base64-encoded: 20 s of audio. */+ const val PIECE_BYTES = BYTES_PER_SECOND * 20+ /** Under half a second is a tap of the mic, not speech (and speech-to-text models invent words for silence). */+ const val MIN_BYTES = BYTES_PER_SECOND / 2+ /** Transcription requests in flight at once, under the channel's and the providers' limits. */+ const val IN_FLIGHT = 3++ /** [said] after what's already in the box, with one space between. */+ fun join(before: String, said: String): String = when {+ before.isBlank() -> said+ said.isEmpty() -> before+ before.last().isWhitespace() -> before + said+ else -> "$before $said"+ }++ /** Byte ranges (start until end) of a recording's 20 s pieces; a tail under half a second stays with the piece before. */+ fun pieces(count: Int): List<IntRange> {+ val starts = (0 until count step PIECE_BYTES).toMutableList()+ if (starts.size > 1 && count - starts.last() < MIN_BYTES) starts.removeAt(starts.lastIndex)+ return starts.mapIndexed { i, start -> start until (starts.getOrNull(i + 1) ?: count) }+ }++ /** Seconds of audio in [bytes] of PCM, for this month's minutes. */+ fun seconds(bytes: Int): Long = (bytes / BYTES_PER_SECOND).toLong()+}diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.ktindex 5a0caaef..10be89cc 100644--- a/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt@@ -41,6 +41,14 @@ data class Bot(val reachableByAssistants: Boolean? = null,/** The bot that created this one; null when the user did. */val createdBy: String? = null,+ /** Uses the memory all the user's bots share ("About you"); null from an older host. */+ val sharedMemory: Boolean? = null,+ /** Keeps the harness's own memory (Claude Code's…) on beside Codync's; null where it has no switch. */+ val harnessMemory: Boolean? = null,+ /** The harness keeps one memory for all its sessions that Codync can't turn off (Hermes Agent, Gemini CLI): every bot on it shares it. */+ val harnessMemoryShared: Boolean? = null,+ /** Moves whenever memory changes, so an open memory screen fetches it again. */+ val memoryRev: Long? = null,val autoName: Boolean = false,val createdAt: Long = 0,val startedAt: Long? = null,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.ktindex f319b344..a7c4ca4f 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.SerialNameimport kotlinx.serialization.Serializableimport kotlinx.serialization.json.*@@ -37,38 +36,3 @@ data class GroupDraft(}}-/** One Engram memory, as the host lists it; unknown kinds and fields pass through. */-@Serializable data class MemoryFact(- val id: String, val title: String = "", val content: String, val createdAt: Long = 0, val kind: String = "",- val memoryType: String = "", val scope: String = "project", val topicKey: String? = null, val pinned: Boolean = false,- val reviewAfter: String? = null, val revisionCount: Int = 0, val source: String? = null,-)--@Serializable data class MemoryListing(val facts: List<MemoryFact> = emptyList(), val total: Int = 0, val nextOffset: Int? = null) {- companion object {- fun decode(value: JsonElement): MemoryListing {- val listing = WireJson.decodeFromJsonElement<MemoryListing>(value)- require(listing.facts.all { it.id.isNotBlank() && it.content.isNotBlank() }) { "The computer sent invalid memory." }- return listing- }- }-}--/** A memory's past versions and the session it came from. */-@Serializable data class MemoryDetail(val fact: MemoryFact, val history: History, val timeline: Timeline) {- @Serializable data class History(val result: String, @SerialName("history_cursor") val cursor: Int? = null)- @Serializable data class Timeline(val result: String)-}--data class MemoryDraft(val botId: String, val id: String? = null, val title: String = "", val content: String = "",- val scope: String = "project", val memoryType: String = "learning", val topicKey: String = "") {- fun body(): JsonObject = buildJsonObject {- put("botId", botId); id?.let { put("id", it) }; put("title", title); put("content", content)- put("scope", scope); put("memoryType", memoryType); put("topicKey", topicKey)- }-- companion object {- fun of(botId: String, fact: MemoryFact?) = MemoryDraft(botId, fact?.id, fact?.title.orEmpty(), fact?.content.orEmpty(),- fact?.scope ?: "project", fact?.memoryType ?: "learning", fact?.topicKey.orEmpty())- }-}diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Memory.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Memory.ktnew file mode 100644index 00000000..d04e0855--- /dev/null+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Memory.kt@@ -0,0 +1,59 @@+package com.codync.android.core++import kotlinx.serialization.Serializable++// A bot's memory as its screen shows it, read-only (iOS `Memory.swift`, `MemoryFiles.swift`): the user changes it by telling the bot.++/** One line of a layer's `MEMORY.md`. */+@Serializable data class MemoryEntry(+ val id: Long,+ /** The bot whose own layer holds it; null for what all bots share. */+ val bot: String? = null,+ /** `active` or `archived`. */+ val state: String = "active",+ val text: String,+ /** `user`, `bot`, `dream` or `imported`. */+ val author: String = "user",+ val authorBot: String? = null,+ val pinned: Boolean = false,+ val updatedAt: Long = 0,+) {+ val archived: Boolean get() = state == "archived"+}++@Serializable data class MemoryLayer(val entries: List<MemoryEntry> = emptyList(), val used: Int = 0, val cap: Int = 0)++/** One dreaming run: what it added and archived (`undone` when an older app undid it). */+@Serializable data class DreamRun(val id: Long, val at: Long, val undone: Boolean = false, val added: List<Change> = emptyList(),+ val archived: List<Change> = emptyList(), val files: List<FileNote>? = null) {+ @Serializable data class Change(val id: Long, val text: String)+ /** A long-form note the run added a line to. */+ @Serializable data class FileNote(val name: String, val shared: Boolean = false, val version: Long = 0)+}++/** A long-form memory note: a Markdown file on one topic, as the host last recorded it. */+@Serializable data class MemoryFile(val bot: String? = null, val name: String, val description: String? = null, val tokens: Int = 0,+ val deleted: Boolean = false, val updatedAt: Long = 0)++/** One layer's folder of notes, and where it is on the computer. */+@Serializable data class MemoryFolder(val files: List<MemoryFile> = emptyList(), val folder: String = "")++/** Both layers' notes, with the caps the host marks: tokens per note, notes per folder. */+@Serializable data class MemoryFiles(val yours: MemoryFolder = MemoryFolder(), val bot: MemoryFolder = MemoryFolder(), val cap: Int = 0, val folderCap: Int = 0)++/** A note as it is on disk now; [content] null when it's gone. */+@Serializable data class MemoryFileDetail(val file: String, val shared: Boolean = false, val content: String? = null, val path: String = "")++/** A bot's memory (`memory`): what all bots share about the user, what this one learned, its dreams and its harness's own notes. */+@Serializable data class BotMemory(+ /** Whether this bot uses what all bots share. */+ val shared: Boolean,+ val yours: MemoryLayer,+ val bot: MemoryLayer,+ val dreams: List<DreamRun>,+ /** Claude Code's own notes for the bot's project folder, read-only. */+ val projectMemory: Project? = null,+ val files: MemoryFiles? = null,+) {+ @Serializable data class Project(val path: String, val text: String = "")+}diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/VoiceProvider.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/VoiceProvider.ktindex 1e2916d6..661138e5 100644--- a/apps/android/core/src/main/kotlin/com/codync/android/core/VoiceProvider.kt+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/VoiceProvider.kt@@ -49,6 +49,11 @@ class VoiceChoices(private val read: (String) -> String?, private val write: (Stget() = VoiceProvider.of(read("callEngine"))set(value) = write("callEngine", value?.id)+ /** What the message box's dictation uses: on-device speech (null) or a provider on the user's key (iOS `dictationEngine`). */+ var dictation: VoiceProvider?+ get() = VoiceProvider.of(read("dictationEngine"))+ set(value) = write("dictationEngine", value?.id)+fun defaults(provider: VoiceProvider): VoiceDefaults = read("callDefaults.${provider.id}")?.let { runCatching { WireJson.decodeFromString(VoiceDefaults.serializer(), it) }.getOrNull() } ?: provider.defaultsfun remember(defaults: VoiceDefaults?, provider: VoiceProvider) {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.ktindex 75148b30..c7f1dbba 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@@ -4,8 +4,14 @@ import kotlinx.serialization.Serializable/** Private summaries only: widget storage never contains chat text or credentials. */@Serializable data class WidgetBot(val id: String, val name: String, val status: String,- val unread: Int = 0, val avatarColor: String = "blue", val avatarShape: String = "blob", val customIcon: CustomIcon? = null)+ val unread: Int = 0, val avatarColor: String = "blue", val avatarShape: String = "blob", val customIcon: CustomIcon? = null,+ /** The computer it lives on: bot IDs are only unique per computer. */+ val computerId: String = "") {+ /** The bot across every computer, as the Team widget's picks keep it (iOS re-keys `<computerId>/<botId>`). */+ val key: String get() = if (computerId.isEmpty()) id else "$computerId/$id"+}+/** Every computer's bots (the Bots and Team widgets) and one computer's usage: the last active one (iOS `lastComputerId`). */@Serializable data class WidgetFeed(val scope: String = "local", val computerId: String? = null,val computerName: String = "", val bots: List<WidgetBot> = emptyList(), val botsAt: Long = 0,val usage: UsageReport = UsageReport(), val usageAt: Long = 0)@@ -27,12 +33,17 @@ fun mostUrgentBot(bots: List<WidgetBot>): WidgetBot? = bots.firstOrNull { it.sta/** The Team widget's four spots: the picked bots first (a deleted pick falls back), then the feed's order (who needs you). */fun teamSlots(bots: List<WidgetBot>, picks: List<String?>): List<WidgetBot?> {- val picked = List(4) { i -> picks.getOrNull(i)?.let { id -> bots.firstOrNull { it.id == id } } }- val queue = ArrayDeque(bots.filter { bot -> picked.none { it?.id == bot.id } })+ val picked = List(4) { i -> picks.getOrNull(i)?.let { key -> bots.firstOrNull { it.key == key } } }+ val queue = ArrayDeque(bots.filter { bot -> picked.none { it?.key == bot.key } })return picked.map { it ?: queue.removeFirstOrNull() }}-fun widgetBots(bots: List<Bot>): List<WidgetBot> = bots.filter { !it.hidden && !it.deleted }- .sortedWith(compareBy<Bot> { when (it.status) { "needsInput" -> 0; "working" -> 1; "error" -> 2; else -> 3 } }- .thenByDescending { it.pinned }.thenByDescending { it.lastAt }.thenBy { it.name })- .take(256).map { WidgetBot(it.id, it.name.take(256), it.status, it.unread, it.avatarColor, it.avatarShape, it.customIcon) }+/** Who needs you comes first in the widgets: waiting for you, working, failed, then the rest. */+fun widgetRank(status: String): Int = when (status) { "needsInput" -> 0; "working" -> 1; "error" -> 2; else -> 3 }++/** Every computer's bots, [bots] by computer ID, who needs you first. */+fun widgetBots(bots: Map<String, List<Bot>>): List<WidgetBot> = bots.flatMap { (computer, list) -> list.map { computer to it } }+ .filter { (_, bot) -> !bot.hidden && !bot.deleted }+ .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) }diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/CustomIconTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/CustomIconTest.ktindex 0fa93ff5..c1d51a5b 100644--- a/apps/android/core/src/test/kotlin/com/codync/android/core/CustomIconTest.kt+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/CustomIconTest.kt@@ -10,7 +10,7 @@ class CustomIconTest {val event = MirrorEvent.decode(WireJson.parseToJsonElement("""{"type":"icons","icons":{"bot:b":{"dataUrl":"data:image/png;base64,iVBORw0KGgo=","tinted":false}}}""").jsonObject) as MirrorEvent.Iconsval icon = event.icons.getValue("bot:b")assertFalse(icon.tinted)- val bots = widgetBots(listOf(Bot("b", "Scout", customIcon = icon)))+ val bots = widgetBots(mapOf("mac" to listOf(Bot("b", "Scout", customIcon = icon))))assertEquals(icon, bots.single().customIcon)val cleared = MirrorEvent.decode(WireJson.parseToJsonElement("""{"type":"icons","icons":{}}""").jsonObject) as MirrorEvent.IconsassertTrue(cleared.icons.isEmpty())@@ -31,7 +31,7 @@ class CustomIconTest {@Test fun widgetFeedBudgetAcceptsAll128MaximumIconsAnd256BotSummaries() {val maximum = CustomIcon("data:image/png;base64," + "A".repeat(65_536), true)val bots = (0 until 256).map { Bot("bot-$it", "n".repeat(256), customIcon = maximum.takeIf { _ -> it < 128 }) }- val bytes = WireJson.encodeToString(WidgetFeed(bots = widgetBots(bots))).toByteArray()+ val bytes = WireJson.encodeToString(WidgetFeed(bots = widgetBots(mapOf("mac" to bots)))).toByteArray()assertTrue("The old limit would reject supported icons", bytes.size > 512 * 1024)assertTrue("All supported icons must fit", bytes.size <= MAX_WIDGET_FEED_BYTES)}diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/DictationTextTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/DictationTextTest.ktnew file mode 100644index 00000000..9a7b5135--- /dev/null+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/DictationTextTest.kt@@ -0,0 +1,21 @@+package com.codync.android.core++import org.junit.Assert.assertEquals+import org.junit.Test++class DictationTextTest {+ @Test fun `words go after the box with one space`() {+ assertEquals("hello", DictationText.join(" ", "hello"))+ assertEquals("Fix it", DictationText.join("Fix it", ""))+ assertEquals("Fix it now", DictationText.join("Fix it", "now"))+ assertEquals("Fix it\nnow", DictationText.join("Fix it\n", "now"))+ }++ @Test fun `a recording goes in 20 s pieces, a short tail staying with the last`() {+ val piece = DictationText.PIECE_BYTES+ assertEquals(listOf(0 until 100), DictationText.pieces(100))+ assertEquals(listOf(0 until piece, piece until piece + DictationText.MIN_BYTES), DictationText.pieces(piece + DictationText.MIN_BYTES))+ assertEquals(listOf(0 until piece + 10), DictationText.pieces(piece + 10))+ assertEquals(emptyList<IntRange>(), DictationText.pieces(0))+ }+}diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/ManagementTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/ManagementTest.ktindex 9372513b..74eb21c9 100644--- a/apps/android/core/src/test/kotlin/com/codync/android/core/ManagementTest.kt+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/ManagementTest.kt@@ -23,21 +23,4 @@ class ManagementTest {Bot("nested", "Team", kind = "group"), Bot("deleted", "Gone", deleted = true))) }}}-- @Test fun `memory decodes profiles history and future kinds without discarding facts`() {- val memory = MemoryListing.decode(WireJson.parseToJsonElement("""{"facts":[- {"id":"profile","title":"Android","content":"Works on Android","createdAt":1,"kind":"profile","pinned":true},- {"id":"log","content":"Reviewed a release","createdAt":2,"kind":"future","extra":true}],"total":5,"nextOffset":2}"""))- assertEquals(2, memory.facts.size)- assertEquals("future", memory.facts.last().kind)- assertEquals(2, memory.nextOffset)- assertEquals(true, memory.facts.first().pinned)- assertFails<IllegalArgumentException> { MemoryListing.decode(WireJson.parseToJsonElement("""{"facts":[{"id":"","content":"fact","createdAt":0,"kind":"profile"}]}""")) }- }-- @Test fun `memory history keeps its cursor`() {- val detail = WireJson.decodeFromJsonElement<MemoryDetail>(WireJson.parseToJsonElement("""{"fact":{"id":"a","content":"x"},- "history":{"result":"v2","history_cursor":3},"timeline":{"result":"t"}}"""))- assertEquals(3, detail.history.cursor)- }}diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/MemoryTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/MemoryTest.ktnew file mode 100644index 00000000..524c874f--- /dev/null+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/MemoryTest.kt@@ -0,0 +1,36 @@+package com.codync.android.core++import kotlinx.serialization.json.decodeFromJsonElement+import org.junit.Assert.*+import org.junit.Test++class MemoryTest {+ @Test fun `a bot's memory decodes both layers, dreams, notes and the harness's own notes`() {+ val memory = WireJson.decodeFromJsonElement<BotMemory>(WireJson.parseToJsonElement("""{+ "shared": true,+ "yours": {"entries": [{"id": 4503599627370495, "bot": null, "state": "active", "text": "Lives in Taipei", "author": "user",+ "authorBot": null, "pinned": false, "evidence": [], "createdAt": 1, "updatedAt": 2}], "used": 12, "cap": 900},+ "bot": {"entries": [{"id": 7, "bot": "b", "state": "archived", "text": "Prefers tabs", "author": "bot", "authorBot": "b", "updatedAt": 3}],+ "used": 4, "cap": 600},+ "files": {"yours": {"files": [], "folder": "/m"}, "bot": {"files": [{"bot": "b", "name": "release.md", "description": "How releases go",+ "tokens": 812, "deleted": false, "updatedAt": 5}], "folder": "/m/b"}, "cap": 800, "folderCap": 20},+ "dreams": [{"id": 1, "at": 9, "undone": false, "added": [{"id": 8, "text": "Ships on Fridays"}], "archived": [],+ "files": [{"name": "release.md", "shared": false, "version": 2}]}],+ "projectMemory": {"path": "/home/me/.claude/projects/x/memory/MEMORY.md", "text": ""},+ "memoryRev": 41}"""))+ assertTrue(memory.shared)+ // Fact IDs are 52-bit numbers.+ assertEquals(4503599627370495, memory.yours.entries.single().id)+ assertTrue(memory.bot.entries.single().archived)+ assertEquals(812, memory.files?.bot?.files?.single()?.tokens)+ assertEquals("release.md", memory.dreams.single().files?.single()?.name)+ assertEquals("", memory.projectMemory?.text)+ }++ @Test fun `a host that keeps no harness notes or files still decodes`() {+ val memory = WireJson.decodeFromJsonElement<BotMemory>(WireJson.parseToJsonElement("""{"shared": false,+ "yours": {"entries": [], "used": 0, "cap": 900}, "bot": {"entries": [], "used": 0, "cap": 600}, "dreams": [], "projectMemory": null}"""))+ assertNull(memory.projectMemory)+ assertNull(memory.files)+ }+}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.ktindex 9f8c4595..72ca49ca 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@@ -8,7 +8,15 @@ class WidgetFeedTest {val bots = listOf(Bot("idle", "Idle"), Bot("hidden", "Hidden", hidden = true),Bot("deleted", "Deleted", deleted = true), Bot("working", "Working", status = "working"),Bot("approval", "Approval", status = "needsInput"))- assertEquals(listOf("approval", "working", "idle"), widgetBots(bots).map { it.id })+ assertEquals(listOf("approval", "working", "idle"), widgetBots(mapOf("mac" to bots)).map { it.id })+ }++ @Test fun `every computer's bots share one order and keep the computer they live on`() {+ val bots = widgetBots(mapOf("mac" to listOf(Bot("a", "Mac idle"), Bot("b", "Mac working", status = "working")),+ "linux" to listOf(Bot("a", "Linux approval", status = "needsInput"))))+ 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 })}@Test fun `team spots keep picks, skip deleted ones and fill the rest in feed order`() {diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/Symbols.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/Symbols.ktindex 860a943d..38258725 100644--- a/apps/android/design/src/main/kotlin/com/codync/android/design/Symbols.kt+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/Symbols.kt@@ -118,6 +118,8 @@ import androidx.annotation.DrawableRes"mic" -> R.drawable.sf_mic"mic.fill" -> R.drawable.sf_mic_fill"mic.slash" -> R.drawable.sf_mic_slash+ "minus.circle" -> R.drawable.sf_minus_circle+ "moon" -> R.drawable.sf_moon"moon.zzz.fill" -> R.drawable.sf_moon_zzz_fill"move" -> R.drawable.sf_move"music.note" -> R.drawable.sf_music_note@@ -170,6 +172,7 @@ import androidx.annotation.DrawableRes"terminal" -> R.drawable.sf_terminal"text.bubble" -> R.drawable.sf_text_bubble"trash" -> R.drawable.sf_trash+ "tray" -> R.drawable.sf_tray"waveform" -> R.drawable.sf_waveform"wifi" -> R.drawable.sf_wifi"wifi.exclamationmark" -> R.drawable.sf_wifi_exclamationmarkdiff --git a/apps/android/design/src/main/res/drawable/sf_minus_circle.xml b/apps/android/design/src/main/res/drawable/sf_minus_circle.xmlnew file mode 100644index 00000000..b8cfcfe0--- /dev/null+++ b/apps/android/design/src/main/res/drawable/sf_minus_circle.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Material Symbols Rounded `do_not_disturb_on`, Generated by tools/symbols.py. -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">+ <group android:translateY="960">+ <path android:fillColor="#FF000000" android:pathData="M325.5-434.5h309q19.15 0 32.33-13.17Q680-460.85 680-480t-13.17-32.33q-13.18-13.17-32.33-13.17h-309q-19.15 0-32.33 13.17Q280-499.15 280-480t13.17 32.33q13.18 13.17 32.33 13.17ZM480-71.87q-84.91 0-159.34-32.12-74.44-32.12-129.5-87.17-55.05-55.06-87.17-129.5Q71.87-395.09 71.87-480t32.12-159.34q32.12-74.44 87.17-129.5 55.06-55.05 129.5-87.17 74.43-32.12 159.34-32.12t159.34 32.12q74.44 32.12 129.5 87.17 55.05 55.06 87.17 129.5 32.12 74.43 32.12 159.34t-32.12 159.34q-32.12 74.44-87.17 129.5-55.06 55.05-129.5 87.17Q564.91-71.87 480-71.87Zm0-91q133.04 0 225.09-92.04 92.04-92.05 92.04-225.09 0-133.04-92.04-225.09-92.05-92.04-225.09-92.04-133.04 0-225.09 92.04-92.04 92.05-92.04 225.09 0 133.04 92.04 225.09 92.05 92.04 225.09 92.04ZM480-480Z"/>+ </group>+</vector>diff --git a/apps/android/design/src/main/res/drawable/sf_moon.xml b/apps/android/design/src/main/res/drawable/sf_moon.xmlnew file mode 100644index 00000000..6c6570d9--- /dev/null+++ b/apps/android/design/src/main/res/drawable/sf_moon.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Material Symbols Rounded `bedtime`, Generated by tools/symbols.py. -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">+ <group android:translateY="960">+ <path android:fillColor="#FF000000" android:pathData="M524-35.22q-84.99 0-159.36-32.38-74.37-32.37-129.52-87.52-55.15-55.15-87.52-129.52-32.38-74.37-32.38-159.36 0-126.8 70.44-230.57 70.45-103.76 189.06-148.86 26.06-10.87 49.49 4.54 23.42 15.41 23.62 43.43-.61 82.61 28.79 157.7 29.4 75.09 87.73 133.41 58.32 58.33 133.29 87.61t157.34 28.91q30.06.44 45.31 22.41 15.25 21.96 5.34 47.83-45.91 119.05-149.77 190.71Q652-35.22 524-35.22Zm0-91q83.7 0 155.71-40.89t114.77-113.11q-84.09-9.43-159.41-44.93-75.33-35.5-135.37-95.55-60.05-60.04-96.05-135.25-36-75.2-44.67-159.29-71.74 43-112.25 115.27Q206.22-527.7 206.22-444q0 132.61 92.58 225.2 92.59 92.58 225.2 92.58ZM499.7-420.7Z"/>+ </group>+</vector>diff --git a/apps/android/design/src/main/res/drawable/sf_tray.xml b/apps/android/design/src/main/res/drawable/sf_tray.xmlnew file mode 100644index 00000000..d01ad1b7--- /dev/null+++ b/apps/android/design/src/main/res/drawable/sf_tray.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Material Symbols Rounded `inbox`, Generated by tools/symbols.py. -->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp" android:height="24dp" android:viewportWidth="960" android:viewportHeight="960">+ <group android:translateY="960">+ <path android:fillColor="#FF000000" android:pathData="M202.87-111.87q-37.78 0-64.39-26.61t-26.61-64.39v-554.26q0-37.78 26.61-64.39t64.39-26.61h554.26q37.78 0 64.39 26.61t26.61 64.39v554.26q0 37.78-26.61 64.39t-64.39 26.61H202.87Zm0-91h554.26v-118.56H640q-30 38-71.5 59t-88.5 21q-47 0-88.5-21t-71.5-59H202.87v118.56ZM480-321.43q31.28 0 58.04-15.79 26.76-15.78 43.29-42.3 6.53-9.86 16.33-15.89 9.8-6.02 21.77-6.02h137.7v-355.7H202.87v355.7h137.7q11.97 0 21.77 6.02 9.8 6.03 16.33 15.89 16.53 26.52 43.29 42.3 26.76 15.79 58.04 15.79ZM202.87-202.87h554.26-554.26Z"/>+ </group>+</vector>diff --git a/apps/android/tools/symbols.py b/apps/android/tools/symbols.pyindex 2698422f..538a5215 100644--- a/apps/android/tools/symbols.py+++ b/apps/android/tools/symbols.py@@ -129,7 +129,10 @@ MAP = {"mic": "mic","mic.fill": "mic+","mic.slash": "mic_off",+ "moon": "bedtime",+ "minus.circle": "do_not_disturb_on","moon.zzz.fill": "bedtime+",+ "tray": "inbox","move": "open_with","music.note": "music_note","network": "public",