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(apps): improve workspace selection and custom icons
leepokaie752640a9f69
diff --git a/apps/Codync.xcodeproj/project.pbxproj b/apps/Codync.xcodeproj/project.pbxprojindex d883dc16..a8d17c3e 100644--- a/apps/Codync.xcodeproj/project.pbxproj+++ b/apps/Codync.xcodeproj/project.pbxproj@@ -76,6 +76,7 @@C7ED489193AC0934515D2E85 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = D0DE72EEAEC947C1D3CA237F /* PrivacyInfo.xcprivacy */; };CF8160C37D98BD7C1472CF49 /* ReviewInvitationModifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB1B021A5F4CCAA3D180C2CB /* ReviewInvitationModifier.swift */; };E0D116BF893B81AEC0D2135A /* BotShortcuts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 300202AE0BDAB4961D1E4423 /* BotShortcuts.swift */; };+ E1C181D77EA48DCDFEC2F15D /* CustomActivityIcon.swift in Sources */ = {isa = PBXBuildFile; fileRef = 365F24B61AEDCFE6C389E904 /* CustomActivityIcon.swift */; };E695251CFD06AC6F4E3396B7 /* OpenBotIntent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C4EB0DBA2F08CD7C0E25E30 /* OpenBotIntent.swift */; };E78E3B5FAFEB79F31AAC104D /* CodyncBot-teardrop-Tint.ttf in Resources */ = {isa = PBXBuildFile; fileRef = C8F46BD8301E7E2C83C35111 /* CodyncBot-teardrop-Tint.ttf */; };EBB0417A5FB2CE6D514D21BE /* ClerkKit in Frameworks */ = {isa = PBXBuildFile; productRef = D9AB2F442A5F243653EAE936 /* ClerkKit */; };@@ -139,6 +140,7 @@300202AE0BDAB4961D1E4423 /* BotShortcuts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotShortcuts.swift; sourceTree = "<group>"; };305DDCC18BB8AA6CD9D19CEF /* WidgetPreviews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WidgetPreviews.swift; sourceTree = "<group>"; };31BFDAD6DCCE1CC98642ACDD /* AccountSession.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AccountSession.swift; sourceTree = "<group>"; };+ 365F24B61AEDCFE6C389E904 /* CustomActivityIcon.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomActivityIcon.swift; sourceTree = "<group>"; };36C62636FD789C49762696A3 /* RosterSectionHeader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RosterSectionHeader.swift; sourceTree = "<group>"; };3F4C4D3B64C608AEF2F85F91 /* Kit */ = {isa = PBXFileReference; lastKnownFileType = folder; name = Kit; path = ios/Kit; sourceTree = SOURCE_ROOT; };445DB0A03CFBB5CC7A830139 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };@@ -306,6 +308,7 @@F1162D95B42A1BF2EB5EC0E9 /* CallControlIntents.swift */,F5B2717A8DFD43DC6DAA9D8C /* CallLiveActivity.swift */,FAB9BDB52C3A9F7B2568A750 /* CodyncWidgets.swift */,+ 365F24B61AEDCFE6C389E904 /* CustomActivityIcon.swift */,5C4EB0DBA2F08CD7C0E25E30 /* OpenBotIntent.swift */,305DDCC18BB8AA6CD9D19CEF /* WidgetPreviews.swift */,39BD6D06FC3DE74E5AA24856 /* Resources */,@@ -682,6 +685,7 @@B6ECB0743C67903DA1956B29 /* CallControlIntents.swift in Sources */,ECE1339FED40D7D5D8806608 /* CallLiveActivity.swift in Sources */,2CDF3DF16A13DAF83CA42168 /* CodyncWidgets.swift in Sources */,+ E1C181D77EA48DCDFEC2F15D /* CustomActivityIcon.swift in Sources */,5C9AE497DA83EB32AEC9057C /* OpenBotIntent.swift in Sources */,3BCC04815E5CA8953E0DDCAD /* WidgetPreviews.swift in Sources */,);diff --git a/apps/android/WhatsNew.md b/apps/android/WhatsNew.mdindex f5b0208e..e2b0c76e 100644--- a/apps/android/WhatsNew.md+++ b/apps/android/WhatsNew.md@@ -8,17 +8,14 @@ else a generic "Bug fixes and improvements" line. Delete old sections.-->## 2.33.2--### zh-Hant-- 電腦的推送通知設定會顯示系統權限狀態;未允許通知時,可直接前往開啟權限。--### en-US-- Computer push settings show when notification permission is missing and help you enable it.--## 2.33.1-### zh-Hant-- 選專案資料夾時,返回鍵可以往上走到家目錄以外的資料夾,Windows 電腦還能切換磁碟;連結(symlink)的資料夾也會出現在清單中。+- 選擇工作資料夾時可使用最近紀錄、貼上路徑,並在底部確認。+- 上傳圖片或貼上網址設定 bot 與 agent 圖示,支援原色、單色及離線快取;自訂圖片維持靜態。+- 自訂圖片需要登入。登入載入時只顯示進度,電腦選單新增裝置圖示。+- 推送設定顯示通知權限,並協助前往開啟。### en-US-- When you choose a project folder, Back climbs above your home folder and, on a Windows computer, to its other drives; linked folders now show up too.+- Choose recent workspaces, paste a path, and confirm at the bottom.+- Upload images or paste URLs for bot and agent icons, with colors, tinting and offline caching. Custom images stay still.+- Custom images require sign-in. Account loading shows progress; computer menus show device icons.+- Push settings show missing notification permission and help you enable it.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 889f44e6..6a301789 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@@ -72,34 +72,37 @@ class AgentSettingsScreenTest {@Test fun hostFolderBrowsingFiltersLocallyDrillsInAndSelectsTheAuthoritativeDirectory() {var chosen: String? = nullval requests = mutableListOf<String?>()- compose.setContent { Hosted { FolderPicker("/home", true, { path ->+ compose.setContent { Hosted { FolderPicker("/home", true, "Fixture computer", load = { path ->requests.add(path)- if (path == "/home/Repo") DirListing("/home/Repo", "/home", true, emptyList())- else DirListing("/home", "/", false, listOf(DirItem("Repo", "/home/Repo", true), DirItem("Other", "/home/Other")))- }) { chosen = it } } }+ if (path == "/home/Repo") DirListing("/home/Repo", "/home", true, emptyList(), recent = emptyList())+ else DirListing("/home", "/", false, listOf(DirItem("Repo", "/home/Repo", true), DirItem("Other", "/home/Other")), recent = emptyList())+ }, select = { it }) { chosen = it } } }+ compose.waitUntil { compose.onAllNodesWithText("Browse other folders").fetchSemanticsNodes().size == 1 }+ compose.onNodeWithText("Search recent workspaces").assertDoesNotExist()+ compose.onNodeWithText("Browse other folders").performClick()compose.waitUntil { compose.onAllNodesWithText("Repo").fetchSemanticsNodes().size == 1 }compose.onNode(hasSetTextAction()).performTextInput("repo")compose.onNodeWithText("Other").assertDoesNotExist()- assertEquals(listOf<String?>("/home"), requests)+ assertEquals(listOf(null, "/home"), requests)compose.onNodeWithText("Repo").performClick()- compose.waitUntil { compose.onAllNodesWithText("Use “Repo”").fetchSemanticsNodes().size == 1 }- assertEquals(listOf<String?>("/home", "/home/Repo"), requests)- compose.onNodeWithText("Use “Repo”").performClick()- assertEquals("/home/Repo", chosen)- compose.onNodeWithContentDescription("Back").performClick()+ compose.waitUntil { requests.lastOrNull() == "/home/Repo" }+ compose.onNodeWithText("Use this folder").performClick()+ compose.waitUntil { chosen == "/home/Repo" }+ assertEquals(listOf(null, "/home", "/home/Repo"), requests)+ compose.onNodeWithContentDescription("Parent folder").performClick()compose.waitUntil { compose.onAllNodesWithText("Other").fetchSemanticsNodes().size == 1 }- compose.onNodeWithText("Use “home”").performClick()- assertEquals("/home", chosen)+ compose.onNodeWithText("Use this folder").performClick()+ compose.waitUntil { chosen == "/home" }}@Test fun anUnavailableOrOfflineFolderShowsWhyWithoutOfferingIt() {val online = mutableStateOf(true)var loads = 0- compose.setContent { Hosted { FolderPicker("/missing", online.value, { loads++; throw java.io.IOException("This folder no longer exists.") }) {+ compose.setContent { Hosted { FolderPicker("/missing", online.value, "Fixture computer", load = { loads++; throw java.io.IOException("This folder no longer exists.") }, select = { fail("Unavailable folder must not be selected"); it }) {fail("A folder that failed to load can't be chosen")} } }compose.waitUntil { compose.onAllNodesWithText("This folder no longer exists.").fetchSemanticsNodes().size == 1 }- compose.onNodeWithText("Use “missing”").assertDoesNotExist()+ compose.onNodeWithText("Use this folder").assertIsNotEnabled()compose.runOnUiThread { online.value = false }compose.onNodeWithText("Connect to this computer to browse its folders.").assertIsDisplayed()assertEquals(1, loads)diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/CustomIconBitmapTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/CustomIconBitmapTest.ktnew file mode 100644index 00000000..e0dd5a51--- /dev/null+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/CustomIconBitmapTest.kt@@ -0,0 +1,40 @@+package com.codync.android++import android.graphics.Bitmap+import android.graphics.Color+import android.util.Base64+import com.codync.android.design.customAvatarBitmap+import com.codync.android.design.customIconBitmap+import java.io.ByteArrayOutputStream+import org.junit.Assert.*+import org.junit.Test++class CustomIconBitmapTest {+ private fun png(width: Int, height: Int): String {+ val image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888).apply { eraseColor(Color.RED) }+ val bytes = ByteArrayOutputStream().use { output ->+ image.compress(Bitmap.CompressFormat.PNG, 100, output)+ output.toByteArray()+ }+ image.recycle()+ return "data:image/png;base64," + Base64.encodeToString(bytes, Base64.NO_WRAP)+ }++ @Test fun originalAndTintedImagesKeepAspectRatioAndShareDecodedPixels() {+ val source = png(2, 1)+ assertSame(customIconBitmap(source), customIconBitmap(source))+ val original = requireNotNull(customAvatarBitmap(source, false, 16, Color.BLUE))+ val tinted = requireNotNull(customAvatarBitmap(source, true, 16, Color.BLUE))+ assertEquals(Color.RED, original.getPixel(8, 8))+ assertEquals(Color.BLUE, tinted.getPixel(8, 8))+ assertEquals(0, Color.alpha(original.getPixel(8, 0)))+ assertEquals(0, Color.alpha(tinted.getPixel(8, 0)))+ }++ @Test fun malformedAndOversizedImagesUseTheBuiltInFallback() {+ for (source in listOf("https://example.com/image.png", "data:image/png;base64,iVBORw0KGgo=", png(257, 1))) {+ assertNull(customIconBitmap(source))+ assertNull(customAvatarBitmap(source, false, 32, Color.BLUE))+ }+ }+}diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/MirrorDatabaseTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/MirrorDatabaseTest.ktindex 52883770..d8ae52b3 100644--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/MirrorDatabaseTest.kt+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/MirrorDatabaseTest.kt@@ -22,6 +22,45 @@ class MirrorDatabaseTest {@After fun cleanup() { mirror.close(); directory.deleteRecursively() }+ @Test fun iconCacheTracksNewerRevisionsAndResetsWithTheHostDatabase() {+ mirror.setStamp("old", "build")+ val first = CustomIcon("first")+ val latest = CustomIcon("latest", true)+ mirror.apply(MirrorEvent.Icons(mapOf("bot:b" to first), 1))+ val cached = mirror.icons()+ assertSame(cached, mirror.icons())+ MirrorDatabase(context, directory, computer).use { other ->+ other.apply(MirrorEvent.Icons(mapOf("bot:b" to latest), 2))+ }+ assertEquals(latest, mirror.icons()["bot:b"])+ mirror.apply(MirrorEvent.Icons(mapOf("bot:b" to first), 1))+ assertEquals(latest, mirror.icons()["bot:b"])+ mirror.apply(MirrorEvent.Icons(emptyMap(), 3))+ assertTrue(mirror.icons().isEmpty())+ mirror.setStamp("new", "build")+ mirror.apply(MirrorEvent.Icons(mapOf("bot:b" to first), 0))+ assertEquals(first, mirror.icons()["bot:b"])+ }++ @Test fun reconnectAcceptsSameHostRollbackAboveBotCursorAndRejectsOldSaveReplies() {+ mirror.setStamp("same-host", "build")+ mirror.apply(MirrorEvent.BotChanged(Bot("b", "Bot", rev = 50)))+ val old = CustomIcon("old")+ mirror.apply(MirrorEvent.Icons(mapOf("bot:b" to old), 100))+ val oldEpoch = mirror.iconEpoch()+ val currentEpoch = mirror.beginIconConnection()+ assertEquals(old, mirror.icons()["bot:b"]) // Keep the offline picture until catch-up arrives.+ mirror.apply(MirrorEvent.Hello("same-host", 90, JsonObject(emptyMap()), null))+ val restored = CustomIcon("restored")+ mirror.apply(MirrorEvent.Icons(mapOf("bot:b" to restored), 90))+ assertEquals(50, mirror.revision())+ assertEquals(restored, mirror.icons()["bot:b"])+ assertFalse(mirror.applyIconReply(MirrorEvent.Icons(mapOf("bot:b" to old), 110), oldEpoch))+ assertEquals(restored, mirror.icons()["bot:b"])+ assertTrue(mirror.applyIconReply(MirrorEvent.Icons(emptyMap(), 91), currentEpoch))+ assertTrue(mirror.icons().isEmpty())+ }+@Test fun rpcRepliesAndHelloCannotCheckpointPastUnseenEvents() {mirror.apply(MirrorEvent.Hello("database", 100, JsonObject(emptyMap()), null))mirror.receive(listOf(entry(90)))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 a3f65593..814c82db 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@@ -125,5 +125,7 @@ import com.kyant.shapes.RoundedRectangle/** The account face of the roster's top bar. */@Composable internal fun AccountAvatar(state: AppState, size: Dp) {val current = state.account.accounts.firstOrNull { it.userId == state.account.userId }- AccountAvatar(current?.avatar, current?.email, size)+ if (!state.account.ready || "session" in state.busy) {+ Box(Modifier.size(size), contentAlignment = Alignment.Center) { ThinkingOrb(size = size * 0.6f) }+ } else AccountAvatar(current?.avatar, current?.email, size)}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AgentSheet.kt b/apps/android/app/src/main/kotlin/com/codync/android/AgentSheet.ktindex f14e4b5d..1e1fa392 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AgentSheet.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AgentSheet.kt@@ -112,6 +112,7 @@ internal fun agentRegistry(state: AppState, agent: String) = agentBackends(stateval curated = backend.curatedval setUp = setUp(backend, auth)CardForm {+ CardSection { row { CustomIconEditor("agent:${backend.id}", state, store) } }CardSection {row {Row(Modifier.padding(vertical = 4.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp)) {diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AlertNotification.kt b/apps/android/app/src/main/kotlin/com/codync/android/AlertNotification.ktindex c1b8c595..bdfe1b0a 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AlertNotification.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AlertNotification.kt@@ -14,6 +14,9 @@ import androidx.core.graphics.drawable.IconCompatimport com.codync.android.core.AlertConversationimport com.codync.android.core.Botimport com.codync.android.design.characterAvatarBitmap+import com.codync.android.design.customAvatarBitmap+import com.codync.android.design.AvatarPalette+import androidx.compose.ui.graphics.toArgbimport com.codync.android.design.symbolRes/**@@ -67,9 +70,12 @@ internal fun notificationFace(context: Context, bot: Bot, members: List<Bot>): Bval end = start + FACEfun place(member: Bot, fraction: Float, x: Float, y: Float) {val pixels = (FACE * fraction).toInt()- canvas.drawBitmap(characterAvatarBitmap(member.avatarShape, member.avatarColor, pixels, DARK_INK, cells = 13), x, y, null)+ val face = customAvatarBitmap(member.customIcon?.dataUrl, member.customIcon?.tinted == true, pixels,+ AvatarPalette.tint(member.avatarColor).toArgb())+ ?: characterAvatarBitmap(member.avatarShape, member.avatarColor, pixels, DARK_INK, cells = 13)+ canvas.drawBitmap(face, x, y, null)}- if (bot.kind != "group") { place(bot, 1f, start, start); return bitmap }+ if (bot.kind != "group" || bot.customIcon != null) { place(bot, 1f, start, start); return bitmap }// An alert carries at most three members' faces: the first two and the speaker.when (members.size) {0 -> ContextCompat.getDrawable(context, requireNotNull(symbolRes("person.2")))?.mutate()?.run {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 a33facee..6176e928 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@@ -10,6 +10,7 @@ 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(),val contextId: String = "local",val generation: Int = 0,val account: AccountState = AccountState(),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 b0e679df..0e63e6d5 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@@ -190,7 +190,7 @@ class AppStore(application: Application) : AndroidViewModel(application) {val screen = snapshot.screen?.let { runCatching { ScreenState.decode(it) }.getOrNull() }mirrorBots = snapshot.botsmutableState.update { current -> current.copy(bots = withMoves(snapshot.bots, pendingSectionMoves), entries = snapshot.entries,- pending = snapshot.pending, usage = snapshot.usage, screen = screen, mirrorRevision = snapshot.rev,+ pending = snapshot.pending, usage = snapshot.usage, screen = screen, mirrorRevision = snapshot.rev, icons = snapshot.icons,selectedBot = current.selectedBot?.takeIf { id -> snapshot.bots.any { it.id == id } }) }if (voiceBinding != null && snapshot.bots.none { it.id == voiceBinding?.botId && !it.deleted }) endVoice("Voice chat ended because its bot was removed.")if (PushPreferences.tasks(getApplication())) {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 df603eab..8ab98c8c 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@@ -164,6 +164,11 @@ fun AppStore.refreshUsage(force: Boolean = true) = action("usage") {CodyncWidgets.update(getApplication())}}+suspend fun AppStore.selectWorkspace(path: String): String {+ return hostQuery("selectWorkspace", body("path" to path)).jsonObject["path"]?.jsonPrimitive?.content+ ?: error("Missing selected folder")+}+suspend fun AppStore.listDirs(path: String?): DirListing {val response = hostQuery("listDirs", body("path" to path))return WireJson.decodeFromJsonElement(response)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 4ef48447..3d336ced 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@@ -114,6 +114,9 @@ fun AppStore.connect() {}launch {active.state.collectLatest { link ->+ val iconEpoch = if (link is LinkState.Ready) {+ withContext(Dispatchers.IO) { requireNotNull(database).beginIconConnection() }+ } else nullshowConnection(link)if (link is LinkState.ComputerOffline) {reconcileMailbox(active)@@ -124,8 +127,12 @@ fun AppStore.connect() {// 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 }val dropped = withContext(Dispatchers.IO) {- requireNotNull(database).setStamp(requireNotNull(hello["hostId"]?.jsonPrimitive?.content),+ val mirror = requireNotNull(database)+ val changed = mirror.setStamp(requireNotNull(hello["hostId"]?.jsonPrimitive?.content),BuildConfig.VERSION_NAME + "/" + hello["version"]?.jsonPrimitive?.content)+ mirror.applyIconReply(MirrorEvent.Icons(hello["icons"]?.let(::decodeCustomIcons).orEmpty(),+ hello["iconsRevision"]?.jsonPrimitive?.longOrNull ?: 0), requireNotNull(iconEpoch))+ changed}// Dropped chats page their earlier messages again.mutableState.update { it.copy(historyComplete = if (dropped) emptySet() else it.historyComplete) }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.ktnew file mode 100644index 00000000..f5eb41c1--- /dev/null+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreIcons.kt@@ -0,0 +1,45 @@+package com.codync.android++import android.app.Application+import android.net.Uri+import android.util.Base64+import com.codync.android.core.*+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+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." }+ val data = file?.let { uri -> withContext(Dispatchers.IO) {+ val bytes = getApplication<Application>().contentResolver.openInputStream(uri)?.use { input ->+ val output = java.io.ByteArrayOutputStream()+ val buffer = ByteArray(8192)+ while (output.size() <= 5 * 1024 * 1024) {+ val count = input.read(buffer)+ if (count < 0) break+ output.write(buffer, 0, count)+ }+ output.toByteArray()+ }+ ?: error("Cannot read this image.")+ require(bytes.isNotEmpty() && bytes.size <= 5 * 1024 * 1024) { "Choose an image up to 5 MiB." }+ Base64.encodeToString(bytes, Base64.NO_WRAP)+ } }+ val active = ready()+ val mirror = requireNotNull(database)+ val epoch = mirror.iconEpoch()+ val response = active.call("setIcon", buildJsonObject {+ put("target", target)+ data?.let { put("data", it) }+ url?.let { put("url", it) }+ tinted?.let { put("tinted", it) }+ if (remove) put("remove", true)+ }, 60_000).jsonObject+ val icons = decodeCustomIcons(response.getValue("icons"))+ val applied = withContext(Dispatchers.IO) {+ mirror.applyIconReply(MirrorEvent.Icons(icons, response.getValue("iconsRevision").jsonPrimitive.long), epoch)+ }+ if (applied && database === mirror) refresh()+ }+}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/BotAvatar.kt b/apps/android/app/src/main/kotlin/com/codync/android/BotAvatar.ktindex c596472b..c19bec72 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/BotAvatar.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/BotAvatar.kt@@ -16,8 +16,8 @@ import com.codync.android.design.*/** A bot's character, or a group's members. */@Composable internal fun BotAvatar(bot: Bot, bots: List<Bot>, size: Dp = 44.dp) {- if (bot.kind == "group") GroupAvatar(bot.memberBots(bots).map { AvatarFace(it.avatarShape, it.avatarColor, it.status) }, size)- else CharacterAvatar(bot.avatarShape, bot.avatarColor, size, bot.status)+ if (bot.kind == "group" && bot.customIcon == null) GroupAvatar(bot.memberBots(bots).map { AvatarFace(it.avatarShape, it.avatarColor, it.status, it.customIcon?.dataUrl, it.customIcon?.tinted == true) }, size)+ else CharacterAvatar(bot.avatarShape, bot.avatarColor, size, bot.status, customImage = bot.customIcon?.dataUrl, customTinted = bot.customIcon?.tinted == true)}/** The roster's avatar, with its status dot (iOS `AvatarWithStatus`): amber needs you, the accent dot is unread. */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 ad24cc31..4c143be8 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@@ -318,8 +318,13 @@ internal fun messagePreview(text: String): String {val summary = connectionSummary(state)DropdownMenu({listOf(- MenuItem("All computers", icon = "checkmark"),- *state.computers.map { MenuItem("${it.name} · ${connectionLabel(state)}", icon = "checkmark") }.toTypedArray(),+ 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),)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 f8d04422..2e16ac0c 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@@ -51,6 +51,7 @@ internal enum class FormPart { All, Often, Rarely }CharacterAvatar(draft.avatarShape, draft.avatarColor, 96.dp)}AvatarPicker(draft.avatarShape, draft.avatarColor, { change(draft.copy(avatarShape = it)) }, { change(draft.copy(avatarColor = it)) })+ draft.id?.let { CustomIconEditor("bot:$it", state, store) }}CardSection("Profile") { nameRow(draft, change); instructionsRow(draft, change); createdByRow(state, bot) }CardSection("Agent") {@@ -75,6 +76,7 @@ internal enum class FormPart { All, Often, Rarely }FormPart.Rarely -> {CardSection("Profile") {row { AvatarPicker(draft.avatarShape, draft.avatarColor, { change(draft.copy(avatarShape = it)) }, { change(draft.copy(avatarColor = it)) }) }+ draft.id?.let { id -> row { CustomIconEditor("bot:$id", state, store) } }nameRow(draft, change); createdByRow(state, bot)}// The agent and its model are on the Details page; what's left is where it works.@@ -85,7 +87,7 @@ internal enum class FormPart { All, Often, Rarely }}}CodyncSheet(folders, { folders = false }) {- FolderPicker(draft.cwd.ifEmpty { state.hello?.get("home")?.jsonPrimitive?.contentOrNull }, online, store::listDirs) {+ FolderPicker(draft.cwd.ifEmpty { state.hello?.get("home")?.jsonPrimitive?.contentOrNull }, online, state.hello?.get("name")?.jsonPrimitive?.contentOrNull ?: "Computer", store::listDirs, store::selectWorkspace) {change(draft.copy(cwd = it)); folders = false}}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 820a858b..44e56d68 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@@ -157,7 +157,7 @@ internal class ConnectionRequestActions(val openApp: (String, ComposioApp) -> Un@Composable internal fun AuthorLabel(botId: String?, state: AppState, name: String? = null) {val bot = state.bots.firstOrNull { it.id == botId }Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {- if (bot != null) CharacterAvatar(bot.avatarShape, bot.avatarColor, 26.dp)+ if (bot != null) CharacterAvatar(bot.avatarShape, bot.avatarColor, 26.dp, customImage = bot.customIcon?.dataUrl, customTinted = bot.customIcon?.tinted == true)Text(state.authorName(botId, name), style = Type.subheadline.medium, color = bot?.let { AvatarPalette.tint(it.avatarColor) } ?: Palette.secondary)}}@@ -300,7 +300,7 @@ internal val Entry.reactions: List<String> get() = (data["reactions"] as? JsonArhorizontalArrangement = Arrangement.spacedBy(4.dp)) {Text(emoji, style = Type.system(15f))Row(horizontalArrangement = Arrangement.spacedBy((-5).dp)) {- for (bot in bots.take(3)) CharacterAvatar(bot.avatarShape, bot.avatarColor, 16.dp)+ for (bot in bots.take(3)) CharacterAvatar(bot.avatarShape, bot.avatarColor, 16.dp, customImage = bot.customIcon?.dataUrl, customTinted = bot.customIcon?.tinted == true)}}}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 a7243b49..c7852c1d 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@@ -301,10 +301,14 @@ private fun ticks(percent: Double, tint: Int, red: Int): Bitmap {return bitmap}-@Composable private fun Face(context: Context, shape: String, color: String, size: Dp, highlight: Int? = null) {+@Composable private fun Face(context: Context, shape: String, color: String, size: Dp, highlight: Int? = null, customIcon: com.codync.android.core.CustomIcon? = null) {val pixels = (size.value * context.resources.displayMetrics.density).toInt().coerceIn(1, 256)val inkColor = ink.getColor(context).toArgb()- val bitmap = remember(shape, color, pixels, inkColor, highlight) { characterAvatarBitmap(shape, color, pixels, inkColor, highlight) }+ val bitmap = remember(shape, color, pixels, inkColor, highlight, customIcon) {+ com.codync.android.design.customAvatarBitmap(customIcon?.dataUrl, customIcon?.tinted == true, pixels,+ com.codync.android.design.AvatarPalette.tint(color).toArgb())+ ?: characterAvatarBitmap(shape, color, pixels, inkColor, highlight)+ }Image(ImageProvider(bitmap), null, GlanceModifier.size(size))}@@ -352,7 +356,7 @@ private fun stateWord(bot: WidgetBot): Pair<String, Ink> = when (bot.status) {Spacer(GlanceModifier.defaultWeight())Summary(count, label, needs > 0, GlanceModifier)Row(GlanceModifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {- for (bot in bots.take(3)) Face(context, bot.avatarShape, bot.avatarColor, 23.dp)+ for (bot in bots.take(3)) Face(context, bot.avatarShape, bot.avatarColor, 23.dp, customIcon = bot.customIcon)Spacer(GlanceModifier.defaultWeight())if (working > 0 && needs > 0) Text("$working working", style = style(9f, secondary))}@@ -374,7 +378,7 @@ private fun stateWord(bot: WidgetBot): Pair<String, Ink> = when (bot.status) {val (word, tint) = stateWord(bot)val open = if (sample) GlanceModifier else GlanceModifier.clickable(actionStartActivity(widgetIntent(context, feed, bot.id)))Row(open.fillMaxWidth().padding(bottom = 8.dp), verticalAlignment = Alignment.CenterVertically) {- Face(context, bot.avatarShape, bot.avatarColor, 24.dp)+ Face(context, bot.avatarShape, bot.avatarColor, 24.dp, customIcon = bot.customIcon)Spacer(GlanceModifier.width(7.dp))Text(bot.name, GlanceModifier.defaultWeight(), style = style(11f, ink, FontWeight.Medium), maxLines = 1)Text(word, style = style(10f, tint, if (bot.status == "needsInput") FontWeight.Medium else FontWeight.Normal), maxLines = 1)@@ -397,7 +401,7 @@ private fun stateWord(bot: WidgetBot): Pair<String, Ink> = when (bot.status) {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) {- Face(context, bot.avatarShape, bot.avatarColor, 30.dp)+ Face(context, bot.avatarShape, bot.avatarColor, 30.dp, customIcon = bot.customIcon)Text(bot.name, style = style(9f, ink, FontWeight.Medium), maxLines = 1)}}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 facb272e..4c3207ac 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@@ -257,13 +257,7 @@ private const val NETWORK_ICON = "point.3.connected.trianglepath.dotted"val tint = color?.let(AvatarPalette::tint) ?: Palette.textBox(Modifier.size(size), contentAlignment = Alignment.Center) {if (device == "linux") Symbol("computer.linux", size = size * 0.55f, tint = tint)- else Symbol(when (device) {- "laptop" -> "laptopcomputer"- "macmini" -> "macmini"- "macstudio" -> "macstudio"- "macpro" -> "macpro.gen3"- else -> "desktopcomputer"- }, size = size * 0.6f, tint = tint)+ else Symbol(computerSymbol(device), size = size * 0.6f, tint = tint)}}@@ -300,3 +294,12 @@ private val ConnectionRoute.icon get() = when (this) {ConnectionRoute.CloudflareFirst -> "cloud"ConnectionRoute.DirectOnly -> "wifi"}++internal fun computerSymbol(device: String?): String = when (device) {+ "laptop" -> "laptopcomputer"+ "macmini" -> "macmini"+ "macstudio" -> "macstudio"+ "macpro" -> "macpro.gen3"+ "linux" -> "computer.linux"+ else -> "desktopcomputer"+}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.ktnew file mode 100644index 00000000..c37a7c30--- /dev/null+++ b/apps/android/app/src/main/kotlin/com/codync/android/CustomIconEditor.kt@@ -0,0 +1,70 @@+package com.codync.android++import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.layout.*+import androidx.compose.animation.AnimatedVisibility+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.ui.Alignment+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.material3.Text+import androidx.compose.runtime.*+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.codync.android.core.*+import com.codync.android.design.*++internal val LocalAgentIconOverrides = staticCompositionLocalOf<Map<String, CustomIcon>> { emptyMap() }++internal fun agentIconOverrides(state: AppState): Map<String, CustomIcon> = buildMap {+ for (agent in agentBackends(state)) state.icons["agent:${agent.id}"]?.let { icon ->+ put(agent.id, icon)+ agent.registry?.let { put(it, icon) }+ }+}++@Composable internal fun CustomIconEditor(target: String, state: AppState, store: AppStore) {+ if (state.hello?.containsKey("icons") != true) return+ var needsSignIn by remember { mutableStateOf(false) }+ val requireAccount: (() -> Unit) -> Unit = { action -> if (state.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 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) },+ )+ }+ Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(12.dp)) {+ Text(tr("Custom icon"), style = Type.subheadline.semibold, color = Palette.text)+ Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {+ if (icon != null) StaticCustomIcon(icon.dataUrl, icon.tinted, 40.dp)+ SecondaryButton("Upload image", enabled = enabled) { requireAccount { picker.launch(arrayOf("image/png", "image/jpeg", "image/webp", "image/svg+xml")) } }+ if (busy) ThinkingOrb(size = 18.dp)+ }+ if (icon != null) SecondaryButton("Use default", enabled = enabled) { store.setIcon(target, remove = true) }+ SecondaryButton("Paste URL", enabled = enabled) { requireAccount { showURL = !showURL } }+ AnimatedVisibility(showURL, enter = fadeIn(), exit = fadeOut()) {+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {+ Text(tr("Image URL"), style = Type.caption, color = Palette.secondary)+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ Box(Modifier.weight(1f)) { FieldBox(url, { if (enabled) url = it }, "https://…", capitalize = false) }+ IconButton("Use URL", "arrow.up", enabled = enabled && url.isNotBlank()) { requireAccount { store.setIcon(target, url = url.trim()) } }+ }+ }+ }+ if (icon != null) SwitchRow("Tint icon", isOn = icon.tinted, onChange = { store.setIcon(target, tinted = it) }, enabled = enabled)+ Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(2.dp)) {+ Text(tr("PNG, JPEG, WebP up to 5 MiB; SVG up to 256 KiB."), style = Type.caption, color = Palette.secondary, textAlign = TextAlign.Center)+ Text(tr("Saved immediately. Custom images stay still."), style = Type.caption, color = Palette.secondary, textAlign = TextAlign.Center)+ }+ if (state.error != null) Text(tr(state.error), style = Type.caption, color = Palette.danger)+ }+}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/FolderPicker.kt b/apps/android/app/src/main/kotlin/com/codync/android/FolderPicker.ktindex aa57cc0a..bb331b62 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/FolderPicker.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/FolderPicker.kt@@ -1,105 +1,124 @@package com.codync.androidimport androidx.activity.compose.BackHandler-import androidx.compose.animation.AnimatedContent-import androidx.compose.animation.slideInHorizontally-import androidx.compose.animation.slideOutHorizontally-import androidx.compose.animation.togetherWith-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.fillMaxSize-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.layout.width+import androidx.compose.animation.AnimatedVisibility+import androidx.compose.foundation.background+import androidx.compose.foundation.horizontalScroll+import androidx.compose.foundation.layout.*import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.verticalScrollimport androidx.compose.material3.Text-import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue+import androidx.compose.runtime.*import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier-import androidx.compose.ui.unit.dpimport androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dpimport com.codync.android.core.DirListingimport com.codync.android.design.*-import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.launch-/** Browses folders on the computer, drilling down in place (iOS `FolderPicker`). */-@Composable internal fun FolderPicker(start: String?, online: Boolean, load: suspend (String?) -> DirListing, pick: (String) -> Unit) {- var stack by remember { mutableStateOf(listOf(start)) }- var forward by remember { mutableStateOf(true) }- // Where the first folder sits, so Back can climb above the starting folder ("" lists the drives).- var parent by remember { mutableStateOf<String?>(null) }- val canGoBack = stack.size > 1 || parent != null- val back = { forward = false; stack = if (stack.size > 1) stack.dropLast(1) else listOf(parent) }- BackHandler(canGoBack) { back() }+/** Host-specific recent selections and browsing; never mixes paths from different computers. */+@Composable internal fun FolderPicker(start: String?, online: Boolean, computer: String,+ load: suspend (String?) -> DirListing, select: suspend (String) -> String, pick: (String) -> Unit) {+ val state = remember { WorkspacePickerState() }+ val scope = rememberCoroutineScope()+ val open = state::open+ val recent = state::showRecent+ val noRecent = state.mode == FolderMode.Recent && !state.busy && state.listing?.recent.orEmpty().isEmpty()+ BackHandler(state.mode == FolderMode.Browse) { recent() }+ LaunchedEffect(state.request, online) { state.load(online, load) }Column(Modifier.fillMaxSize()) {- Row(verticalAlignment = Alignment.CenterVertically) {- if (canGoBack) Box(Modifier.padding(start = 12.dp)) { BackButton { back() } }- Box(Modifier.weight(1f)) { ModalHeader(stack.last()?.let(::folderName) ?: "Folders") }- }- AnimatedContent(stack, transitionSpec = {- val sign = if (forward) 1 else -1- slideInHorizontally(Motion.layoutOffset) { it * sign } togetherWith slideOutHorizontally(Motion.layoutOffset) { -it * sign }- }, label = "Folder") { shown ->- val onParent: ((String?) -> Unit)? = if (shown.size > 1) null else { found -> parent = found }- FolderLevel(shown.last(), online, load, pick, onParent) { forward = true; stack = stack + it }- }- }-}--/** One folder's subfolders, filterable, with "Use" on top. */-@Composable private fun FolderLevel(path: String?, online: Boolean, load: suspend (String?) -> DirListing, pick: (String) -> Unit,- onParent: ((String?) -> Unit)?, open: (String) -> Unit) {- var listing by remember { mutableStateOf<DirListing?>(null) }- var error by remember { mutableStateOf<String?>(null) }- var filter by remember { mutableStateOf("") }- LaunchedEffect(path, online) {- if (!online) { error = "Connect to this computer to browse its folders."; return@LaunchedEffect }- try { listing = load(path).also { onParent?.invoke(it.parent) }; error = null }- catch (cancelled: CancellationException) { throw cancelled }- catch (failure: Exception) { error = failure.message ?: "Couldn't open this folder." }- }- Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(20.dp), verticalArrangement = Arrangement.spacedBy(22.dp)) {- SearchField(filter, { filter = it })- val current = listing- when {- current != null -> {- // The drive list (Windows) has no folder of its own to use.- if (current.path.isNotEmpty()) CardSection(footer = current.path) {- row {- Row(Modifier.fillMaxWidth().plainButton { pick(current.path) }, verticalAlignment = Alignment.CenterVertically,- horizontalArrangement = Arrangement.spacedBy(8.dp)) {- Symbol("checkmark.circle.fill", size = 20.dp, tint = Palette.accent)- Text("Use “${folderName(current.path)}”", style = Type.headline, color = Palette.accent)+ ModalHeader("Choose workspace")+ Column(Modifier.weight(1f).verticalScroll(rememberScrollState()).padding(horizontal = 20.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {+ Text(tr("Your bot will work in this folder."), style = Type.subheadline, color = Palette.secondary)+ Row(Modifier.fillMaxWidth().background(Palette.surface, RoundedCornerShape(12.dp)).padding(12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {+ Symbol("desktopcomputer", size = 18.dp)+ Text(computer, Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis, style = Type.body)+ Text(tr(if (online) "Connected" else "Disconnected"), style = Type.caption, color = Palette.secondary)+ }+ if (noRecent) FolderBrowse(!state.saving) { open(start) }+ if (state.mode == FolderMode.Browse) Row(verticalAlignment = Alignment.CenterVertically) {+ IconButton("Recent workspaces", "chevron.left", enabled = !state.saving) { recent() }+ Row(Modifier.weight(1f).horizontalScroll(rememberScrollState()), verticalAlignment = Alignment.CenterVertically) {+ val ancestors = state.listing?.ancestors+ if (ancestors != null) ancestors.forEachIndexed { i, dir ->+ if (i > 0) Text("/", color = Palette.tertiary, style = Type.caption)+ Text(dir.name, Modifier.padding(6.dp).plainButton(enabled = !state.saving) { open(dir.path) }, style = Type.caption, maxLines = 1)+ } else Text(state.listing?.path ?: tr("Folders"), style = Type.caption, maxLines = 1)+ }+ IconButton("Parent folder", "arrow.up", enabled = state.listing?.parent != null && !state.busy && !state.saving) { state.listing?.parent?.let(open) }+ IconButton("Enter folder path", "pencil", enabled = !state.saving) { state.pathInput = state.listing?.path.orEmpty(); state.pathOpen = !state.pathOpen }+ }+ AnimatedVisibility(state.pathOpen) {+ Row(Modifier.background(Palette.surface, RoundedCornerShape(10.dp)).padding(10.dp), verticalAlignment = Alignment.CenterVertically) {+ PlainTextField(state.pathInput, { state.pathInput = it }, Modifier.weight(1f), prompt = "Paste an absolute path", singleLine = true, enabled = !state.saving)+ IconButton("Go to folder", "arrow.right", enabled = state.pathInput.isNotBlank() && !state.saving) { open(state.pathInput.trim()) }+ }+ }+ if (!noRecent) {+ SearchField(state.filter, { state.filter = it }, prompt = if (state.mode == FolderMode.Recent) "Search recent workspaces" else "Filter this folder")+ Text(tr(if (state.mode == FolderMode.Recent) "Recent workspaces" else "Folders"), style = Type.caption, color = Palette.secondary)+ when {+ state.busy -> Box(Modifier.fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center) { Spinner(20.dp) }+ state.mode == FolderMode.Recent -> {+ val items = state.listing?.recent.orEmpty().filter { it.path.contains(state.filter, ignoreCase = true) }+ Column {+ items.forEach { item ->+ Row(Modifier.fillMaxWidth().background(if (state.selected == item.path) Palette.surface else androidx.compose.ui.graphics.Color.Transparent, RoundedCornerShape(12.dp))+ .plainButton(enabled = !state.saving) { state.selected = item.path }.padding(12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ Symbol("folder", size = 18.dp, tint = Palette.secondary)+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Text(item.path.split('/', '\\').lastOrNull { it.isNotEmpty() } ?: item.path, style = Type.body, maxLines = 1, overflow = TextOverflow.Ellipsis)+ Text(item.path, style = Type.caption, color = Palette.secondary, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ if (state.selected == item.path) Symbol("checkmark", size = 16.dp)+ }+ }+ if (items.isEmpty()) FolderEmpty(if (state.filter.isEmpty()) "Choose a folder to see it here next time." else "No matching folders.")}}- }- val dirs = current.dirs.filter { filter.isBlank() || it.name.contains(filter.trim(), ignoreCase = true) }- if (dirs.isNotEmpty()) CardSection {- for (dir in dirs) row {- Row(Modifier.fillMaxWidth().plainButton { open(dir.path) }, verticalAlignment = Alignment.CenterVertically,- horizontalArrangement = Arrangement.spacedBy(10.dp)) {- Box(Modifier.width(20.dp), contentAlignment = Alignment.Center) {- Symbol(if (dir.isGit) "arrow.triangle.branch" else "folder", size = 18.dp, tint = if (dir.isGit) Palette.accent else Palette.secondary)+ else -> {+ val dirs = state.listing?.dirs.orEmpty().filter { it.name.contains(state.filter, ignoreCase = true) }+ Column {+ dirs.forEach { dir ->+ Row(Modifier.fillMaxWidth().plainButton(enabled = !state.saving) { open(dir.path) }.padding(vertical = 13.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ Symbol(if (dir.isGit) "arrow.triangle.branch" else "folder", size = 18.dp, tint = Palette.secondary)+ Text(dir.name, Modifier.weight(1f), style = Type.body, maxLines = 1, overflow = TextOverflow.Ellipsis)+ Symbol("chevron.right", size = 12.dp, tint = Palette.tertiary)+ }}- Text(dir.name, Modifier.weight(1f), style = Type.body, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)- Symbol("chevron.right", size = 13.dp, tint = Palette.tertiary)+ if (state.listing != null && dirs.isEmpty()) FolderEmpty(if (state.filter.isEmpty()) "No subfolders. You can use this folder." else "No matching folders.")}}}}- error != null -> Text(tr(error.orEmpty()), style = Type.body, color = Palette.danger)- else -> Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { Spinner(20.dp) }+ state.error?.let { Text(tr(it), style = Type.subheadline, color = Palette.danger) }+ if (state.mode == FolderMode.Recent && !noRecent) FolderBrowse(!state.saving) { open(start) }+ Spacer(Modifier.height(12.dp))+ }+ Row(Modifier.fillMaxWidth().background(Palette.surface).padding(20.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Text(tr(if (state.mode == FolderMode.Recent) "Selected folder" else "Current folder"), style = Type.caption, color = Palette.secondary)+ Text(state.selected.ifEmpty { tr("Choose a folder") }, style = Type.caption, maxLines = 1, overflow = TextOverflow.Ellipsis)+ }+ PrimaryButton(if (state.saving) "Saving…" else "Use this folder", enabled = state.selected.isNotEmpty() && online && !state.busy && !state.saving) {+ scope.launch { state.confirm(load, select)?.let(pick) }+ }}}}-/** A path's last folder, for `/` and Windows `\` paths alike; null for the drive list (""). */-private fun folderName(path: String): String? = path.split('/', '\\').lastOrNull { it.isNotEmpty() } ?: path.ifEmpty { null }+@Composable private fun FolderEmpty(message: String) {+ Box(Modifier.fillMaxWidth().padding(vertical = 24.dp), contentAlignment = Alignment.Center) {+ Text(tr(message), style = Type.subheadline, color = Palette.secondary)+ }+}++@Composable private fun FolderBrowse(enabled: Boolean, onBrowse: () -> Unit) {+ Row(Modifier.fillMaxWidth().plainButton(enabled = enabled, action = onBrowse).padding(vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ Symbol("folder", size = 18.dp)+ Text(tr("Browse other folders"), Modifier.weight(1f), style = Type.body)+ Symbol("chevron.right", size = 12.dp)+ }+}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..4f9df6aa 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@@ -68,6 +68,7 @@ class MainActivity : ComponentActivity() {val phrases = remember(appLanguage, systemTag) { AppLanguageStore.phrases(applicationContext, appLanguage, systemTag) }val systemChinese = remember(systemTag) { systemScript(systemTag) != null }CompositionLocalProvider(+ LocalAgentIconOverrides provides agentIconOverrides(state),LocalNetworkImages provides images,LocalAppLanguage provides appLanguage,LocalSystemChinese provides systemChinese,diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MarketRows.kt b/apps/android/app/src/main/kotlin/com/codync/android/MarketRows.ktindex f9235330..9928d1a5 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/MarketRows.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/MarketRows.kt@@ -95,6 +95,8 @@ import com.kyant.shapes.RoundedRectangle/** A coding agent's logo by ACP registry id, in its brand color when it has one; a terminal glyph otherwise. */@Composable internal fun AgentIcon(registry: String?, size: Dp) {+ val custom = LocalAgentIconOverrides.current[registry]+ if (StaticCustomIcon(custom?.dataUrl, custom?.tinted == true, size)) returnval tint = AGENT_TINTS[registry]?.let { Color(it) } ?: Palette.textval res = agentIconRes(registry)if (res != null) Image(painterResource(res), null, Modifier.size(size).clearAndSetSemantics {}, colorFilter = ColorFilter.tint(tint))diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MirrorDatabase.kt b/apps/android/app/src/main/kotlin/com/codync/android/MirrorDatabase.ktindex 0be3bebc..5988e545 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/MirrorDatabase.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/MirrorDatabase.kt@@ -41,15 +41,50 @@ class MirrorDatabase(context: Context, directory: File, computerId: String) :db.execSQL("CREATE TABLE history(lane TEXT PRIMARY KEY)")}+ private var decodedIcons: Map<String, com.codync.android.core.CustomIcon>? = null+ private var decodedIconsRevision: String? = null++ private var iconConnectionEpoch = 0L++ /** A reconnect's snapshot is authoritative even after restoring an older database with the same host id. */+ @Synchronized fun beginIconConnection(): Long = transaction { db ->+ iconConnectionEpoch+++ db.delete("meta", "k='iconsRevision'", null)+ iconConnectionEpoch+ }++ @Synchronized fun iconEpoch(): Long = iconConnectionEpoch++ /** A reply from a previous connection cannot repopulate the newly restored cache. */+ @Synchronized fun applyIconReply(event: MirrorEvent.Icons, epoch: Long): Boolean {+ if (epoch != iconConnectionEpoch) return false+ apply(event)+ return true+ }++ /** Read only the image metadata; a push need not load the conversation history. */+ @Synchronized fun icons(): Map<String, com.codync.android.core.CustomIcon> {+ val db = readableDatabase+ val revision = meta(db, "iconsRevision")+ if (decodedIcons != null && decodedIconsRevision == revision) return requireNotNull(decodedIcons)+ return meta(db, "icons")?.let { com.codync.android.core.decodeCustomIcons(WireJson.parseToJsonElement(it)) }.orEmpty().also {+ decodedIcons = it+ decodedIconsRevision = revision+ }+ }+@Synchronized fun snapshot(): MirrorSnapshot {val db = readableDatabase+ val icons = icons()return MirrorSnapshot(- rows(db, "SELECT payload FROM bots WHERE deleted=0") { WireJson.decodeFromString<Bot>(it) },+ rows(db, "SELECT payload FROM bots WHERE deleted=0") { WireJson.decodeFromString<Bot>(it) }+ .map { it.copy(customIcon = icons["bot:${it.id}"]) },rows(db, "SELECT payload FROM entries ORDER BY seq") { WireJson.decodeFromString<Entry>(it) },rows(db, "SELECT payload FROM pending ORDER BY created") { WireJson.decodeFromString<PendingSend>(it) },meta(db, "rev")?.toLong() ?: 0,meta(db, "usage")?.let { WireJson.parseToJsonElement(it).jsonObject } ?: JsonObject(emptyMap()),meta(db, "screen")?.let { WireJson.parseToJsonElement(it).jsonObject },+ icons,)}@@ -72,6 +107,11 @@ class MirrorDatabase(context: Context, directory: File, computerId: String) :@Synchronized fun apply(event: MirrorEvent) = apply(listOf(event))@Synchronized fun apply(events: List<MirrorEvent>) = transaction { db ->for (event in events) when (event) {+ is MirrorEvent.Icons -> if (event.revision >= (meta(db, "iconsRevision")?.toLong() ?: -1)) {+ setMeta(db, "icons", WireJson.encodeToString(event.icons))+ setMeta(db, "iconsRevision", event.revision.toString())+ decodedIcons = null+ }is MirrorEvent.Hello -> {if (meta(db, "hostId")?.let { it != event.hostId } == true) reset(db)setMeta(db, "hostId", event.hostId)@@ -145,9 +185,11 @@ class MirrorDatabase(context: Context, directory: File, computerId: String) :entry.clientNonce?.takeIf { entry.kind == "user" && it.isNotEmpty() }?.let { db.delete("pending", "nonce=?", arrayOf(it)) }}private fun reset(db: SQLiteDatabase) {+ decodedIcons = null+ decodedIconsRevision = nulldb.delete("bots", null, null)dropConversation(db)- db.delete("meta", "k IN ('usage','screen')", null)+ db.delete("meta", "k IN ('usage','screen','icons','iconsRevision')", null)}private fun dropConversation(db: SQLiteDatabase) {listOf("entries", "history").forEach { db.delete(it, null, null) }diff --git a/apps/android/app/src/main/kotlin/com/codync/android/NotificationIcons.kt b/apps/android/app/src/main/kotlin/com/codync/android/NotificationIcons.ktnew file mode 100644index 00000000..98ae00ce--- /dev/null+++ b/apps/android/app/src/main/kotlin/com/codync/android/NotificationIcons.kt@@ -0,0 +1,19 @@+package com.codync.android++import android.content.Context+import com.codync.android.core.CustomIcon++/** A notification can use only its active account's paired-computer cache. No network or chat reads. */+internal fun notificationIcons(context: Context, scope: String, computer: String): Map<String, CustomIcon> {+ if (PushPreferences.retired(context)) return emptyMap()+ val user = PushPreferences.activeUser(context) ?: "local"+ if (LocalStore.referenceId(user) != scope) return emptyMap()+ return try {+ val local = LocalStore(context, user)+ if (local.computers().none { it.id == computer }) return emptyMap()+ MirrorDatabase(context, local.directory, computer).use { it.icons() }+ } catch (error: Exception) {+ android.util.Log.w("Codync", "Notification uses its built-in face because the image cache is unavailable", error)+ emptyMap()+ }+}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 3394e4de..55627c93 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@@ -234,7 +234,7 @@ internal object NotificationDisplay {val builder = builder(context, scope, computer, bot, ALERTS, kind.orEmpty()).setContentTitle(alert.title).setContentText(alert.body).setSubText(alert.subtitle).setStyle(NotificationCompat.BigTextStyle().bigText(alert.body)).setAutoCancel(true).setCategory(NotificationCompat.CATEGORY_MESSAGE)- alert.conversation(bot)?.let { conversation ->+ alert.copy(faces = alert.faces.withCustomIcons(notificationIcons(context, scope, computer))).conversation(bot)?.let { conversation ->// A system that refuses the conversation still shows the plain alert.try { AlertConversations.style(context, builder, tag, computer, open(context, scope, computer, bot), alert.body, conversation) }catch (error: Exception) { android.util.Log.w("Codync", "Alert shown without its conversation", error) }@@ -275,7 +275,10 @@ internal object NotificationDisplay {val style = Notification.ProgressStyle().setStyledByProgress(true).setProgressSegments(List(4) { Notification.ProgressStyle.Segment(25).setColor(tint) }).setProgress(filled * 25)- val face = com.codync.android.design.characterAvatarBitmap(watch.avatarShape, watch.avatarColor, 128, 0xFF141414.toInt())+ val custom = notificationIcons(context, scope, computer)["bot:${watch.botId}"]+ val face = com.codync.android.design.customAvatarBitmap(custom?.dataUrl, custom?.tinted == true, 128,+ com.codync.android.design.AvatarPalette.colors[watch.avatarColor]?.toInt() ?: 0xFF1084FE.toInt())+ ?: com.codync.android.design.characterAvatarBitmap(watch.avatarShape, watch.avatarColor, 128, 0xFF141414.toInt())val open = builder(context, scope, computer, watch.botId, TASKS).build().contentIntentval notification = Notification.Builder(context, TASKS).setSmallIcon(R.drawable.ic_notification).setContentTitle(watch.name).setContentText(text).setLargeIcon(android.graphics.drawable.Icon.createWithBitmap(face)).setContentIntent(open).setStyle(style)diff --git a/apps/android/app/src/main/kotlin/com/codync/android/WidgetCards.kt b/apps/android/app/src/main/kotlin/com/codync/android/WidgetCards.ktindex 3733138c..87b12d2b 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/WidgetCards.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/WidgetCards.kt@@ -285,7 +285,7 @@ private fun rank(bot: WidgetBot) = when (bot.status) { "needsInput" -> 0; "workisummary()Row(verticalAlignment = Alignment.CenterVertically) {Row(horizontalArrangement = Arrangement.spacedBy((-4).dp)) {- for (bot in ordered.take(3)) CharacterAvatar(bot.avatarShape, bot.avatarColor, 23.dp)+ for (bot in ordered.take(3)) CharacterAvatar(bot.avatarShape, bot.avatarColor, 23.dp, customImage = bot.customIcon?.dataUrl, customTinted = bot.customIcon?.tinted == true)}Spacer(Modifier.weight(1f))if (working > 0 && needs > 0) Text("$working working", style = Type.system(9f), color = Palette.secondary)@@ -300,7 +300,7 @@ private fun rank(bot: WidgetBot) = when (bot.status) { "needsInput" -> 0; "workifor (bot in bots) {val (label, tint) = widgetState(bot.status)Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(7.dp)) {- CharacterAvatar(bot.avatarShape, bot.avatarColor, 24.dp)+ CharacterAvatar(bot.avatarShape, bot.avatarColor, 24.dp, customImage = bot.customIcon?.dataUrl, customTinted = bot.customIcon?.tinted == true)Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(1.dp)) {Text(widgetName(bot), style = Type.system(11f).semibold, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)val activity = activities[bot.id]?.takeIf { bot.status == "working" || bot.status == "needsInput" }@@ -322,7 +322,7 @@ private fun rank(bot: WidgetBot) = when (bot.status) { "needsInput" -> 0; "workiif (bot == null) Box(Modifier.size(26.dp)) { CharacterAvatar("blob", "gray", 26.dp, monochrome = Palette.text.copy(alpha = 0.18f)) }else {Column(Modifier.padding(horizontal = 4.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(4.dp)) {- CharacterAvatar(bot.avatarShape, bot.avatarColor, 30.dp, bot.status)+ CharacterAvatar(bot.avatarShape, bot.avatarColor, 30.dp, bot.status, customImage = bot.customIcon?.dataUrl, customTinted = bot.customIcon?.tinted == true)Text(widgetName(bot), style = Type.system(9f).semibold, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)}if (bot.status == "working" || bot.status == "error") Box(Modifier.align(Alignment.TopEnd).padding(7.dp).size(7.dp)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 06a4daee..4e1adf24 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/WidgetRefreshWorker.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/WidgetRefreshWorker.kt@@ -37,6 +37,7 @@ class WidgetRefreshWorker(context: Context, parameters: WorkerParameters) : Coroval 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)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 e9712efd..3b5e7b3c 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@@ -87,12 +87,12 @@ internal object WidgetStore {@Synchronized fun refreshLanguage() { changed() }private fun changed() { changes.value++ }private inline fun <reified T> read(file: AtomicFile): T? = try {- if (!file.baseFile.exists() || file.baseFile.length() > 512 * 1024) null+ if (!file.baseFile.exists() || file.baseFile.length() > MAX_WIDGET_FEED_BYTES) nullelse WireJson.decodeFromString<T>(file.readFully().toString(Charsets.UTF_8))} catch (_: Exception) { null }private inline fun <reified T> write(file: AtomicFile, value: T) {val bytes = WireJson.encodeToString(value).toByteArray()- require(bytes.size <= 512 * 1024) { "The widget report is too large." }+ require(bytes.size <= MAX_WIDGET_FEED_BYTES) { "The widget report is too large." }val output = file.startWrite()try { output.write(bytes); file.finishWrite(output) }catch (error: Throwable) { file.failWrite(output); throw error }diff --git a/apps/android/app/src/main/kotlin/com/codync/android/WorkspacePickerState.kt b/apps/android/app/src/main/kotlin/com/codync/android/WorkspacePickerState.ktnew file mode 100644index 00000000..a7ebf715--- /dev/null+++ b/apps/android/app/src/main/kotlin/com/codync/android/WorkspacePickerState.kt@@ -0,0 +1,80 @@+package com.codync.android++import androidx.compose.runtime.*+import com.codync.android.core.DirListing+import kotlinx.coroutines.CancellationException++internal enum class FolderMode { Recent, Browse }++/** Navigation and request lifetime, independent of the composable that renders it. */+internal class WorkspacePickerState {+ var mode by mutableStateOf(FolderMode.Recent)+ private set+ var path by mutableStateOf<String?>(null)+ private set+ var listing by mutableStateOf<DirListing?>(null)+ private set+ var selected by mutableStateOf("")+ var filter by mutableStateOf("")+ var error by mutableStateOf<String?>(null)+ private set+ var busy by mutableStateOf(true)+ private set+ var saving by mutableStateOf(false)+ private set+ var pathOpen by mutableStateOf(false)+ var pathInput by mutableStateOf("")+ var request by mutableIntStateOf(0)+ private set+ private var generation = 0++ fun open(next: String?) {+ if (saving) return+ mode = FolderMode.Browse+ path = next+ selected = ""+ filter = ""+ pathOpen = false+ request+++ }++ fun showRecent() {+ if (saving) return+ mode = FolderMode.Recent+ path = null+ selected = ""+ filter = ""+ pathOpen = false+ request+++ }++ suspend fun load(online: Boolean, fetch: suspend (String?) -> DirListing) {+ val current = ++generation+ listing = null+ error = null+ busy = true+ try {+ check(online) { "Connect to this computer to browse its folders." }+ val result = fetch(path)+ if (current != generation) return+ listing = result+ if (mode == FolderMode.Browse) selected = result.path+ } catch (cancelled: CancellationException) { throw cancelled }+ catch (failure: Exception) {+ if (current == generation) error = failure.message ?: "Couldn't open this folder."+ } finally { if (current == generation) busy = false }+ }++ suspend fun confirm(fetch: suspend (String?) -> DirListing, select: suspend (String) -> String): String? {+ if (saving || busy || selected.isEmpty()) return null+ val current = generation+ saving = true+ error = null+ return try {+ val chosen = if (listing?.recent != null) select(selected) else fetch(selected).path+ chosen.takeIf { current == generation }+ } catch (cancelled: CancellationException) { throw cancelled }+ catch (failure: Exception) { error = failure.message ?: "Couldn't open this folder."; null }+ finally { saving = false }+ }+}diff --git a/apps/android/app/src/test/kotlin/com/codync/android/WorkspacePickerStateTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/WorkspacePickerStateTest.ktnew file mode 100644index 00000000..e31b7a14--- /dev/null+++ b/apps/android/app/src/test/kotlin/com/codync/android/WorkspacePickerStateTest.kt@@ -0,0 +1,56 @@+package com.codync.android++import com.codync.android.core.DirListing+import kotlinx.coroutines.CompletableDeferred+import kotlinx.coroutines.CoroutineStart+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import org.junit.Assert.*+import org.junit.Test++class WorkspacePickerStateTest {+ private fun listing(path: String, recent: Boolean = true) = DirListing(path, dirs = emptyList(), recent = if (recent) emptyList() else null)++ @Test fun `same folder can be reopened and recent closes path input`() = runBlocking {+ val state = WorkspacePickerState()+ state.open("/project")+ state.load(true) { listing(it!!) }+ state.open("/project")+ state.load(true) { listing(it!!) }+ assertEquals("/project", state.selected)+ state.pathOpen = true+ state.showRecent()+ assertFalse(state.pathOpen)+ assertEquals("", state.selected)+ }++ @Test fun `older host validates without calling unsupported selection method`() = runBlocking {+ val state = WorkspacePickerState()+ state.open("/project")+ state.load(true) { listing(it!!, recent = false) }+ val chosen = state.confirm({ listing(it!!, recent = false) }, { error("unsupported endpoint") })+ assertEquals("/project", chosen)+ }++ @Test fun `failed selection stays open and shows the error`() = runBlocking {+ val state = WorkspacePickerState()+ state.open("/gone")+ state.load(true) { listing(it!!) }+ assertNull(state.confirm({ listing(it!!) }, { error("Folder was removed") }))+ assertEquals("Folder was removed", state.error)+ assertFalse(state.saving)+ }++ @Test fun `older folder response cannot replace newer navigation`() = runBlocking {+ val state = WorkspacePickerState()+ val first = CompletableDeferred<DirListing>()+ state.open("/old")+ val pending = launch(start = CoroutineStart.UNDISPATCHED) { state.load(true) { first.await() } }+ state.open("/new")+ state.load(true) { listing(it!!) }+ first.complete(listing("/old"))+ pending.join()+ assertEquals("/new", state.selected)+ assertEquals("/new", state.listing?.path)+ }+}diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/AgentSettings.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/AgentSettings.ktindex 53ae5348..614b96e3 100644--- a/apps/android/core/src/main/kotlin/com/codync/android/core/AgentSettings.kt+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/AgentSettings.kt@@ -24,5 +24,7 @@ import kotlinx.serialization.Serializable}data class ModelChoice(val id: String?, val name: String, val description: String? = null)-@Serializable data class DirListing(val path: String, val parent: String? = null, val isGit: Boolean = false, val dirs: List<DirItem>)+@Serializable data class RecentWorkspace(val path: String, val usedAt: Long)+@Serializable data class DirListing(val path: String, val parent: String? = null, val isGit: Boolean = false, val dirs: List<DirItem>,+ val recent: List<RecentWorkspace>? = null, val ancestors: List<DirItem>? = null)@Serializable data class DirItem(val name: String, val path: String, val isGit: Boolean = false)diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/BotSnapshot.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/BotSnapshot.ktindex 8aeeed4c..5fea5f7b 100644--- a/apps/android/core/src/main/kotlin/com/codync/android/core/BotSnapshot.kt+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/BotSnapshot.kt@@ -14,12 +14,15 @@ internal suspend fun botSnapshot(events: Flow<JsonObject>): List<Bot> {val bots = linkedMapOf<String, Bot>()var head: Long? = nullvar complete = false+ var remaining: Long? = null+ var icons: Map<String, CustomIcon>? = nullevents.takeWhile { event ->when (event.text("type")) {"hello" -> {check(head == null) { "The computer restarted its roster snapshot." }head = requireNotNull(event["rev"]?.jsonPrimitive?.longOrNull).also { require(it >= 0) }- complete = head == 0L+ remaining = event["catchUp"]?.jsonPrimitive?.longOrNull?.also { require(it >= 0) }+ complete = remaining?.let { it == 0L } ?: (head == 0L)}"bot", "entry" -> {val target = requireNotNull(head) { "The computer sent updates before its snapshot header." }@@ -30,10 +33,18 @@ internal suspend fun botSnapshot(events: Flow<JsonObject>): List<Bot> {val revision = requireNotNull(event["rev"]?.jsonPrimitive?.longOrNull)complete = revision >= target}+ "icons" -> {+ requireNotNull(head) { "The computer sent icons before its snapshot header." }+ icons = decodeCustomIcons(event.getValue("icons"))+ }"resync" -> throw IOException("The computer's roster changed too quickly. Try again.")}+ if (event.text("type") != "hello") remaining?.let {+ remaining = it - 1+ complete = remaining == 0L+ }!complete}.collect()check(complete) { "The computer disconnected before its roster finished loading." }- return bots.values.toList()+ return icons?.let { bots.values.toList().withCustomIcons(it) } ?: bots.values.toList()}diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.ktindex fbd7e554..e1829257 100644--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt@@ -149,6 +149,7 @@ data class PendingSend(data class OutgoingFile(val path: String, val name: String, val size: Long)sealed interface MirrorEvent {+ data class Icons(val icons: Map<String, CustomIcon>, val revision: Long = 0) : MirrorEvent/** The stream's first event; `network` is null from hosts before the network view (or one this app can't read). */data class Hello(val hostId: String, val rev: Long, val usage: JsonObject, val screen: JsonObject?, val network: NetworkView? = null) : MirrorEventdata class BotChanged(val bot: Bot) : MirrorEvent@@ -166,6 +167,7 @@ sealed interface MirrorEvent {companion object {fun decode(value: JsonObject): MirrorEvent = when (value.text("type")) {+ "icons" -> Icons(decodeCustomIcons(value.getValue("icons")), value["iconsRevision"]?.jsonPrimitive?.longOrNull ?: 0)"hello" -> Hello(requireNotNull(value.text("hostId")),requireNotNull(value["rev"]?.jsonPrimitive?.longOrNull),value["usage"]?.jsonObject ?: JsonObject(emptyMap()), value["screen"]?.takeUnless { it == JsonNull }?.jsonObject,@@ -193,4 +195,5 @@ data class MirrorSnapshot(val rev: Long = 0,val usage: JsonObject = JsonObject(emptyMap()),val screen: JsonObject? = null,+ val icons: Map<String, CustomIcon> = emptyMap(),)diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/CustomIcon.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/CustomIcon.ktnew file mode 100644index 00000000..10a2483f--- /dev/null+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/CustomIcon.kt@@ -0,0 +1,15 @@+package com.codync.android.core++import kotlinx.serialization.Serializable+import kotlinx.serialization.json.JsonElement+import kotlinx.serialization.json.decodeFromJsonElement++@Serializable data class CustomIcon(val dataUrl: String, val tinted: Boolean = false)++fun decodeCustomIcons(value: JsonElement): Map<String, CustomIcon> = WireJson.decodeFromJsonElement(value)++/** Apply the current image snapshot, including removals, without replacing fresh bot metadata. */+fun List<Bot>.withCustomIcons(icons: Map<String, CustomIcon>): List<Bot> = map { it.copy(customIcon = icons["bot:${it.id}"]) }++/** 128 normalized images plus the existing 512 KiB summary allowance. */+const val MAX_WIDGET_FEED_BYTES = 128 * 65_558 + 512 * 1024diff --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 e3195e2c..5a0caaef 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@@ -69,6 +69,7 @@ data class Bot(val agentStep: AgentStep? = null,/** Agents of its chain resting now. */val resting: List<Resting> = emptyList(),+ val customIcon: CustomIcon? = null,) {/** Its band in the roster: pinned bots, then the rest. Reordering stays inside a band. */val band: Int get() = if (pinned) 0 else 1diff --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 d22ad445..75148b30 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,7 +4,7 @@ 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 unread: Int = 0, val avatarColor: String = "blue", val avatarShape: String = "blob", val customIcon: CustomIcon? = null)@Serializable data class WidgetFeed(val scope: String = "local", val computerId: String? = null,val computerName: String = "", val bots: List<WidgetBot> = emptyList(), val botsAt: Long = 0,@@ -35,4 +35,4 @@ fun teamSlots(bots: List<WidgetBot>, picks: List<String?>): List<WidgetBot?> {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) }+ .take(256).map { WidgetBot(it.id, it.name.take(256), it.status, it.unread, it.avatarColor, it.avatarShape, it.customIcon) }diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/BotSnapshotTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/BotSnapshotTest.ktindex 6c08ac0d..7074504b 100644--- a/apps/android/core/src/test/kotlin/com/codync/android/core/BotSnapshotTest.kt+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/BotSnapshotTest.kt@@ -41,4 +41,26 @@ class BotSnapshotTest {botSnapshot(flowOf(header(8), buildJsonObject { put("type", "resync") }))} }}++ @Test fun `icon-only revisions complete the advertised catch-up and decorate bot faces`() = runBlocking {+ val icon = CustomIcon("data:image/png;base64,iVBORw0KGgo=", true)+ val stream = flow {+ emit(buildJsonObject { put("type", "hello"); put("rev", 50); put("catchUp", 2) })+ emit(buildJsonObject { put("type", "icons"); put("iconsRevision", 50)+ put("icons", WireJson.encodeToJsonElement(mapOf("bot:b" to icon))) })+ emit(bot("b", 3))+ fail("An icon revision need not be a bot/entry revision to finish the snapshot")+ }+ assertEquals(icon, botSnapshot(stream).single().customIcon)+ }++ @Test fun `empty icon snapshot removes stale inline custom faces`() = runBlocking {+ val result = botSnapshot(flowOf(+ buildJsonObject { put("type", "hello"); put("rev", 3); put("catchUp", 2) },+ buildJsonObject { put("type", "icons"); put("icons", buildJsonObject {}) },+ buildJsonObject { put("type", "bot"); put("rev", 3)+ put("bot", WireJson.encodeToJsonElement(Bot("b", "Bot", rev = 3, customIcon = CustomIcon("stale")))) },+ ))+ assertNull(result.single().customIcon)+ }}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.ktnew file mode 100644index 00000000..0fa93ff5--- /dev/null+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/CustomIconTest.kt@@ -0,0 +1,38 @@+package com.codync.android.core++import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.encodeToString+import org.junit.Assert.*+import org.junit.Test++class CustomIconTest {+ @Test fun iconsEventsPreserveOriginalColorsAndWidgetImages() {+ val event = MirrorEvent.decode(WireJson.parseToJsonElement("""{"type":"icons","icons":{"bot:b":{"dataUrl":"data:image/png;base64,iVBORw0KGgo=","tinted":false}}}""").jsonObject) as MirrorEvent.Icons+ val icon = event.icons.getValue("bot:b")+ assertFalse(icon.tinted)+ val bots = widgetBots(listOf(Bot("b", "Scout", customIcon = icon)))+ assertEquals(icon, bots.single().customIcon)+ val cleared = MirrorEvent.decode(WireJson.parseToJsonElement("""{"type":"icons","icons":{}}""").jsonObject) as MirrorEvent.Icons+ assertTrue(cleared.icons.isEmpty())+ }++ @Test fun cachedNotificationIconsPreserveFreshNamesAndClearRemovedImages() {+ val icon = CustomIcon("data:image/png;base64,iVBORw0KGgo=", true)+ val fresh = listOf(Bot("b", "New name", customIcon = icon), Bot("member", "Speaker"))+ val enriched = fresh.withCustomIcons(mapOf("bot:member" to icon))+ assertEquals("New name", enriched[0].name)+ assertNull(enriched[0].customIcon)+ assertEquals(icon, enriched[1].customIcon)+ val alert = PushAlert("title", body = "body", from = "member", faces =+ listOf(Bot("group", "Team", kind = "group", members = listOf("member"))) + enriched)+ assertEquals(icon, alert.conversation("group")?.speaker?.customIcon)+ }++ @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()+ 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/design/src/main/kotlin/com/codync/android/design/CharacterAvatar.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/CharacterAvatar.ktindex a9de5605..db96c881 100644--- a/apps/android/design/src/main/kotlin/com/codync/android/design/CharacterAvatar.kt+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/CharacterAvatar.kt@@ -32,7 +32,7 @@ object AvatarPalette {fun tint(id: String): Color = Color(colors[id] ?: colors.getValue("blue"))}-data class AvatarFace(val shape: String, val color: String, val status: String = "idle")+data class AvatarFace(val shape: String, val color: String, val status: String = "idle", val customImage: String? = null, val customTinted: Boolean = false)/** Static system-widget drawing uses the same mask, palette and eyes as the app; [cells] is its grid (7, 9 or 13). */fun characterAvatarBitmap(shape: String, color: String, pixels: Int, ink: Int, highlight: Int? = null, cells: Int = 9): android.graphics.Bitmap {@@ -64,7 +64,8 @@ fun characterAvatarBitmap(shape: String, color: String, pixels: Int, ink: Int, h/** Port of CodyncKit's dotted character; the accompanying name/status supplies accessibility text. */@Composable fun CharacterAvatar(shape: String, color: String, size: Dp = 40.dp, status: String = "idle", monochrome: Color? = null,- highlight: Color? = null) {+ highlight: Color? = null, customImage: String? = null, customTinted: Boolean = false) {+ if (StaticCustomIcon(customImage, customTinted, size, monochrome ?: AvatarPalette.tint(color))) returnval owner = LocalLifecycleOwner.currentvar active by remember(owner) { mutableStateOf(owner.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) }DisposableEffect(owner) {@@ -72,7 +73,7 @@ fun characterAvatarBitmap(shape: String, color: String, pixels: Int, ink: Int, howner.lifecycle.addObserver(observer)onDispose { owner.lifecycle.removeObserver(observer) }}- val time = if (active && status in listOf("working", "needsInput") && ValueAnimator.areAnimatorsEnabled()) {+ val time = if (customImage == null && active && status in listOf("working", "needsInput") && ValueAnimator.areAnimatorsEnabled()) {val transition = rememberInfiniteTransition(label = "Character activity")val seconds by transition.animateFloat(0f, 3600f, infiniteRepeatable(tween(3_600_000, easing = LinearEasing)), label = "Character light and eyes")seconds.toDouble()@@ -111,7 +112,7 @@ fun characterAvatarBitmap(shape: String, color: String, pixels: Int, ink: Int, hfun side(fraction: Float) = size * fraction@Composable fun place(index: Int, fraction: Float, align: Alignment) {val face = faces[index]- Box(Modifier.align(align)) { CharacterAvatar(face.shape, face.color, side(fraction), face.status) }+ Box(Modifier.align(align)) { CharacterAvatar(face.shape, face.color, side(fraction), face.status, customImage = face.customImage, customTinted = face.customTinted) }}when (faces.size) {0 -> Symbol("person.2", Modifier.align(Alignment.Center), size = size * 0.4f, tint = Palette.secondary)diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/CustomIcon.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/CustomIcon.ktnew file mode 100644index 00000000..45ecee23--- /dev/null+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/CustomIcon.kt@@ -0,0 +1,61 @@+package com.codync.android.design++import android.graphics.Bitmap+import android.graphics.BitmapFactory+import android.graphics.Canvas+import android.graphics.Paint+import android.graphics.PorterDuff+import android.graphics.PorterDuffColorFilter+import android.graphics.RectF+import android.util.Base64+import android.util.LruCache+import androidx.compose.foundation.Image+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.ColorFilter+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.unit.Dp++/** PNGs are immutable; share bounded decoded images across rows, widgets and notifications. */+private val decodedIcons = object : LruCache<String, Bitmap>(4 * 1024 * 1024) {+ override fun sizeOf(key: String, value: Bitmap) = value.allocationByteCount+}++fun customIconBitmap(dataUrl: String?): Bitmap? {+ val prefix = "data:image/png;base64,"+ if (dataUrl == null || !dataUrl.startsWith(prefix) || dataUrl.length > 65_558) return null+ decodedIcons.get(dataUrl)?.let { return it }+ val bytes = try { Base64.decode(dataUrl.substring(prefix.length), Base64.NO_WRAP) }+ catch (_: IllegalArgumentException) { return null }+ if (bytes.size < 8 || !bytes.take(8).toByteArray().contentEquals(byteArrayOf(-119, 80, 78, 71, 13, 10, 26, 10))) return null+ val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)+ if (bounds.outWidth !in 1..256 || bounds.outHeight !in 1..256) return null+ return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)?.also { decodedIcons.put(dataUrl, it) }+}++/** A static aspect-fit bitmap suitable for system widgets and notification faces. */+fun customAvatarBitmap(dataUrl: String?, tinted: Boolean, pixels: Int, tint: Int): Bitmap? {+ require(pixels in 1..256)+ val image = customIconBitmap(dataUrl) ?: return null+ val bitmap = Bitmap.createBitmap(pixels, pixels, Bitmap.Config.ARGB_8888)+ val scale = pixels.toFloat() / maxOf(image.width, image.height)+ val width = image.width * scale+ val height = image.height * scale+ val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG).apply {+ if (tinted) colorFilter = PorterDuffColorFilter(tint, PorterDuff.Mode.SRC_IN)+ }+ Canvas(bitmap).drawBitmap(image, null, RectF((pixels - width) / 2, (pixels - height) / 2,+ (pixels + width) / 2, (pixels + height) / 2), paint)+ return bitmap+}++/** Returns false for a missing/damaged image so the caller renders its normal fallback. */+@Composable fun StaticCustomIcon(dataUrl: String?, tinted: Boolean, size: Dp, color: Color = Palette.text): Boolean {+ val bitmap = remember(dataUrl) { customIconBitmap(dataUrl)?.asImageBitmap() } ?: return false+ Image(bitmap, null, Modifier.size(size), colorFilter = if (tinted) ColorFilter.tint(color) else null)+ return true+}diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/Menus.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/Menus.ktindex 65c96a96..a38a20c0 100644--- a/apps/android/design/src/main/kotlin/com/codync/android/design/Menus.kt+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/Menus.kt@@ -81,6 +81,7 @@ class MenuItem(val children: List<MenuItem>? = null,/** Shows [title] as it is, never translated: a name the user gave (a section's). */val verbatim: Boolean = false,+ val detail: String? = null,val action: () -> Unit = {},) {/** [title] as the row shows it: through [translate], unless [verbatim]. */@@ -252,6 +253,7 @@ private val MenuShape = RoundedRectangle(26.dp).padding(start = 16.dp, end = 16.dp, top = 4.dp, bottom = 4.dp),verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(13.dp)) {val leading = when {+ item.icon != null -> item.iconitem.selected == true -> "checkmark"item.selected == false -> nullelse -> item.icon@@ -259,7 +261,11 @@ private val MenuShape = RoundedRectangle(26.dp)Box(Modifier.size(24.dp), contentAlignment = Alignment.Center) {if (leading != null) Symbol(leading, size = 21.dp, tint = ink)}- Text(item.shownTitle(translator()), Modifier.weight(1f), style = if (bold) Type.body.semibold else Type.body, color = ink)+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {+ Text(item.shownTitle(translator()), style = if (bold) Type.body.semibold else Type.body, color = ink)+ item.detail?.let { Text(tr(it), style = Type.caption, color = Palette.secondary) }+ }+ if (item.icon != null && item.selected == true) Symbol("checkmark", size = 16.dp, tint = ink)if (item.children != null) Symbol("chevron.right", size = 16.dp, tint = Palette.secondary)}}diff --git a/apps/desktop/src/renderer/client/host-client.ts b/apps/desktop/src/renderer/client/host-client.tsindex cef2f5b4..0bf62476 100644--- a/apps/desktop/src/renderer/client/host-client.ts+++ b/apps/desktop/src/renderer/client/host-client.ts@@ -64,8 +64,9 @@ export class LoopbackTransport implements HostTransport {}export type HostEvent =+ | { type: 'icons'; iconsRevision: number; icons: import('@shared/custom-icons').CustomIcons }/** `network` is null from hosts before the network view. */- | { type: 'hello'; hostId: string; rev: number; usage: Usage; screen: ScreenState | null; network: NetworkView | null }+ | { type: 'hello'; hostId: string; rev: number; usage: Usage; screen: ScreenState | null; network: NetworkView | null; icons?: import('@shared/custom-icons').CustomIcons }| { type: 'bot'; bot: Bot }| { type: 'botDeleted'; id: string; rev: number }| { type: 'entry'; entry: Entry }@@ -92,6 +93,8 @@ export function parseEvent(line: string): HostEvent | null {}const type = raw.typeswitch (type) {+ case 'icons':+ return { type, iconsRevision: Number(raw.iconsRevision ?? 0), icons: (raw.icons ?? {}) as import('@shared/custom-icons').CustomIcons }case 'hello':return {type,@@ -100,6 +103,7 @@ export function parseEvent(line: string): HostEvent | null {usage: (raw.usage as Usage) ?? { providers: [] },screen: normalizeScreen(raw.screen as ScreenState | undefined),network: (raw.network as NetworkView | undefined) ?? null,+ icons: raw.icons as import('@shared/custom-icons').CustomIcons | undefined,}case 'bot': {const bot = raw.bot as (Bot & { deleted?: boolean }) | undefineddiff --git a/apps/desktop/src/renderer/components/AgentIcon.tsx b/apps/desktop/src/renderer/components/AgentIcon.tsxindex 6a872245..8610edf2 100644--- a/apps/desktop/src/renderer/components/AgentIcon.tsx+++ b/apps/desktop/src/renderer/components/AgentIcon.tsx@@ -1,4 +1,5 @@import { Icon } from './Icon'+import { CustomIcon, useAgentIcon } from './CustomIcon'// Agents' logos by ACP registry id, or by Codync's id for agents outside the registry// (template images: drawn in the current color).@@ -11,6 +12,11 @@ export function agentIconURL(registry: string | null | undefined) {/** An agent's logo from the ACP registry, or a generic terminal when it has none. */export function AgentIcon({ registry, size, color = 'currentColor' }: { registry?: string | null; size: number; color?: string }) {+ const custom = useAgentIcon(registry)+ return <CustomIcon icon={custom} size={size} color={color} fallback={<BundledIcon registry={registry} size={size} color={color} />} />+}++function BundledIcon({ registry, size, color }: { registry?: string | null; size: number; color: string }) {const url = agentIconURL(registry)if (!url) return <Icon name="terminal" size={size * 0.8} scaled={false} color={color} />return (diff --git a/apps/desktop/src/renderer/components/Avatar.tsx b/apps/desktop/src/renderer/components/Avatar.tsxindex f3719e93..6703149f 100644--- a/apps/desktop/src/renderer/components/Avatar.tsx+++ b/apps/desktop/src/renderer/components/Avatar.tsx@@ -5,6 +5,7 @@ import { avatarColor, palette, useDark, usePixelRatio, useReduceMotion } from '.import { Icon } from './Icon'import './avatar.css'import { LeadAgentBadge } from './LeadAgentBadge'+import { CustomIcon } from './CustomIcon'export type Mood = 'idle' | 'working' | 'needsInput' | 'failed'@@ -70,6 +71,11 @@ export function characterPath(kind: string, w: number, h: number) {return { path: p, stroke }}+export function CharacterAvatar(props: CharacterProps) {+ return <CustomIcon icon={props.customIcon} size={props.size ?? 40} color={props.tint ?? avatarColor(props.color)}+ fallback={<GeneratedCharacterAvatar {...props} mood={props.customIcon ? 'idle' : props.mood} />} />+}+interface Dot {row: numbercol: number@@ -102,6 +108,7 @@ function grid(shape: string, size: number, cells: number): Dot[] {}interface CharacterProps {+ customIcon?: import('@shared/custom-icons').CustomIconshape: string/** An avatar palette id, or a CSS color with `tint`. */color: string@@ -116,7 +123,7 @@ interface CharacterProps {* Grok-Bot-style character drawn like the app icon: an even grid of dots shaded as if the* silhouette were a ball, with hollow eyes that glance while it works and blink now and then.*/-export const CharacterAvatar = memo(function CharacterAvatar({ shape, color, tint, size = 40, mood = 'idle', dark: forceDark }: CharacterProps) {+const GeneratedCharacterAvatar = memo(function GeneratedCharacterAvatar({ shape, color, tint, size = 40, mood = 'idle', dark: forceDark }: CharacterProps) {const canvas = useRef<HTMLCanvasElement>(null)const dark = useDark() || forceDark === trueconst reduce = useReduceMotion()@@ -227,7 +234,9 @@ export function moodOf(bot: Bot, animated = true): Mood {}export function BotAvatar({ bot, size = 40, animated = true }: { bot: Bot; size?: number; animated?: boolean }) {- return <CharacterAvatar shape={bot.avatarShape} color={bot.avatarColor} size={size} mood={moodOf(bot, animated)} />+ return <CustomIcon icon={bot.customIcon} size={size} color={avatarColor(bot.avatarColor)} fallback={+ <CharacterAvatar shape={bot.avatarShape} color={bot.avatarColor} size={size} mood={moodOf(bot, animated && !bot.customIcon)} />+ } />}/**@@ -283,7 +292,7 @@ export function GroupAvatar({ members, size = 40, animated = true }: { members:export function AvatarWithStatus({ bot, members = [], size = 44 }: { bot: Bot; members?: Bot[]; size?: number }) {return (<div className={`avatar-frame ${bot.lead ? 'lead-avatar' : ''}`} style={{ width: size, height: size }}>- {isGroup(bot) ? <GroupAvatar members={members} size={size} /> : <BotAvatar bot={bot} size={size} />}+ {isGroup(bot) && !bot.customIcon ? <GroupAvatar members={members} size={size} /> : <BotAvatar bot={bot} size={size} />}{bot.lead ? <LeadAgentBadge size={Math.max(12, size * 0.34)} /> : null}{needsInput(bot) ? (<div className="avatar-badge needs-you" style={{ width: size * 0.36, height: size * 0.36 }}>diff --git a/apps/desktop/src/renderer/components/CustomIcon.tsx b/apps/desktop/src/renderer/components/CustomIcon.tsxnew file mode 100644index 00000000..f0adb7d1--- /dev/null+++ b/apps/desktop/src/renderer/components/CustomIcon.tsx@@ -0,0 +1,23 @@+import { useContext, useState, type ReactNode } from 'react'+import { validIcon, type CustomIcon as IconData } from '@shared/custom-icons'+import { StoreContext } from '../store/context'+import { useModel } from '../lib/observable'++export function useAgentIcon(registry?: string | null) {+ const store = useModel(useContext(StoreContext))+ const backend = store?.hello?.backends.find((b) => b.id === registry || b.registry === registry)+ return store?.icons[`agent:${backend?.id ?? registry}`]+}++/** Static normalized image, including when the bot is working. */+export function CustomIcon({ icon, size, color = 'currentColor', fallback }: {+ icon?: IconData; size: number; color?: string; fallback: ReactNode+}) {+ const [failed, setFailed] = useState<string | null>(null)+ if (!validIcon(icon) || failed === icon.dataUrl) return fallback+ return <img src={icon.dataUrl} alt="" width={size} height={size} onError={() => setFailed(icon.dataUrl)}+ style={{ objectFit: 'contain', flex: 'none', ...(icon.tinted ? {+ background: color, objectPosition: '-9999px', maskImage: `url("${icon.dataUrl}")`,+ maskSize: 'contain', maskPosition: 'center', maskRepeat: 'no-repeat',+ } : {}) }} />+}diff --git a/apps/desktop/src/renderer/components/Overlay.tsx b/apps/desktop/src/renderer/components/Overlay.tsxindex e2694d91..104ace6a 100644--- a/apps/desktop/src/renderer/components/Overlay.tsx+++ b/apps/desktop/src/renderer/components/Overlay.tsx@@ -201,6 +201,8 @@ export function Dialog({ open, title, message, actions, cancel = 'Cancel', onClo/** One row in a Codync menu: an action, or a choice when `selected` is set. */export interface MenuItem {title: string+ /** Secondary context below the main label. */+ detail?: stringicon?: string/** A picture in the icon's place (an agent's logo). */leading?: ReactNode@@ -288,7 +290,10 @@ export function MenuPanel({ items, reactions, dismiss, maxHeight }: { items: Men{item.leading ?? (item.icon ? <Icon name={item.icon} size={12} /> : null)}</span>) : null}- <span className="menu-title">{item.verbatim ? item.title : tr(item.title)}</span>+ <span className={`menu-title${item.detail ? ' with-detail' : ''}`}>+ <span>{item.verbatim ? item.title : tr(item.title)}</span>+ {item.detail && <span className="menu-detail">{tr(item.detail)}</span>}+ </span>{item.selected !== undefined ? (<span className={`check-slot${item.selected ? ' on' : ''}`}><Icon name="checkmark" size={10} weight="semibold" />diff --git a/apps/desktop/src/renderer/components/overlay.css b/apps/desktop/src/renderer/components/overlay.cssindex b15ff4e2..7bb42180 100644--- a/apps/desktop/src/renderer/components/overlay.css+++ b/apps/desktop/src/renderer/components/overlay.css@@ -250,7 +250,9 @@align-items: center;gap: 10px;width: 100%;- padding: 6px 10px;+ padding: 8px 10px;+ min-height: 34px;+ line-height: 1.35;border-radius: var(--radius-s);font-size: var(--text-callout);color: var(--text);@@ -270,8 +272,13 @@}.menu-title {flex: 1;- margin-right: 16px;+ min-width: 0;+ margin-right: 8px;+ text-align: left;+ overflow-wrap: anywhere;}+.menu-title.with-detail { display: flex; flex-direction: column; gap: 2px; }+.menu-detail { font-size: var(--text-caption); color: var(--secondary); }.reaction-button {display: grid;diff --git a/apps/desktop/src/renderer/lib/icon-bitmap.ts b/apps/desktop/src/renderer/lib/icon-bitmap.tsnew file mode 100644index 00000000..8a501bbd--- /dev/null+++ b/apps/desktop/src/renderer/lib/icon-bitmap.ts@@ -0,0 +1,35 @@+import { validIcon, type CustomIcon } from '../../shared/custom-icons'++const bitmaps = new Map<string, { image: HTMLImageElement; ready: Promise<void> }>()++/** One decode per cached PNG. Invalid images use the caller's built-in fallback. */+export function iconBitmap(icon: CustomIcon | undefined) {+ if (!validIcon(icon)) return undefined+ let entry = bitmaps.get(icon.dataUrl)+ if (!entry) {+ const image = new Image()+ const ready = new Promise<void>((resolve) => { image.onload = () => resolve(); image.onerror = () => resolve() })+ image.src = icon.dataUrl+ entry = { image, ready }+ bitmaps.set(icon.dataUrl, entry)+ if (bitmaps.size > 128) bitmaps.delete(bitmaps.keys().next().value!)+ }+ return entry+}++export function drawIconBitmap(ctx: CanvasRenderingContext2D, icon: CustomIcon | undefined, size: number, color: string): boolean {+ const image = iconBitmap(icon)?.image+ if (!image?.complete || !image.naturalWidth) return false+ const scale = size / Math.max(image.naturalWidth, image.naturalHeight)+ const width = image.naturalWidth * scale+ const height = image.naturalHeight * scale+ ctx.save()+ ctx.drawImage(image, (size - width) / 2, (size - height) / 2, width, height)+ if (icon?.tinted) {+ ctx.globalCompositeOperation = 'source-in'+ ctx.fillStyle = color+ ctx.fillRect(0, 0, size, size)+ }+ ctx.restore()+ return true+}diff --git a/apps/desktop/src/renderer/lib/icon-cache.test.ts b/apps/desktop/src/renderer/lib/icon-cache.test.tsnew file mode 100644index 00000000..a21669a1--- /dev/null+++ b/apps/desktop/src/renderer/lib/icon-cache.test.ts@@ -0,0 +1,60 @@+import { strict as assert } from 'node:assert'+import { test } from 'node:test'+import { loadIconCache, saveIconCache } from './icon-cache.ts'++test('disk cache keeps the newest replacement and removal, isolated by account/computer', async () => {+ const values = new Map<string, unknown>()+ let failNextWrite = false+ const original = globalThis.indexedDB+ // Delay the first open: independent writes would otherwise allow an old image to win.+ let opens = 0+ globalThis.indexedDB = { open() {+ const request: any = {}+ const delay = opens++ === 0 ? 30 : 0+ setTimeout(() => {+ request.result = {+ close() {},+ transaction(_name: string, _mode?: string) {+ const transaction: any = { objectStore() { return {+ put(value: unknown, key: string) {+ setTimeout(() => {+ if (failNextWrite) {+ failNextWrite = false+ transaction.error = new Error('Disk full')+ transaction.onerror()+ } else {+ values.set(key, value)+ transaction.oncomplete()+ }+ }, 0)+ },+ get(key: string) {+ const read: any = {}+ setTimeout(() => { read.result = values.get(key); read.onsuccess() }, 0)+ return read+ },+ } } }+ return transaction+ },+ }+ request.onsuccess()+ }, delay)+ return request+ } } as unknown as IDBFactory+ try {+ const first = { 'bot:b': { dataUrl: 'first', tinted: false } }+ const a = saveIconCache('alice/computer', first)+ first['bot:b'].dataUrl = 'mutated after enqueue'+ const b = saveIconCache('alice/computer', { 'bot:b': { dataUrl: 'second', tinted: true } })+ const other = saveIconCache('bob/computer', { 'bot:b': { dataUrl: 'other account', tinted: false } })+ await Promise.all([a, b, other])+ assert.equal((await loadIconCache('alice/computer'))['bot:b']?.dataUrl, 'second')+ assert.equal((await loadIconCache('bob/computer'))['bot:b']?.dataUrl, 'other account')+ failNextWrite = true+ const failed = saveIconCache('alice/computer', first)+ const removed = saveIconCache('alice/computer', {})+ await assert.rejects(failed, /Disk full/)+ await removed+ assert.deepEqual(await loadIconCache('alice/computer'), {})+ } finally { globalThis.indexedDB = original }+})diff --git a/apps/desktop/src/renderer/lib/icon-cache.ts b/apps/desktop/src/renderer/lib/icon-cache.tsnew file mode 100644index 00000000..e89ed0aa--- /dev/null+++ b/apps/desktop/src/renderer/lib/icon-cache.ts@@ -0,0 +1,48 @@+import type { CustomIcons } from '@shared/custom-icons'++/** Images stay out of localStorage's small quota and the transcript cache. One entry per computer/account. */+async function database(): Promise<IDBDatabase> {+ return new Promise((resolve, reject) => {+ const request = indexedDB.open('codync-icons-v1', 1)+ request.onupgradeneeded = () => request.result.createObjectStore('icons')+ request.onsuccess = () => resolve(request.result)+ request.onerror = () => reject(request.error)+ })+}++export async function loadIconCache(key: string): Promise<CustomIcons> {+ const db = await database()+ try {+ return await new Promise((resolve, reject) => {+ const request = db.transaction('icons').objectStore('icons').get(key)+ request.onsuccess = () => resolve((request.result as CustomIcons | undefined) ?? {})+ request.onerror = () => reject(request.error)+ })+ } finally { db.close() }+}++async function writeIconCache(key: string, icons: CustomIcons): Promise<void> {+ const db = await database()+ try {+ await new Promise<void>((resolve, reject) => {+ const transaction = db.transaction('icons', 'readwrite')+ transaction.objectStore('icons').put(icons, key)+ transaction.oncomplete = () => resolve()+ transaction.onerror = () => reject(transaction.error)+ transaction.onabort = () => reject(transaction.error ?? new Error('Icon cache write was cancelled'))+ })+ } finally { db.close() }+}++// Preserve replacement/removal order even when opening IndexedDB finishes out of order.+const pending = new Map<string, Promise<void>>()++export function saveIconCache(key: string, icons: CustomIcons): Promise<void> {+ const snapshot = structuredClone(icons)+ const previous = pending.get(key) ?? Promise.resolve()+ const next = previous.catch(() => {}).then(() => writeIconCache(key, snapshot))+ pending.set(key, next)+ const cleanup = () => { if (pending.get(key) === next) pending.delete(key) }+ void next.then(cleanup, cleanup)+ return next+}diff --git a/apps/desktop/src/renderer/store/bot-mirror.ts b/apps/desktop/src/renderer/store/bot-mirror.tsindex c1e1203e..147d8281 100644--- a/apps/desktop/src/renderer/store/bot-mirror.ts+++ b/apps/desktop/src/renderer/store/bot-mirror.ts@@ -17,6 +17,7 @@ import { Observable } from '../lib/observable'import { hostHasSections } from '../lib/roster-sections'import { ComposerDrafts } from '@shared/composer-drafts'import { canLoadHistory } from '@shared/mirror-window'+import { loadIconCache, saveIconCache } from '../lib/icon-cache'/** The first host where the user picks the lead and may delete it. */const LEAD_CHOICE_HOST = '2.33.0'@@ -34,6 +35,25 @@ export type Connection =* read, entry merging and the on-device cache.*/export class BotMirror extends Observable {+ icons: import('@shared/custom-icons').CustomIcons = {}+ private iconsReceived = false+ protected iconsRevision = -1+ iconsEpoch = 0++ applyIcons(icons: import('@shared/custom-icons').CustomIcons, revision = 0) {+ if (revision < this.iconsRevision) return+ this.iconsRevision = revision+ this.iconsReceived = true+ void saveIconCache(this.cacheKey, icons).catch((error: unknown) => console.warn('Could not cache custom icons', error))+ this.restoreIcons(icons)+ }++ private restoreIcons(icons: import('@shared/custom-icons').CustomIcons) {+ this.icons = icons+ for (const [id, bot] of this.bots) this.bots.set(id, { ...bot, customIcon: icons[`bot:${id}`] })+ this.onRosterChanged?.()+ this.changed()+ }computer: Computerconnection: Connection = { kind: 'connecting' }hostRoute: HostRoute | null = null@@ -254,6 +274,9 @@ export class BotMirror extends Observable {}private loadCache() {+ void loadIconCache(this.cacheKey).then((icons) => {+ if (!this.retired && !this.iconsReceived) this.restoreIcons(icons)+ }).catch((error: unknown) => console.warn('Could not read cached icons', error))try {const raw = localStorage.getItem(this.cacheKey)if (!raw) return@@ -282,7 +305,8 @@ export class BotMirror extends Observable {kept.push(...list.filter((e) => !e.id.startsWith('local-')).slice(-200))kept.push(...list.filter((e) => e.id.startsWith('local-') && e.data.status === 'failed'))}- const cache = { stamp: `${this.appVersion}/${this.hello?.version ?? ''}`, hostId: this.hostId, rev: this.rev, bots: [...this.bots.values()], entries: kept }+ const bots = [...this.bots.values()].map(({ customIcon: _image, ...bot }) => bot)+ const cache = { stamp: `${this.appVersion}/${this.hello?.version ?? ''}`, hostId: this.hostId, rev: this.rev, bots, entries: kept }try {localStorage.setItem(this.cacheKey, JSON.stringify(cache))} catch {}diff --git a/apps/desktop/src/renderer/store/bot-store.ts b/apps/desktop/src/renderer/store/bot-store.tsindex 5a8a931f..dccd132d 100644--- a/apps/desktop/src/renderer/store/bot-store.ts+++ b/apps/desktop/src/renderer/store/bot-store.ts@@ -418,6 +418,10 @@ export class BotStore extends BotSync {} catch {}}+ async selectWorkspace(path: string) {+ return (await this.ready()).call<{ path: string }>('selectWorkspace', { path })+ }+async listDirs(path: string | null) {return (await this.ready()).call<DirListing>('listDirs', { path })}diff --git a/apps/desktop/src/renderer/store/bot-sync.ts b/apps/desktop/src/renderer/store/bot-sync.tsindex 25f0c81f..fbdf2ad0 100644--- a/apps/desktop/src/renderer/store/bot-sync.ts+++ b/apps/desktop/src/renderer/store/bot-sync.ts@@ -139,7 +139,7 @@ export class BotSync extends BotMirror {const attempt = async () => {if (!alive()) returntry {- await this.refreshHello(client)+ await this.refreshHello(client, loop)if (!alive()) returnif (this.mismatch) {this.finishRefresh?.()@@ -195,10 +195,13 @@ export class BotSync extends BotMirror {this.runEvents(this.client)}- private async refreshHello(client: HostClient) {+ private async refreshHello(client: HostClient, loop: number) {+ const epoch = ++this.iconsEpochconst h = await client.hello()- if (this.retired) return+ if (this.retired || loop !== this.eventsLoop || epoch !== this.iconsEpoch) return+ this.iconsRevision = -1this.hello = h+ this.applyIcons(h.icons ?? {}, h.iconsRevision)this.noteHostVersion({ version: h.version, minApp: h.minApp })if (this.isLoopback) this.updateComputer((c) => ({ ...c, name: h.name, device: h.device ?? c.device }))this.changed()@@ -219,9 +222,13 @@ export class BotSync extends BotMirror {private apply(event: HostEvent) {switch (event.type) {+ case 'icons':+ this.applyIcons(event.icons, event.iconsRevision)+ breakcase 'hello':if (this.hostId && this.hostId !== event.hostId) this.resetMirror()this.hostId = event.hostId+ if (event.icons) this.applyIcons(event.icons)this.usage = event.usagethis.screen = event.screenthis.network = event.network@@ -229,7 +236,7 @@ export class BotSync extends BotMirror {this.floors = snapshotFloors(this.entries, this.rev === 0 ? 0 : this.requestedSince)breakcase 'bot':- this.bots.set(event.bot.id, event.bot)+ this.bots.set(event.bot.id, { ...event.bot, customIcon: this.icons[`bot:${event.bot.id}`] })this.bump(event.bot.rev)this.onRosterChanged?.()if (event.bot.unread > 0) this.acknowledgeVisible(event.bot.id)@@ -295,6 +302,8 @@ export class BotSync extends BotMirror {}private resetMirror() {+ this.iconsRevision = -1+ this.applyIcons({})this.composerDrafts.clear()this.bots = new Map()this.entries = keptEntries(this.entries, (e) => e.id.startsWith('local-'))diff --git a/apps/desktop/src/renderer/store/icon-editor.ts b/apps/desktop/src/renderer/store/icon-editor.tsnew file mode 100644index 00000000..bf066b62--- /dev/null+++ b/apps/desktop/src/renderer/store/icon-editor.ts@@ -0,0 +1,41 @@+import { account } from './account'+import type { CustomIcons } from '@shared/custom-icons'+import { Observable } from '../lib/observable'+import type { BotStore } from './bot-store'++export class IconEditor extends Observable {+ busy = false+ error: string | null = null++ constructor(private store: BotStore, readonly target: string) { super() }++ async save(change: { file?: File; url?: string; tinted?: boolean; remove?: boolean }) {+ if (this.busy) return+ this.busy = true+ this.error = null+ this.changed()+ try {+ if ((change.file || change.url) && !account.isSignedIn) throw new Error('Sign in to use custom images.')+ const epoch = this.store.iconsEpoch+ const client = this.store.client+ if (!client || this.store.connection.kind !== 'online') throw new Error('Connect to your computer to change its icons.')+ const { file, ...body } = change+ const data = file ? await readImage(file) : undefined+ const result = await client.call<{ icons: CustomIcons; iconsRevision: number }>('setIcon', { target: this.target, ...body, data }, 60_000)+ if (epoch === this.store.iconsEpoch) this.store.applyIcons(result.icons, result.iconsRevision)+ } catch (e) {+ this.error = e instanceof Error ? e.message : String(e)+ } finally {+ this.busy = false+ this.changed()+ }+ }+}++async function readImage(file: File): Promise<string> {+ if (!file.size || file.size > 5 * 1024 * 1024) throw new Error('Choose an image up to 5 MiB.')+ const bytes = new Uint8Array(await file.arrayBuffer())+ let binary = ''+ for (let at = 0; at < bytes.length; at += 8192) binary += String.fromCharCode(...bytes.subarray(at, at + 8192))+ return btoa(binary)+}diff --git a/apps/desktop/src/renderer/store/use-folder-picker.ts b/apps/desktop/src/renderer/store/use-folder-picker.tsnew file mode 100644index 00000000..b9f21d30--- /dev/null+++ b/apps/desktop/src/renderer/store/use-folder-picker.ts@@ -0,0 +1,66 @@+import { useEffect, useRef, useState } from 'react'+import type { DirListing } from '@shared/models'+import { useStore } from './context'++/** Keeps asynchronous browsing and confirmation out of the renderer. */+export function useFolderPicker(onPick: (path: string) => void) {+ const store = useStore()+ const [requestId, setRequestId] = useState(0)+ const [mode, setMode] = useState<'recent' | 'browse'>('recent')+ const [listing, setListing] = useState<DirListing | null>(null)+ const [path, setPath] = useState<string | null>(null)+ const [selected, setSelected] = useState('')+ const [filter, setFilter] = useState('')+ const [error, setError] = useState<string | null>(null)+ const [busy, setBusy] = useState(false)+ const [saving, setSaving] = useState(false)+ const [pathOpen, setPathOpen] = useState(false)+ const [input, setInput] = useState('')+ const generation = useRef(0)+ const online = store.connection.kind === 'online'+ useEffect(() => {+ const request = ++generation.current+ setBusy(true)+ setError(null)+ setListing(null)+ store.listDirs(path).then(result => {+ if (generation.current !== request) return+ setListing(result)+ if (mode === 'browse') setSelected(result.path)+ }).catch(e => { if (generation.current === request) setError(errorText(e)) })+ .finally(() => { if (generation.current === request) setBusy(false) })+ return () => { generation.current++ }+ }, [store, path, mode, online, requestId])+ const open = (next: string | null) => {+ setSelected('')+ setFilter('')+ setPath(next)+ setMode('browse')+ setPathOpen(false)+ setRequestId(id => id + 1)+ }+ const showRecent = () => {+ setMode('recent')+ setPath(null)+ setFilter('')+ setSelected('')+ setPathOpen(false)+ setRequestId(id => id + 1)+ }+ const confirm = async () => {+ if (!selected || saving || !online || busy) return+ const request = generation.current+ setSaving(true)+ setError(null)+ try {+ // Absence of `recent` means an older host: validate with its existing browsing API.+ const result = listing?.recent ? await store.selectWorkspace(selected) : await store.listDirs(selected)+ if (request === generation.current) onPick(result.path)+ } catch (e) { if (request === generation.current) setError(errorText(e)) }+ finally { setSaving(false) }+ }+ return { store, mode, showRecent, listing, selected, setSelected, filter, setFilter,+ error, busy, saving, pathOpen, setPathOpen, input, setInput, online, open, confirm }+}++function errorText(error: unknown) { return error instanceof Error ? error.message : String(error) }diff --git a/apps/desktop/src/renderer/views/ComputerFilterHeader.tsx b/apps/desktop/src/renderer/views/ComputerFilterHeader.tsxindex 16fdcab8..15866c2c 100644--- a/apps/desktop/src/renderer/views/ComputerFilterHeader.tsx+++ b/apps/desktop/src/renderer/views/ComputerFilterHeader.tsx@@ -1,10 +1,9 @@-import type { Computer } from '@shared/models'import { sshSummary, sshStatusDetail } from '@shared/ssh-startup'import { DropdownMenu } from '../components/Controls'+import { ComputerBadge } from './ComputerBadge'import { Icon } from '../components/Icon'import type { MenuItem } from '../components/Overlay'import { Text } from '../components/Text'-import { useTr } from '../lib/use-language'import { useApp } from '../store/context'import { useSSH } from './settings/ssh-model'import type { Connection } from '../store/bot-store'@@ -45,7 +44,6 @@ function summary(connections: Connection[]) {/** The roster's connection summary, with details and filters on demand. */export function ComputerFilterHeader({ hidden, setHidden, manage, compact = false }: { hidden: string; setHidden: (v: string) => void; manage: () => void; compact?: boolean }) {const app = useApp()- const tr = useTr()const ssh = useSSH()const pending = ssh.state.profiles.filter((p) => !ssh.state.attachments.some((a) => a.profileId === p.id))const pendingSummary = sshSummary(pending.map((p) => ssh.status(p.id)))@@ -53,19 +51,20 @@ export function ComputerFilterHeader({ hidden, setHidden, manage, compact = falsconst stores = selection.shown.map((id) => app.store(id)).filter((s) => !!s)const online = stores.filter((s) => s.shownConnection.kind === 'online').lengthconst text = pendingSummary ? `${online ? `${online} connected · ` : ''}${pendingSummary}` : summary(stores.map((s) => s.shownConnection))- const title = (c: Computer) => {- const store = app.store(c.id)- return store ? `${store.hostName} · ${tr(store.connectionLabel)}` : c.name- }const items = (): MenuItem[] => {- const list: MenuItem[] = [{ title: 'All computers', selected: selection.shown.length === app.computers.length, action: () => setHidden('') }]- for (const c of app.computers) list.push({ title: title(c), selected: selection.shown.includes(c.id), action: () => setHidden(selection.toggling(c.id)) })+ const list: MenuItem[] = [{ title: 'All computers', icon: 'desktopcomputer', selected: selection.shown.length === app.computers.length, action: () => setHidden('') }]+ for (const c of app.computers) {+ const store = app.store(c.id)+ list.push({ title: store?.hostName ?? c.name, verbatim: true, detail: store?.connectionLabel,+ leading: <ComputerBadge computer={c} size={26} />, selected: selection.shown.includes(c.id),+ action: () => setHidden(selection.toggling(c.id)) })+ }for (const p of pending) {const status = ssh.status(p.id)const detail = sshStatusDetail(status, false)- list.push({ title: `${p.name || p.host} · ${detail}`, action: manage })+ list.push({ title: p.name || p.host, verbatim: true, detail, icon: 'network', action: manage })}- if (app.computers.length > 1) app.computers.forEach((c, i) => list.push({ title: `Only ${c.name}`, divider: i === 0, action: () => setHidden(selection.only(c.id)) }))+ if (app.computers.length > 1) app.computers.forEach((c, i) => list.push({ title: `Only ${c.name}`, leading: <ComputerBadge computer={c} size={26} />, divider: i === 0, action: () => setHidden(selection.only(c.id)) }))if (stores.length) list.push({ title: 'Reconnect', icon: 'arrow.clockwise', divider: true, action: () => stores.forEach((s) => s.restartStream()) })if (app.host.state.kind === 'notInstalled') list.push({ title: `Install host on this ${window.codync.platform === 'darwin' ? 'Mac' : 'computer'}`, icon: 'desktopcomputer', action: () => window.codync.host.install() })if (app.host.state.kind === 'failed') list.push({ title: 'Try again on this computer', icon: 'arrow.clockwise', action: () => window.codync.host.restart() })diff --git a/apps/desktop/src/renderer/views/PanelMenus.tsx b/apps/desktop/src/renderer/views/PanelMenus.tsxindex c1bacbd0..974753c7 100644--- a/apps/desktop/src/renderer/views/PanelMenus.tsx+++ b/apps/desktop/src/renderer/views/PanelMenus.tsx@@ -2,7 +2,7 @@ import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'reimport { Spinner } from '../components/Controls'import { Icon } from '../components/Icon'import type { MenuItem } from '../components/Overlay'-import { HStack, IconSlot, VStack } from '../components/Stack'+import { IconSlot, VStack } from '../components/Stack'import { Text } from '../components/Text'import type { Link } from '@shared/analytics'import { account, useAccount } from '../store/account'@@ -15,19 +15,14 @@ import { useTr } from '../lib/use-language'// right-click actions, both built on the same keyboard-driven rows.export function ProfileAvatar() {- const { user, isBusy } = useAccount()+ const { user, isBusy, isReady } = useAccount()return (<span className="profile-avatar" aria-hidden>- {user?.avatarURL ? (+ {isBusy || !isReady ? <Spinner size={14} /> : user?.avatarURL ? (<img src={user.avatarURL} alt="" className="profile-avatar-image" />) : (<Icon name="person.fill" size={15} weight="medium" color="var(--secondary)" />)}- {isBusy ? (- <HStack as="span" justify="center" className="profile-avatar-busy">- <Spinner size={14} />- </HStack>- ) : null}</span>)}diff --git a/apps/desktop/src/renderer/views/bots/BotEditorView.tsx b/apps/desktop/src/renderer/views/bots/BotEditorView.tsxindex 15ffb8e7..1d6187d5 100644--- a/apps/desktop/src/renderer/views/bots/BotEditorView.tsx+++ b/apps/desktop/src/renderer/views/bots/BotEditorView.tsx@@ -1,13 +1,13 @@import { useCallback, useEffect, useRef, useState } from 'react'import { fastModeRefusal, fastModeShown } from '@shared/fast-mode'import { restLine, restOf, withBackend } from '@shared/fallbacks'-import { draftOf, type Bot, type BotDraft, type DirListing } from '@shared/models'+import { draftOf, type Bot, type BotDraft } from '@shared/models'import { AgentIcon } from '../../components/AgentIcon'import { CharacterAvatar } from '../../components/Avatar'-import { CardSection, ChoicePicker, DropdownMenu, IconButton, Pill, SearchField, Spinner, ValueRow } from '../../components/Controls'+import { CardSection, ChoicePicker, DropdownMenu, IconButton, Pill, Spinner, ValueRow } from '../../components/Controls'import { Icon } from '../../components/Icon'import { ModalHeader, Sheet, SheetPage, useDismiss } from '../../components/Overlay'-import { HStack, IconSlot } from '../../components/Stack'+import { HStack } from '../../components/Stack'import { Text } from '../../components/Text'import { useStore } from '../../store/context'import { useAgentModels } from './agent-models'@@ -18,8 +18,10 @@ import { FormSheet } from '../marketplace/pieces'import { SkillSheet, type SkillRef } from '../marketplace/SkillSheet'import { AnchoredPanel, AutoTextArea, AvatarPicker, Field, SwitchRow } from './parts'import { NetworkSwitches } from './NetworkSwitches'+import { FolderPicker } from './FolderPicker'import './bots.css'import { useTr } from '../../lib/use-language'+import { CustomIconEditor } from './CustomIconEditor'/** Edit a bot in a modal: the settings form plus Close / Save. New bots start in `NewBotView`. */@@ -187,11 +189,12 @@ function BotSettingsForm({ draft, onChange, error, plugins, part = 'all' }: {<CardSection title="Profile"><ValueRow label="Avatar"><button ref={avatarRef} className="avatar-button small" title="Edit Bot avatar" aria-label="Edit Bot avatar" onClick={() => setPickingAvatar((p) => !p)}>- <CharacterAvatar shape={draft.avatarShape} color={draft.avatarColor} size={24} />+ <CharacterAvatar shape={draft.avatarShape} color={draft.avatarColor} size={24} customIcon={draft.id ? store.icons[`bot:${draft.id}`] : undefined} /></button><AnchoredPanel open={pickingAvatar} onClose={() => setPickingAvatar(false)} anchor={avatarRef}><div className="avatar-picker-panel"><AvatarPicker shape={draft.avatarShape} color={draft.avatarColor} onShape={(s) => set('avatarShape', s)} onColor={(c) => set('avatarColor', c)} />+ {draft.id && <CustomIconEditor target={`bot:${draft.id}`} />}</div></AnchoredPanel></ValueRow>@@ -348,117 +351,3 @@ function PluginToggles({ title, empty, items, selection, onChange, onInfo }: {</CardSection>)}--/** Browses folders on the host, drilling down in place. */-function FolderPicker({ start, onPick }: { start: string | null; onPick: (path: string) => void }) {- // The folders opened so far; the last one is shown.- const [stack, setStack] = useState<(string | null)[]>([start])- const [forward, setForward] = useState(true)- const current = stack[stack.length - 1] ?? null- // Where the first folder sits, so Back can climb above the starting folder ('' lists the drives).- const [parent, setParent] = useState<string | null>(null)- return (- <SheetPage>- <HStack>- {stack.length > 1 || parent !== null ? (- <HStack align="stretch" className="fade-in folder-back">- <IconButton- title="Back"- icon="chevron.left"- onClick={() => {- setForward(false)- setStack((s) => (s.length > 1 ? s.slice(0, -1) : [parent]))- }}- />- </HStack>- ) : null}- <div className="folder-title">- <ModalHeader title={current ? lastPathComponent(current) : 'Folders'} />- </div>- </HStack>- <div className="folder-levels">- <FolderLevel- key={`${stack.length}:${current}`}- path={current}- forward={forward}- onPick={onPick}- onParent={stack.length > 1 ? undefined : setParent}- onOpen={(path) => {- setForward(true)- setStack((s) => [...s, path])- }}- />- </div>- </SheetPage>- )-}--/** One folder's subfolders. */-function FolderLevel({ path, forward, onPick, onOpen, onParent }: {- path: string | null- forward: boolean- onPick: (path: string) => void- onOpen: (path: string) => void- onParent?: (parent: string | null) => void-}) {- const store = useStore()- const [listing, setListing] = useState<DirListing | null>(null)- const [error, setError] = useState<string | null>(null)- const [filter, setFilter] = useState('')-- useEffect(() => {- let live = true- store- .listDirs(path)- .then((l) => {- if (!live) return- setListing(l)- onParent?.(l.parent ?? null)- })- .catch((e: unknown) => live && setError(errorText(e)))- return () => {- live = false- }- }, [store, path, onParent])-- const dirs = listing?.dirs.filter((d) => !filter || d.name.toLowerCase().includes(filter.toLowerCase())) ?? []-- return (- <div className={`bot-form level-slide ${forward ? 'from-trailing' : 'from-leading'}`}>- <div className="bot-form-content folder-level-content">- <SearchField value={filter} onChange={setFilter} />- {listing ? (- <>- {listing.path ? (- <CardSection footer={listing.path}>- <button className="press folder-use" onClick={() => onPick(listing.path)}>- <Icon name="checkmark.circle.fill" size={13} />- <Text truncate>{`Use “${lastPathComponent(listing.path)}”`}</Text>- </button>- </CardSection>- ) : null}- {dirs.length ? (- <CardSection>- {dirs.map((dir) => (- <button key={dir.path} className="press folder-row" onClick={() => onOpen(dir.path)}>- <IconSlot width={20}>- <Icon name={dir.isGit ? 'arrow.triangle.branch' : 'folder'} size={12} color={dir.isGit ? 'var(--accent)' : 'var(--secondary)'} />- </IconSlot>- <Text tone="text" truncate grow>{dir.name}</Text>- <Icon name="chevron.right" size={10} weight="semibold" color="var(--tertiary)" />- </button>- ))}- </CardSection>- ) : null}- </>- ) : error ? (- <Text tone="danger">{error}</Text>- ) : (- <HStack align="stretch" justify="center">- <Spinner size={20} />- </HStack>- )}- </div>- </div>- )-}diff --git a/apps/desktop/src/renderer/views/bots/CustomIconEditor.tsx b/apps/desktop/src/renderer/views/bots/CustomIconEditor.tsxnew file mode 100644index 00000000..281adf3f--- /dev/null+++ b/apps/desktop/src/renderer/views/bots/CustomIconEditor.tsx@@ -0,0 +1,69 @@+import { useId, useMemo, useRef, useState } from 'react'+import { Button, IconButton, Spinner } from '../../components/Controls'+import { CustomIcon } from '../../components/CustomIcon'+import { HStack, VStack } from '../../components/Stack'+import { Text } from '../../components/Text'+import { useModel } from '../../lib/observable'+import { useStore } from '../../store/context'+import { IconEditor } from '../../store/icon-editor'+import { account, useAccount } from '../../store/account'+import { Dialog, usePresence } from '../../components/Overlay'+import { useTr } from '../../lib/use-language'+import './custom-icon-editor.css'+import { SwitchRow } from './parts'++/** Changes are saved immediately, independently of the bot's text settings. */+export function CustomIconEditor({ target }: { target: string }) {+ const store = useStore()+ const editor = useModel(useMemo(() => new IconEditor(store, target), [store, target]))+ const session = useAccount()+ const [needsSignIn, setNeedsSignIn] = useState(false)+ const requireAccount = (action: () => void) => { if (session.isSignedIn) action(); else setNeedsSignIn(true) }+ const [url, setURL] = useState('')+ const [showURL, setShowURL] = useState(false)+ const reveal = usePresence(showURL)+ const urlId = useId()+ const tr = useTr()+ const input = useRef<HTMLInputElement>(null)+ const icon = store.icons[target]+ const disabled = editor.busy || session.isBusy || !session.isReady || store.connection.kind !== 'online'+ if (!store.hello?.icons) return null+ return <VStack gap={10} className="custom-icon-editor">+ <Text size="subheadline" weight="semibold">Custom icon</Text>+ <HStack gap={8} wrap justify="center">+ <CustomIcon icon={icon} size={40} fallback={null} />+ <Button kind="secondary" disabled={disabled} onClick={() => requireAccount(() => input.current?.click())}>Upload from desktop</Button>+ <Button kind="secondary" disabled={disabled} onClick={() => requireAccount(() => setShowURL((shown) => !shown))}>Paste URL</Button>+ {icon && <Button disabled={disabled} onClick={() => void editor.save({ remove: true })}>Use default</Button>}+ {editor.busy && <Spinner />}+ </HStack>+ <input ref={input} type="file" hidden accept="image/png,image/jpeg,image/webp,image/svg+xml"+ onChange={(event) => {+ const file = event.currentTarget.files?.[0]+ event.currentTarget.value = ''+ if (file) requireAccount(() => { void editor.save({ file }) })+ }} />+ {reveal.mounted && <div className={`custom-icon-url ${reveal.shown ? 'shown' : ''}`}+ onKeyDown={(event) => { if (event.key === 'Enter' && event.target instanceof HTMLInputElement && !event.nativeEvent.isComposing) { event.preventDefault(); if (!disabled && url.trim()) void editor.save({ url: url.trim() }) } }}>+ <label htmlFor={urlId}>{tr('Image URL')}</label>+ <HStack gap={8}>+ <input id={urlId} className="field-box" type="url" placeholder="https://…" value={url} disabled={disabled}+ autoFocus onChange={(event) => setURL(event.target.value)} />+ <IconButton title="Use URL" icon="arrow.up" size={36} disabled={disabled || !url.trim()}+ onClick={() => void editor.save({ url: url.trim() })} />+ </HStack>+ </div>}+ {icon && <SwitchRow title="Tint icon" detail="Turn off to keep the image's original colors." on={icon.tinted}+ onChange={(tinted) => { if (!disabled) void editor.save({ tinted }) }} />}+ <VStack gap={2} className="custom-icon-help">+ <Text size="caption" tone="secondary">PNG, JPEG, WebP up to 5 MiB; SVG up to 256 KiB.</Text>+ <Text size="caption" tone="secondary">Saved immediately. Custom images stay still.</Text>+ </VStack>+ <Dialog open={needsSignIn} title="Sign in required" message="Sign in to use custom images."+ onClose={() => setNeedsSignIn(false)} actions={[+ { title: 'Continue with Apple', action: () => { setNeedsSignIn(false); void account.signIn('apple') } },+ { title: 'Continue with Google', action: () => { setNeedsSignIn(false); void account.signIn('google') } },+ ]} />+ {(editor.error || session.errorMessage) && <Text size="caption" tone="danger">{editor.error || session.errorMessage}</Text>}+ </VStack>+}diff --git a/apps/desktop/src/renderer/views/bots/FolderPicker.tsx b/apps/desktop/src/renderer/views/bots/FolderPicker.tsxnew file mode 100644index 00000000..c7693875--- /dev/null+++ b/apps/desktop/src/renderer/views/bots/FolderPicker.tsx@@ -0,0 +1,57 @@+import { Button, IconButton, SearchField, Spinner } from '../../components/Controls'+import { Icon } from '../../components/Icon'+import { ModalHeader, SheetPage, usePresence } from '../../components/Overlay'+import { Text } from '../../components/Text'+import { useFolderPicker } from '../../store/use-folder-picker'+import { useTr } from '../../lib/use-language'+import { lastPathComponent } from './drafts'+import './folder-picker.css'++/** The computer is fixed by the bot being edited; never select a path on another host. */+export function FolderPicker({ start, onPick }: { start: string | null; onPick: (path: string) => void }) {+ const tr = useTr()+ const { store, mode, showRecent, listing, selected, setSelected, filter, setFilter,+ error, busy, saving, pathOpen, setPathOpen, input, setInput, online, open, confirm } = useFolderPicker(onPick)+ const presence = usePresence(pathOpen, 180)+ const recent = listing?.recent?.filter(item => `${item.path}`.toLocaleLowerCase().includes(filter.toLocaleLowerCase())) ?? []+ const dirs = listing?.dirs.filter(item => item.name.toLocaleLowerCase().includes(filter.toLocaleLowerCase())) ?? []+ const noRecent = mode === 'recent' && !busy && !listing?.recent?.length+ const browse = <button className="workspace-row workspace-browse" disabled={saving} onClick={() => open(start)}><Icon name="folder" size={16} /><Text grow>{tr('Browse other folders')}</Text><Icon name="chevron.right" size={10} /></button>+ return <SheetPage>+ <ModalHeader title="Choose workspace" />+ <div className="workspace-picker">+ <Text tone="secondary">{tr('Your bot will work in this folder.')}</Text>+ <div className="workspace-computer"><Icon name="desktopcomputer" size={16} /><Text truncate>{store.hello?.name ?? tr('Computer')}</Text><Text tone="secondary">{tr(online ? 'Connected' : 'Disconnected')}</Text></div>+ {noRecent && browse}+ {mode === 'browse' && <div className="workspace-navigation">+ <IconButton title="Recent workspaces" icon="chevron.left" disabled={saving} onClick={showRecent} />+ <nav className="workspace-location" aria-label={tr('Folder path')}>{listing?.ancestors?.length ? listing.ancestors.map(ancestor => <button key={ancestor.path} disabled={saving || busy} onClick={() => open(ancestor.path)}>{ancestor.name}</button>) : <Text tone="secondary" truncate>{listing?.path || tr('Folders')}</Text>}</nav>+ <IconButton title="Parent folder" icon="arrow.up" disabled={busy || saving || listing?.parent == null} onClick={() => open(listing?.parent ?? null)} />+ <IconButton title="Enter folder path" icon="pencil" disabled={saving} onClick={() => { setInput(listing?.path ?? ''); setPathOpen(!pathOpen) }} />+ </div>}+ {presence.mounted && <form className={`workspace-path ${presence.shown ? 'shown' : ''}`} onSubmit={e => { e.preventDefault(); if (input.trim() && !saving) open(input.trim()) }}>+ <input aria-label={tr('Folder path')} placeholder={tr('Paste an absolute path')} value={input} onChange={e => setInput(e.target.value)} autoFocus />+ <IconButton title="Go to folder" icon="arrow.right" disabled={!input.trim() || saving} onClick={() => open(input.trim())} />+ </form>}+ {!noRecent && <>+ <SearchField value={filter} onChange={setFilter} prompt={mode === 'recent' ? 'Search recent workspaces' : 'Filter this folder'} />+ <Text tone="secondary" className="workspace-section-title">{tr(mode === 'recent' ? 'Recent workspaces' : 'Folders')}</Text>+ <div className="workspace-list" key={mode}>+ {busy ? <div className="workspace-empty"><Spinner /></div> : mode === 'recent' ? <>+ {recent.map(item => <button key={item.path} disabled={saving} className={`workspace-row ${selected === item.path ? 'selected' : ''}`} aria-pressed={selected === item.path} onClick={() => setSelected(item.path)}>+ <Icon name="folder" size={18} /><div className="workspace-row-label"><Text truncate>{lastPathComponent(item.path)}</Text><Text tone="secondary" truncate className="workspace-row-path">{item.path}</Text></div>+ {selected === item.path && <Icon name="checkmark" size={14} />}+ </button>)}+ {!recent.length && <Text tone="secondary" className="workspace-empty">{tr(filter ? 'No matching folders.' : 'Choose a folder to see it here next time.')}</Text>}+ </> : <>+ {dirs.map(dir => <button key={dir.path} disabled={saving} className="workspace-row directory" onClick={() => open(dir.path)}><Icon name={dir.isGit ? 'arrow.triangle.branch' : 'folder'} size={16} /><Text truncate grow>{dir.name}</Text><Icon name="chevron.right" size={10} /></button>)}+ {listing && !dirs.length && <Text tone="secondary" className="workspace-empty">{tr(filter ? 'No matching folders.' : 'No subfolders. You can use this folder.')}</Text>}+ </>}+ </div>+ </>}+ {error && <Text tone="danger" role="alert">{error}</Text>}+ {mode === 'recent' && !noRecent && browse}+ </div>+ <div className="workspace-footer"><div className="workspace-row-label"><Text tone="secondary" className="workspace-row-path">{tr(mode === 'recent' ? 'Selected folder' : 'Current folder')}</Text><Text truncate>{selected || tr('Choose a folder')}</Text></div><Button onClick={() => void confirm()} disabled={!selected || busy || saving || !online}>{saving ? <Spinner /> : tr('Use this folder')}</Button></div>+ </SheetPage>+}diff --git a/apps/desktop/src/renderer/views/bots/bots.css b/apps/desktop/src/renderer/views/bots/bots.cssindex 56acce2d..3f514a36 100644--- a/apps/desktop/src/renderer/views/bots/bots.css+++ b/apps/desktop/src/renderer/views/bots/bots.css@@ -71,36 +71,6 @@ textarea.field-box {border-radius: var(--radius-s);}-/* Folder picker (FolderPicker). */-.folder-back {- padding-left: 10px;-}-.folder-title {- flex: 1;- min-width: 0;-}-.folder-levels {- flex: 1;- min-height: 0;- overflow: hidden;-}-.folder-level-content {- gap: 14px;-}-.folder-use {- display: flex;- align-items: center;- gap: 8px;- font-size: var(--text-body);- font-weight: 700;- color: var(--accent);-}-.folder-row {- display: flex;- align-items: center;- gap: 10px;-}-.avatar-button {padding: 12px;background: var(--bubble-agent);@@ -113,6 +83,11 @@ textarea.field-box {}.avatar-picker-panel {padding: 14px;+ width: min(380px, calc(100vw - 32px));+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 16px;}/* Five shapes and six colors to a row, like the new bot sheet. */.avatar-picker {diff --git a/apps/desktop/src/renderer/views/bots/custom-icon-editor.css b/apps/desktop/src/renderer/views/bots/custom-icon-editor.cssnew file mode 100644index 00000000..a1ed5259--- /dev/null+++ b/apps/desktop/src/renderer/views/bots/custom-icon-editor.css@@ -0,0 +1,9 @@+.custom-icon-editor { width: 100%; text-align: center; }+.custom-icon-help { text-align: center; }+.custom-icon-editor .styled-button { white-space: nowrap; }+.custom-icon-url { display: flex; flex-direction: column; gap: 6px; opacity: 0; transform: translateY(-4px); transition: opacity 160ms ease, transform 160ms ease; }+.custom-icon-url.shown { opacity: 1; transform: translateY(0); }+.custom-icon-url label { text-align: left; font-size: 13px; color: var(--secondary); }+.custom-icon-url .field-box { flex: 1; min-width: 0; width: 0; }+.custom-icon-url .icon-button { flex-shrink: 0; background: var(--bubble-user); }+@media (prefers-reduced-motion: reduce) { .custom-icon-url { transition: none; transform: none; } }diff --git a/apps/desktop/src/renderer/views/bots/folder-picker.css b/apps/desktop/src/renderer/views/bots/folder-picker.cssnew file mode 100644index 00000000..1aacd637--- /dev/null+++ b/apps/desktop/src/renderer/views/bots/folder-picker.css@@ -0,0 +1,22 @@+.workspace-picker { display: flex; flex-direction: column; gap: 14px; padding: 0 20px 18px; flex: 1; min-height: 0; overflow: auto; }+.workspace-computer { display: flex; align-items: center; gap: 10px; background: var(--surface); padding: 11px 12px; border-radius: var(--radius-s); }+.workspace-computer > :last-child { margin-left: auto; font-size: var(--text-caption); }+.workspace-navigation { display: flex; align-items: center; gap: 5px; }+.workspace-location { flex: 1; min-width: 0; display: flex; align-items: center; overflow: auto; gap: 4px; }+.workspace-location button { color: var(--secondary); white-space: nowrap; padding: 5px; font-size: var(--text-caption); }+.workspace-location button:last-child { color: var(--text); }+.workspace-location button + button::before { content: "/"; padding-right: 8px; color: var(--tertiary); }+.workspace-section-title, .workspace-row-path { font-size: var(--text-caption); }+.workspace-section-title { margin-top: 8px; }+.workspace-list { min-height: 130px; animation: fade-in 180ms ease; }+.workspace-row { width: 100%; display: flex; align-items: center; gap: 12px; padding: 12px; border-radius: var(--radius-s); text-align: left; color: var(--text); transition: background 180ms; }+.workspace-row:hover { background: var(--bubble-agent); }+.workspace-row.selected { background: var(--bubble-agent); }+.workspace-row.directory { padding-block: 10px; }+.workspace-row-label { display: flex; flex-direction: column; gap: 4px; min-width: 0; flex: 1; }+.workspace-empty { display: block; padding: 24px 12px; text-align: center; }+.workspace-footer { display: flex; align-items: center; gap: 18px; padding: 16px 20px; background: var(--surface); }+.workspace-path { display: flex; gap: 8px; opacity: 0; transform: translateY(-4px); transition: opacity 180ms, transform 180ms; }+.workspace-path.shown { opacity: 1; transform: none; }+.workspace-path input { flex: 1; min-width: 0; border: 0; padding: 10px 12px; border-radius: var(--radius-s); background: var(--bubble-agent); color: var(--text); font: inherit; }+@media (prefers-reduced-motion: reduce) { .workspace-path, .workspace-row, .workspace-list { animation: none; transition: none; } }diff --git a/apps/desktop/src/renderer/views/chat-window.css b/apps/desktop/src/renderer/views/chat-window.cssindex 6550fdd0..b506a399 100644--- a/apps/desktop/src/renderer/views/chat-window.css+++ b/apps/desktop/src/renderer/views/chat-window.css@@ -271,10 +271,6 @@ html[data-platform="darwin"] .sidebar-header {height: 100%;object-fit: cover;}-.profile-avatar-busy {- position: absolute;- inset: 0;-}.rail-actions {display: flex;diff --git a/apps/desktop/src/renderer/views/island-summary.ts b/apps/desktop/src/renderer/views/island-summary.tsindex 70355448..4a35c0a9 100644--- a/apps/desktop/src/renderer/views/island-summary.ts+++ b/apps/desktop/src/renderer/views/island-summary.ts@@ -49,6 +49,7 @@ function islandBot(store: BotStore, bot: Bot, ref: string, name: string): Islandref,name,shape: bot.avatarShape,+ customIcon: bot.customIcon,color: bot.avatarColor,status: bot.status,backend: store.backendName(bot.backend),@@ -74,7 +75,7 @@ function pendingCards({ ref, bot, store }: RosterItem): IslandPermission[] {return {ref: refKey(ref),entryId: e.id,- bot: { name: author.name, shape: author.avatarShape, color: author.avatarColor, backend: store.backendName(author.backend) },+ bot: { customIcon: author.customIcon, name: author.name, shape: author.avatarShape, color: author.avatarColor, backend: store.backendName(author.backend) },headline: permissionHeadline(e.data.toolKind),title: e.data.title ?? '',options: sortedOptions(e.data.options ?? []).map((o) => ({ id: o.optionId, label: optionLabel(o), kind: o.kind })),diff --git a/apps/desktop/src/renderer/views/island/IslandViews.tsx b/apps/desktop/src/renderer/views/island/IslandViews.tsxindex 1c950ec4..3fcf73eb 100644--- a/apps/desktop/src/renderer/views/island/IslandViews.tsx+++ b/apps/desktop/src/renderer/views/island/IslandViews.tsx@@ -32,7 +32,7 @@ export function Wings({ model, peek }: { model: IslandModel; peek: boolean }) {{model.screen.notch || peek ? null : <span className="island-wings-label">{label}</span>}<span className="island-wing-left"><span key={focus.ref} className={`island-wing-avatar ${swap}`}>- <CharacterAvatar shape={focus.shape} color={focus.color} size={peek ? 18 : 20} mood={moodOf(focus)} dark />+ <CharacterAvatar customIcon={focus.customIcon} shape={focus.shape} color={focus.color} size={peek ? 18 : 20} mood={moodOf(focus)} dark />{peek ? null : <StateBadge badge={badgeOf(focus)} small />}</span></span>@@ -42,7 +42,7 @@ export function Wings({ model, peek }: { model: IslandModel; peek: boolean }) {<span ref={cluster} className="island-cluster">{others.map((b) => (<span key={b.ref} data-flip={b.ref} className={`island-cluster-bot ${arrivals.has(b.ref) ? 'island-swap' : ''}`}>- <CharacterAvatar shape={b.shape} color={b.color} size={11} mood={moodOf(b)} dark />+ <CharacterAvatar customIcon={b.customIcon} shape={b.shape} color={b.color} size={11} mood={moodOf(b)} dark />{b.status === 'needsInput' ? <StatusDot bot={b} /> : null}</span>))}@@ -96,7 +96,7 @@ export function Overview({ model }: { model: IslandModel }) {title={b.detail}><span className="island-pill-bot">- <CharacterAvatar shape={b.shape} color={b.color} size={24} mood={moodOf(b)} dark />+ <CharacterAvatar customIcon={b.customIcon} shape={b.shape} color={b.color} size={24} mood={moodOf(b)} dark /><StatusDot bot={b} /></span><span className="truncate">{b.name}</span>@@ -196,7 +196,7 @@ export function Message({ model }: { model: IslandModel }) {<div className="island-with-minis"><div className="island-card island-message"><span key={bot.ref} className={`island-message-bot ${swap}`}>- <CharacterAvatar shape={bot.shape} color={bot.color} size={44} mood={moodOf(bot)} dark />+ <CharacterAvatar customIcon={bot.customIcon} shape={bot.shape} color={bot.color} size={44} mood={moodOf(bot)} dark /></span><div className="island-message-body"><div className="island-agent">@@ -207,7 +207,7 @@ export function Message({ model }: { model: IslandModel }) {onClick={() => model.nextMessageBot()}title="Choose a bot">- <CharacterAvatar shape={bot.shape} color={bot.color} size={18} mood={moodOf(bot)} dark />+ <CharacterAvatar customIcon={bot.customIcon} shape={bot.shape} color={bot.color} size={18} mood={moodOf(bot)} dark />{bot.name}<Icon name="chevron.down" size={8} weight="bold" scaled={false} /></button>diff --git a/apps/desktop/src/renderer/views/island/island-parts.tsx b/apps/desktop/src/renderer/views/island/island-parts.tsxindex 78455b67..bfe240c8 100644--- a/apps/desktop/src/renderer/views/island/island-parts.tsx+++ b/apps/desktop/src/renderer/views/island/island-parts.tsx@@ -39,7 +39,7 @@ function glowOf(badge: Badge, color: string) {/** The bot in the big slot: its character, a glow in its state's color and a badge. */export function BigCharacter({ bot, size, mood, badge, onOpen }: {- bot: Pick<IslandBot, 'shape' | 'color'>+ bot: Pick<IslandBot, 'shape' | 'color' | 'customIcon'>size: numbermood: Moodbadge: Badge@@ -49,7 +49,7 @@ export function BigCharacter({ bot, size, mood, badge, onOpen }: {const inner = (<>{glow ? <span aria-hidden className="island-glow" style={{ background: `radial-gradient(circle, ${withAlpha(glow, 0.36)}, ${withAlpha(glow, 0)} 68%)` }} /> : null}- <CharacterAvatar shape={bot.shape} color={bot.color} size={size} mood={mood} dark />+ <CharacterAvatar customIcon={bot.customIcon} shape={bot.shape} color={bot.color} size={size} mood={mood} dark /><StateBadge badge={badge} /></>)@@ -112,7 +112,7 @@ export function MiniColumn({ bots, onOpen }: { bots: IslandBot[]; onOpen: (ref:<div ref={column} className="island-minis">{bots.map((b) => (<button key={b.ref} data-flip={b.ref} className={`island-mini ${arrivals.has(b.ref) ? 'island-swap' : ''}`} title={b.name} aria-label={`Open ${b.name}`} onClick={() => onOpen(b.ref)}>- <CharacterAvatar shape={b.shape} color={b.color} size={18} mood={moodOf(b)} dark />+ <CharacterAvatar customIcon={b.customIcon} shape={b.shape} color={b.color} size={18} mood={moodOf(b)} dark /><StatusDot bot={b} /></button>))}diff --git a/apps/desktop/src/renderer/views/marketplace/AgentSheet.tsx b/apps/desktop/src/renderer/views/marketplace/AgentSheet.tsxindex bf6f6923..4aee86c5 100644--- a/apps/desktop/src/renderer/views/marketplace/AgentSheet.tsx+++ b/apps/desktop/src/renderer/views/marketplace/AgentSheet.tsx@@ -13,6 +13,8 @@ import { errorText, market, type AgentAuth, type AuthMethod } from './market-modimport { ErrorText, Field, ScreenHeader, SlideStack, WebLink, filled } from './pieces'import { AgentBrings } from './AgentBrings'import { SetupTerminalView } from './SetupTerminal'+import { CustomIconEditor } from '../bots/CustomIconEditor'+import { CustomIcon, useAgentIcon } from '../../components/CustomIcon'type SetupRoute = { kind: 'install' } | { kind: 'node' } | { kind: 'terminal'; method: AuthMethod | null } | { kind: 'keys'; method: AuthMethod }@@ -44,6 +46,11 @@ export function AgentTile({ registry, icon, tile, radius }: { registry?: string/** `AgentIcon` painted with `agentTint` (which can be a gradient, so a mask over `background`). */function TintedAgentIcon({ registry, size }: { registry?: string | null; size: number }) {+ const custom = useAgentIcon(registry)+ return <CustomIcon icon={custom} size={size} color={agentTint(registry)} fallback={<BundledAgentIcon registry={registry} size={size} />} />+}++function BundledAgentIcon({ registry, size }: { registry?: string | null; size: number }) {const url = agentIconURL(registry)if (!url) return <Icon name="terminal" size={size * 0.8} scaled={false} />return (@@ -206,6 +213,7 @@ export function AgentSheet({ initial, recheck = false }: { initial: Backend; recsubtitle={backend.description || undefined}/><CardForm>+ <CardSection><CustomIconEditor target={`agent:${backend.id}`} /></CardSection>{curated ? (<CardSection><SetupStepRowdiff --git a/apps/desktop/src/renderer/views/tray-summary.ts b/apps/desktop/src/renderer/views/tray-summary.tsindex 3664dbb3..be498c86 100644--- a/apps/desktop/src/renderer/views/tray-summary.ts+++ b/apps/desktop/src/renderer/views/tray-summary.ts@@ -1,7 +1,8 @@-import { useEffect } from 'react'+import { useEffect, useState } from 'react'import { TRAY_SYMBOLS, type TrayImage, type TraySummary } from '@shared/ipc'import { isGroup, isWorking, needsInput, folderName, type Bot, type UsageWindow } from '@shared/models'import type { NetworkView } from '@shared/network'+import { iconBitmap, drawIconBitmap } from '../lib/icon-bitmap'import { drawCharacter, moodOf } from '../components/Avatar'import { fallbackPath } from '../components/icon-fallbacks'import { botsTemplate, presenceTitle, roleTitle } from '../lib/network-copy'@@ -38,15 +39,17 @@ function canvasImage(key: string, width: number, height: number, draw: (ctx: Canconst x2 = x1 && at(2)if (!x1 || !x2) return nullconst image = { x1, x2 }+ if (cache.size >= 512) cache.delete(cache.keys().next().value!)cache.set(full, image)return image}function avatarIcon(bot: Bot) {- const key = `bot|${bot.id}|${bot.avatarShape}|${bot.avatarColor}|${bot.status}|${bot.unread > 0}`+ const bitmap = iconBitmap(bot.customIcon)?.image+ const key = `bot|${bot.customIcon?.dataUrl ?? ""}|${bot.customIcon?.tinted}|${bitmap?.complete}|${bot.id}|${bot.avatarShape}|${bot.avatarColor}|${bot.status}|${bot.unread > 0}`return canvasImage(key, 20, 20, (ctx) => {const dark = isDark()- drawCharacter(ctx, { shape: bot.avatarShape, fill: avatarColor(bot.avatarColor), size: 20, mood: moodOf(bot, false), dark, t: 0, still: true })+ if (!drawIconBitmap(ctx, bot.customIcon, 20, avatarColor(bot.avatarColor))) drawCharacter(ctx, { shape: bot.avatarShape, fill: avatarColor(bot.avatarColor), size: 20, mood: moodOf(bot, false), dark, t: 0, still: true })const badge = needsInput(bot) ? palette(dark).warning : bot.unread > 0 ? (dark ? '#FFFFFF' : '#000000') : nullif (badge) {const r = needsInput(bot) ? 3.6 : 2.8@@ -139,11 +142,18 @@ function usageLine(w: UsageWindow) {/** Sends what the menu bar shows whenever the stores change. */export function useTraySummary(app: AppModel) {+ const [, redraw] = useState(0)const stores = [...app.stores.values()]useModels(stores)const [textSize] = usePref(prefs.textSize)const [iconStyle] = usePref(prefs.usageIconStyle)const [language] = usePref(prefs.appLanguage)+ useEffect(() => {+ let current = true+ const pending = app.roster.map(({ bot }) => iconBitmap(bot.customIcon)).filter((entry) => entry && !entry.image.complete)+ if (pending.length) void Promise.all(pending.map((entry) => entry!.ready)).then(() => { if (current) redraw((n) => n + 1) })+ return () => { current = false }+ })useEffect(() => {const timer = setTimeout(() => {const local = app.localdiff --git a/apps/desktop/src/shared/custom-icons.test.ts b/apps/desktop/src/shared/custom-icons.test.tsnew file mode 100644index 00000000..11b6dc73--- /dev/null+++ b/apps/desktop/src/shared/custom-icons.test.ts@@ -0,0 +1,11 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { validIcon } from './custom-icons.ts'++test('custom icons accept only bounded PNG data, never remote or active content', () => {+ assert.ok(validIcon({ dataUrl: 'data:image/png;base64,iVBORw0KGgo=', tinted: false }))+ for (const dataUrl of ['https://example.com/icon.png', 'data:image/svg+xml,<svg/>', 'data:image/png;base64,!', `data:image/png;base64,${'A'.repeat(65559)}`]) {+ assert.equal(validIcon({ dataUrl, tinted: false }), false)+ }+ assert.equal(validIcon(undefined), false)+})diff --git a/apps/desktop/src/shared/custom-icons.ts b/apps/desktop/src/shared/custom-icons.tsnew file mode 100644index 00000000..d4c753b9--- /dev/null+++ b/apps/desktop/src/shared/custom-icons.ts@@ -0,0 +1,12 @@+export interface CustomIcon {+ dataUrl: string+ tinted: boolean+}++export type CustomIcons = Record<string, CustomIcon>++/** Only host-normalized PNGs are rendered, never URLs supplied by another device. */+export function validIcon(icon: CustomIcon | undefined): icon is CustomIcon {+ return !!icon && typeof icon.dataUrl === 'string' && icon.dataUrl.length <= 65558+ && /^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/.test(icon.dataUrl)+}diff --git a/apps/desktop/src/shared/island.ts b/apps/desktop/src/shared/island.tsindex a2c82f0e..0b72b28a 100644--- a/apps/desktop/src/shared/island.ts+++ b/apps/desktop/src/shared/island.ts@@ -13,6 +13,7 @@ export interface IslandStep {/** One bot as the island shows it (`ref` = computerId/botId). */export interface IslandBot {+ customIcon?: import('./custom-icons').CustomIconref: stringname: stringshape: string@@ -43,7 +44,7 @@ export interface IslandOption {export interface IslandPermission {ref: stringentryId: string- bot: Pick<IslandBot, 'name' | 'shape' | 'color' | 'backend'>+ bot: Pick<IslandBot, 'name' | 'shape' | 'color' | 'backend' | 'customIcon'>headline: stringtitle: stringoptions: IslandOption[]diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.tsindex 02d137a1..963fc650 100644--- a/apps/desktop/src/shared/models.ts+++ b/apps/desktop/src/shared/models.ts@@ -7,6 +7,7 @@ import type { CallLine } from './calls'export type BotStatus = 'idle' | 'working' | 'needsInput' | 'error'export interface Bot {+ customIcon?: import('./custom-icons').CustomIconid: string/** `agent`, or `group`: several bots and the user in one chat. */kind: string@@ -463,6 +464,8 @@ export function normalizeScreen(raw: Partial<ScreenState> | undefined | null): S}export interface Hello {+ iconsRevision?: number+ icons?: import('./custom-icons').CustomIconshostId: stringname: stringversion: string@@ -498,7 +501,11 @@ export interface DirItem {isGit: boolean}+export interface RecentWorkspace { path: string; usedAt: number }+export interface DirListing {+ recent?: RecentWorkspace[]+ ancestors?: DirItem[]path: stringparent?: string | nullisGit: booleandiff --git a/apps/ios/App/CodyncApp.swift b/apps/ios/App/CodyncApp.swiftindex fcb656eb..39818269 100644--- a/apps/ios/App/CodyncApp.swift+++ b/apps/ios/App/CodyncApp.swift@@ -31,6 +31,11 @@ struct CodyncApp: App {.environment(app).environment(app.accounts).environment(app.account)+ .environment(\.customIconAccount, CustomIconAccount(+ signedIn: app.account.isSignedIn, loading: app.account.isBusy || !app.account.isReady,+ error: app.account.errorMessage,+ signInApple: { Task { await app.account.signIn(provider: .apple) } },+ signInGoogle: { Task { await app.account.signIn(provider: .google) } }))// A computer needs a newer app: its App Store page has the Update button..environment(\.appUpdate, AppUpdateAction {Analytics.shared.capture(.linkOpened(.appStore))diff --git a/apps/ios/App/Push.swift b/apps/ios/App/Push.swiftindex c1f6d2fc..dbc4148d 100644--- a/apps/ios/App/Push.swift+++ b/apps/ios/App/Push.swift@@ -247,6 +247,7 @@ final class LiveActivities {guard BotActivityAttributes.mayStart else { return }let attributes = BotActivityAttributes(bot: bot, computerId: ref.computerId, link: store.storage.botURL(ref))do {+ try bot.customIcon?.cacheForActivity(context: attributes.iconContext)let activity = try Activity.request(attributes: attributes, content: .init(state: state, staleDate: staleDate), pushType: .token)// Offline (mailbox): `resume(with:)` registers the push token once the computer connects.if let client = store.client { observe(activity, client: client) }@@ -315,13 +316,14 @@ final class LiveActivities {// Until the computer starts on the message, an idle bot just hasn't begun yet.let local = ["sending", "queued"].contains(current.content.state.status)guard !local || bot.isWorking else { return }- let state = CallActivity.withCall(.init(+ var state = CallActivity.withCall(.init(status: bot.status,// ACP activity is already visible in the app. Show it in the local Live Activity// while this phone is connected; APNs payloads continue to contain no free text.activity: bot.activity,startedAt: bot.startedAt.map(Date.init(milliseconds:))), botId: ref.botId)+ state.customIconRevision = (bot.customIcon?.filename ?? "default") + (bot.customIcon?.tinted == true ? ":tint" : ":color")// A call with the bot keeps its activity up after the task.let working = bot.isWorking || CallActivity.isLive(botId: ref.botId)Task.detached { await Self.apply(ref, state: state, end: !working) }diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swiftindex b0b0141e..23957146 100644--- a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift@@ -1,6 +1,7 @@import Foundationpublic enum HostEvent: Sendable {+ case icons([String: CustomIcon], revision: Int64)/// The stream's first event; `network` is nil from hosts before the network view.case hello(hostId: String, rev: Int64, usage: Usage, screen: ScreenState?, network: NetworkView?)case bot(Bot)@@ -108,6 +109,9 @@ public struct HostClient: Sendable {let d = decoderguard let env = try? d.decode(Envelope.self, from: data) else { return nil }switch env.type {+ case "icons":+ struct Icons: Decodable { var icons: [String: CustomIcon]; var iconsRevision: Int64? }+ return (try? d.decode(Icons.self, from: data)).map { .icons($0.icons, revision: $0.iconsRevision ?? 0) }case "hello":let usage = (try? d.decode(UsageWrap.self, from: data))?.usage ?? Usage()let screen = (try? d.decode(ScreenWrap.self, from: data))?.screen@@ -357,6 +361,12 @@ public extension HostClient {try await call("usage", ["refresh": refresh])}+ func selectWorkspace(_ path: String) async throws -> String {+ struct Reply: Decodable { var path: String }+ let reply: Reply = try await call("selectWorkspace", ["path": path])+ return reply.path+ }+func listDirs(_ path: String?) async throws -> DirListing {struct Body: Encodable { var path: String? }return try await call("listDirs", Body(path: path))diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swift b/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swiftindex 214399db..84c40194 100644--- a/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Client/SharedStore.swift@@ -1,5 +1,6 @@import CryptoKitimport Foundation+import os/// Values shared between the app, its widgets and its notification extension through the App Group,/// one namespace per account context so a signed-out account's data never shows in another.@@ -111,6 +112,8 @@ public enum SharedStore {public func erase() {for name in Self.names { defaults.removeObject(forKey: key(name)) }DeviceIdentity.delete(context: self)+ do { try ActivityIconCache.erase(context: id) }+ catch { Logger(subsystem: "com.pokai.Codync", category: "CustomIcon").error("Cannot erase activity icons: \(error.localizedDescription)") }let caches = URL.cachesDirectorylet marker = "-\(id)-"for file in (try? FileManager.default.contentsOfDirectory(atPath: caches.path())) ?? []diff --git a/apps/ios/Kit/Sources/CodyncKit/Design/ActivityCards.swift b/apps/ios/Kit/Sources/CodyncKit/Design/ActivityCards.swiftindex 8b2aada4..1547ae32 100644--- a/apps/ios/Kit/Sources/CodyncKit/Design/ActivityCards.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Design/ActivityCards.swift@@ -61,13 +61,14 @@ public struct ActivityAvatar: View {let color: Stringlet state: BotActivityPresentationlet size: CGFloat+ let customIcon: CustomIcon?- public init(shape: String, color: String, state: BotActivityPresentation, size: CGFloat) {- self.shape = shape; self.color = color; self.state = state; self.size = size+ public init(shape: String, color: String, state: BotActivityPresentation, size: CGFloat, customIcon: CustomIcon? = nil) {+ self.shape = shape; self.color = color; self.state = state; self.size = size; self.customIcon = customIcon}public var body: some View {- CharacterAvatar(shape: shape, color: color, size: size, mood: state.mood, still: true)+ CharacterAvatar(shape: shape, color: color, size: size, mood: state.mood, still: true, customIcon: customIcon).animation(Motion.activityPhase, value: state.mood)}}@@ -183,7 +184,7 @@ public struct BotActivityCard<Face: View, Mark: View>: View {public extension BotActivityCard where Face == ActivityAvatar, Mark == BotActivityIndicator {init(bot: Bot, state: BotActivityPresentation, startedAt: Date? = nil) {self.init(name: widgetName(bot), state: state, startedAt: startedAt) {- ActivityAvatar(shape: bot.avatarShape, color: bot.avatarColor, state: state, size: 32)+ ActivityAvatar(shape: bot.avatarShape, color: bot.avatarColor, state: state, size: 32, customIcon: bot.customIcon)} mark: {BotActivityIndicator(state: state, size: 28)}@@ -315,7 +316,9 @@ public struct BotActivityPreview: View {/// The island plays the working bot's loop (WorkingBotFace in the widget); here the live/// avatar stands in for it.@ViewBuilder private func islandFace(_ size: CGFloat) -> some View {- if state.phase == .working {+ if bot.customIcon != nil {+ CharacterAvatar(bot: bot, size: size, still: true)+ } else if state.phase == .working {CharacterAvatar(shape: bot.avatarShape, color: bot.avatarColor, size: size, mood: .working)} else {ActivityAvatar(shape: bot.avatarShape, color: bot.avatarColor, state: state, size: size)diff --git a/apps/ios/Kit/Sources/CodyncKit/Design/ActivityIconCache.swift b/apps/ios/Kit/Sources/CodyncKit/Design/ActivityIconCache.swiftnew file mode 100644index 00000000..3165381d--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncKit/Design/ActivityIconCache.swift@@ -0,0 +1,69 @@+import ActivityKit+import CryptoKit+import Foundation+import UIKit++/// Static PNGs shared by this account’s Live Activities. No network reads.+public enum ActivityIconCache {+ public static func writeImage(_ icon: CustomIcon, context: String) throws {+ guard let data = icon.pngData, let filename = icon.filename, let directory = directory(context) else { return }+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ let file = directory.appendingPathComponent(filename)+ if !FileManager.default.fileExists(atPath: file.path) { try data.write(to: file, options: .atomic) }+ }++ public static func erase(context: String) throws {+ guard let directory = directory(context), FileManager.default.fileExists(atPath: directory.path) else { return }+ try FileManager.default.removeItem(at: directory)+ }++ public struct ActivityReference: Codable, Sendable {+ public var name: String+ public var tinted: Bool+ }++ /// A small local pointer lets an already-running activity follow replacements/removals.+ public static func writeReference(_ icon: CustomIcon?, computerId: ComputerID, botId: String, context: String) throws {+ try icon?.cacheForActivity(context: context)+ guard let directory = directory(context), let file = referenceURL(computerId, botId, context) else { return }+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ let reference = ActivityReference(name: icon?.filename ?? "", tinted: icon?.tinted ?? false)+ try JSONEncoder().encode(reference).write(to: file, options: .atomic)+ }++ public static func activityReference(computerId: ComputerID, botId: String, context: String) -> ActivityReference? {+ guard let file = referenceURL(computerId, botId, context), let data = try? Data(contentsOf: file) else { return nil }+ return try? JSONDecoder().decode(ActivityReference.self, from: data)+ }++ /// Remove superseded PNGs, preserving references belonging to other computers and activities.+ public static func prune(context: String) throws {+ guard let directory = directory(context), FileManager.default.fileExists(atPath: directory.path) else { return }+ let files = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)+ var retained = Set(Activity<BotActivityAttributes>.activities.filter { $0.attributes.iconContext == context }.compactMap { $0.attributes.currentCustomIconName })+ for file in files where file.lastPathComponent.hasPrefix("activity-") && file.pathExtension == "json" {+ let reference = try JSONDecoder().decode(ActivityReference.self, from: Data(contentsOf: file))+ if !reference.name.isEmpty { retained.insert(reference.name) }+ }+ for file in files where file.pathExtension == "png" && !retained.contains(file.lastPathComponent) {+ try FileManager.default.removeItem(at: file)+ }+ }++ private static func referenceURL(_ computerId: ComputerID, _ botId: String, _ context: String) -> URL? {+ let key = SHA256.hash(data: Data("\(computerId)\u{0}\(botId)".utf8)).map { String(format: "%02x", $0) }.joined()+ return directory(context)?.appendingPathComponent("activity-\(key).json")+ }++ @MainActor public static func image(filename: String, context: String) -> UIImage? {+ guard filename.count == 68, filename.hasSuffix(".png"),+ filename.dropLast(4).allSatisfy({ $0.isHexDigit }), let directory = directory(context) else { return nil }+ return UIImage(contentsOfFile: directory.appendingPathComponent(filename).path)+ }++ private static func directory(_ context: String) -> URL? {+ FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: SharedStore.appGroup)?+ .appendingPathComponent("CustomIcons", isDirectory: true)+ .appendingPathComponent(SHA256.hash(data: Data(context.utf8)).map { String(format: "%02x", $0) }.joined(), isDirectory: true)+ }+}diff --git a/apps/ios/Kit/Sources/CodyncKit/Design/CharacterAvatar.swift b/apps/ios/Kit/Sources/CodyncKit/Design/CharacterAvatar.swiftindex e98c7c9d..24a65db0 100644--- a/apps/ios/Kit/Sources/CodyncKit/Design/CharacterAvatar.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Design/CharacterAvatar.swift@@ -12,11 +12,13 @@ public struct CharacterAvatar: View {let size: CGFloatlet mood: Moodlet still: Bool+ var customIcon: CustomIcon?/// `still` draws one frame of the mood (widgets and Live Activities render one frame);/// a change of mood then moves the halftone highlight and the eyes, animatable dot by dot.- public init(shape: String, color: String, size: CGFloat = 40, mood: Mood = .idle, still: Bool = false) {+ public init(shape: String, color: String, size: CGFloat = 40, mood: Mood = .idle, still: Bool = false, customIcon: CustomIcon? = nil) {self.init(shape: shape, tint: AvatarPalette.color(color), size: size, mood: mood, still: still)+ self.customIcon = customIcon}public init(shape: String, tint: Color, size: CGFloat = 40, mood: Mood = .idle, still: Bool = false) {@@ -34,15 +36,23 @@ public struct CharacterAvatar: View {size: size,mood: animated ? bot.mood : .idle)+ customIcon = bot.customIcon}/// The bot's current mood, drawn as one frame.public init(bot: Bot, size: CGFloat = 40, still: Bool) {self.init(shape: bot.avatarShape, color: bot.avatarColor, size: size, mood: bot.mood, still: still)+ customIcon = bot.customIcon}public var body: some View {- DottedBody(shape: shape, color: color, size: size, mood: mood, paused: still)+ Group {+ if let customIcon, customIcon.image != nil {+ CustomIconView(icon: customIcon, size: size, tint: color)+ } else {+ DottedBody(shape: shape, color: color, size: size, mood: mood, paused: still || customIcon != nil)+ }+ }.frame(width: size, height: size).accessibilityHidden(true)}@@ -326,7 +336,7 @@ public struct AvatarWithStatus: View {public var body: some View {Group {- if bot.isGroup { GroupAvatar(members: members, size: size) } else { CharacterAvatar(bot: bot, size: size) }+ if bot.isGroup && bot.customIcon == nil { GroupAvatar(members: members, size: size) } else { CharacterAvatar(bot: bot, size: size) }}.overlay(alignment: bot.lead ? .topTrailing : .bottomTrailing) {if bot.needsInput {diff --git a/apps/ios/Kit/Sources/CodyncKit/Design/CustomIconView.swift b/apps/ios/Kit/Sources/CodyncKit/Design/CustomIconView.swiftnew file mode 100644index 00000000..6765f590--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncKit/Design/CustomIconView.swift@@ -0,0 +1,21 @@+import SwiftUI++/// Custom images never run the generated character's sprite/timer animation.+public struct CustomIconView: View {+ let icon: CustomIcon+ let size: CGFloat+ let tint: Color++ public init(icon: CustomIcon, size: CGFloat, tint: Color = Palette.text) {+ self.icon = icon+ self.size = size+ self.tint = tint+ }++ public var body: some View {+ if let image = icon.image {+ Image(uiImage: image).resizable().renderingMode(icon.tinted ? .template : .original)+ .scaledToFit().foregroundStyle(tint).frame(width: size, height: size).accessibilityHidden(true)+ }+ }+}diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Bot.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Bot.swiftindex 9a4454d3..8b50a4f5 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/Bot.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Bot.swift@@ -12,6 +12,7 @@ public struct Bot: Codable, Identifiable, Hashable, Sendable {public var description: Stringpublic var avatarColor: Stringpublic var avatarShape: String+ public var customIcon: CustomIcon?public var backend: Stringpublic var command: String?public var cwd: String@@ -107,6 +108,7 @@ extension Bot {description = try c.decodeIfPresent(String.self, forKey: .description) ?? ""avatarColor = try c.decodeIfPresent(String.self, forKey: .avatarColor) ?? "blue"avatarShape = try c.decodeIfPresent(String.self, forKey: .avatarShape) ?? "blob"+ customIcon = try c.decodeIfPresent(CustomIcon.self, forKey: .customIcon)backend = try c.decodeIfPresent(String.self, forKey: .backend) ?? "custom"command = try c.decodeIfPresent(String.self, forKey: .command)cwd = try c.decodeIfPresent(String.self, forKey: .cwd) ?? ""diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/BotActivity.swift b/apps/ios/Kit/Sources/CodyncKit/Models/BotActivity.swiftindex ca5aac15..2993fdd8 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/BotActivity.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/BotActivity.swift@@ -39,6 +39,8 @@ public struct BotActivityAttributes: ActivityAttributes {public var callStartedAt: Date?/// That call's microphone is muted (its Live Activity's mute button).public var callMuted: Bool?+ /// Changes trigger a local redraw; remote status updates still use the shared local pointer.+ public var customIconRevision: String?public init(status: String, activity: String, startedAt: Date?, call: CallState? = nil, callStartedAt: Date? = nil,callMuted: Bool? = nil) {@@ -57,13 +59,29 @@ public struct BotActivityAttributes: ActivityAttributes {public var name: Stringpublic var avatarShape: Stringpublic var avatarColor: String+ public var customIconContext: String?+ public var iconContext: String { customIconContext ?? "local" }+ public var customIconName: String?+ public var customIconTinted: Bool?++ public var currentCustomIconName: String? {+ let name = ActivityIconCache.activityReference(computerId: computerId, botId: botId, context: iconContext)?.name ?? customIconName+ return name?.isEmpty == true ? nil : name+ }++ public var currentCustomIconTinted: Bool {+ ActivityIconCache.activityReference(computerId: computerId, botId: botId, context: iconContext)?.tinted ?? (customIconTinted == true)+ }public init(bot: Bot, computerId: ComputerID, link: URL? = nil) {+ customIconContext = URLComponents(url: link ?? AppEnvironment.current.link("bot"), resolvingAgainstBaseURL: false)?.queryItems?.first { $0.name == "scope" }?.value ?? SharedStore.activeContext.idself.link = linkself.computerId = computerIdbotId = bot.idname = bot.nameavatarShape = bot.avatarShapeavatarColor = bot.avatarColor+ customIconName = bot.customIcon?.filename+ customIconTinted = bot.customIcon?.tinted}}diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/CustomIcon.swift b/apps/ios/Kit/Sources/CodyncKit/Models/CustomIcon.swiftnew file mode 100644index 00000000..c4c15084--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncKit/Models/CustomIcon.swift@@ -0,0 +1,41 @@+import CryptoKit+import Foundation+import UIKit++/// The host supplies a static, normalized PNG, never an arbitrary remote URL.+public struct CustomIcon: Codable, Hashable, Sendable {+ public var dataUrl: String+ public var tinted: Bool++ public var pngData: Data? {+ let prefix = "data:image/png;base64,"+ guard dataUrl.hasPrefix(prefix), dataUrl.utf8.count <= 65_558,+ let data = Data(base64Encoded: String(dataUrl.dropFirst(prefix.count))),+ data.starts(with: [137, 80, 78, 71, 13, 10, 26, 10]) else { return nil }+ return data+ }++ /// Only the small filename goes in ActivityKit's limited attributes, not the image bytes.+ public var filename: String? {+ pngData.map { SHA256.hash(data: $0).map { String(format: "%02x", $0) }.joined() + ".png" }+ }++ @MainActor private static let decoded: NSCache<NSString, UIImage> = {+ let cache = NSCache<NSString, UIImage>()+ cache.countLimit = 128+ cache.totalCostLimit = 8 * 1024 * 1024+ return cache+ }()++ @MainActor public var image: UIImage? {+ guard let data = pngData, let filename else { return nil }+ if let cached = Self.decoded.object(forKey: filename as NSString) { return cached }+ guard let image = UIImage(data: data) else { return nil }+ Self.decoded.setObject(image, forKey: filename as NSString, cost: Int(image.size.width * image.size.height) * 4)+ return image+ }++ public func cacheForActivity(context: String) throws {+ try ActivityIconCache.writeImage(self, context: context)+ }+}diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swiftindex b1073d77..b4aa0f06 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift@@ -216,6 +216,8 @@ public enum SetupStep: String, Codable, Sendable {}public struct Hello: Codable, Sendable {+ public var icons: [String: CustomIcon]?+ public var iconsRevision: Int64?public var hostId: Stringpublic var name: Stringpublic var version: String@@ -243,7 +245,15 @@ public struct Hello: Codable, Sendable {public var latestVersion: String?}+public struct RecentWorkspace: Codable, Sendable, Identifiable {+ public var path: String+ public var usedAt: Int64+ public var id: String { path }+}+public struct DirListing: Codable, Sendable {+ public var recent: [RecentWorkspace]?+ public var ancestors: [DirItem]?public var path: Stringpublic var parent: String?public var isGit: Booldiff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.jsonindex f820ac07..caa82c11 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json@@ -1409,5 +1409,40 @@"cloud assistants are off here": "Cloud-Assistenten sind hier aus","Offered to the network: bots on your other computers can see and message this bot.": "Im Netzwerk angeboten: Bots auf deinen anderen Computern sehen diesen Bot und können ihm schreiben.","Reachable by cloud assistants: ChatGPT or Claude in your Codync account can see and message this bot.": "Für Cloud-Assistenten erreichbar: ChatGPT oder Claude in deinem Codync-Konto sehen diesen Bot und können ihm schreiben.",- "Live Activities on the Lock Screen and in the Dynamic Island turn on and off together.": "Live-Aktivitäten auf dem Sperrbildschirm und in der Dynamic Island werden gemeinsam ein- und ausgeschaltet."+ "Live Activities on the Lock Screen and in the Dynamic Island turn on and off together.": "Live-Aktivitäten auf dem Sperrbildschirm und in der Dynamic Island werden gemeinsam ein- und ausgeschaltet.",+ "The Dynamic Island shows the same Live Activity as the Lock Screen, so this switch turns off both.": "Die Dynamic Island zeigt dieselbe Live-Aktivität wie der Sperrbildschirm. Dieser Schalter deaktiviert daher beide.",+ "Custom icon": "Eigenes Symbol",+ "Choose image": "Bild auswählen",+ "Use default": "Standard verwenden",+ "Image URL": "Bild-URL",+ "Use URL": "URL verwenden",+ "Tint icon": "Symbol einfärben",+ "Turn off to keep the image's original colors.": "Deaktivieren, um die Originalfarben des Bildes beizubehalten.",+ "Choose an image up to 5 MiB.": "Wähle ein Bild mit höchstens 5 MiB.",+ "Cannot read this image.": "Dieses Bild kann nicht gelesen werden.",+ "Upload from desktop": "Vom Computer hochladen",+ "Upload image": "Bild hochladen",+ "Paste URL": "URL einfügen",+ "PNG, JPEG, WebP up to 5 MiB; SVG up to 256 KiB.": "PNG, JPEG, WebP bis 5 MiB; SVG bis 256 KiB.",+ "Saved immediately. Custom images stay still.": "Wird sofort gespeichert. Eigene Bilder bleiben unbewegt.",+ "Sign in required": "Anmeldung erforderlich",+ "Sign in to use custom images.": "Melde dich an, um eigene Bilder zu verwenden.",+ "Choose workspace": "Choose workspace",+ "Your bot will work in this folder.": "Your bot will work in this folder.",+ "Recent workspaces": "Recent workspaces",+ "Search recent workspaces": "Search recent workspaces",+ "Filter this folder": "Filter this folder",+ "Browse other folders": "Browse other folders",+ "Use this folder": "Use this folder",+ "Selected folder": "Selected folder",+ "Current folder": "Current folder",+ "Choose a folder": "Choose a folder",+ "Choose a folder to see it here next time.": "Choose a folder to see it here next time.",+ "No matching folders.": "No matching folders.",+ "No subfolders. You can use this folder.": "No subfolders. You can use this folder.",+ "Parent folder": "Parent folder",+ "Enter folder path": "Enter folder path",+ "Folder path": "Folder path",+ "Paste an absolute path": "Paste an absolute path",+ "Go to folder": "Go to folder"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.jsonindex 51ff0782..54a5e17e 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json@@ -1409,5 +1409,40 @@"cloud assistants are off here": "los asistentes en la nube están desactivados aquí","Offered to the network: bots on your other computers can see and message this bot.": "Ofrecido a la red: los bots de tus otras computadoras pueden ver este bot y escribirle.","Reachable by cloud assistants: ChatGPT or Claude in your Codync account can see and message this bot.": "Accesible para asistentes en la nube: ChatGPT o Claude en tu cuenta de Codync pueden ver este bot y escribirle.",- "Live Activities on the Lock Screen and in the Dynamic Island turn on and off together.": "Las actividades en directo de la pantalla bloqueada y la Dynamic Island se activan y desactivan juntas."+ "Live Activities on the Lock Screen and in the Dynamic Island turn on and off together.": "Las actividades en directo de la pantalla bloqueada y la Dynamic Island se activan y desactivan juntas.",+ "The Dynamic Island shows the same Live Activity as the Lock Screen, so this switch turns off both.": "Dynamic Island muestra la misma actividad en directo que la pantalla de bloqueo, así que este interruptor desactiva ambas.",+ "Custom icon": "Icono personalizado",+ "Choose image": "Elegir imagen",+ "Use default": "Usar predeterminado",+ "Image URL": "URL de la imagen",+ "Use URL": "Usar URL",+ "Tint icon": "Colorear icono",+ "Turn off to keep the image's original colors.": "Desactiva para conservar los colores originales de la imagen.",+ "Choose an image up to 5 MiB.": "Elige una imagen de hasta 5 MiB.",+ "Cannot read this image.": "No se puede leer esta imagen.",+ "Upload from desktop": "Subir desde el ordenador",+ "Upload image": "Subir imagen",+ "Paste URL": "Pegar URL",+ "PNG, JPEG, WebP up to 5 MiB; SVG up to 256 KiB.": "PNG, JPEG, WebP hasta 5 MiB; SVG hasta 256 KiB.",+ "Saved immediately. Custom images stay still.": "Se guarda al instante. Las imágenes personalizadas no se animan.",+ "Sign in required": "Debes iniciar sesión",+ "Sign in to use custom images.": "Inicia sesión para usar imágenes personalizadas.",+ "Choose workspace": "Choose workspace",+ "Your bot will work in this folder.": "Your bot will work in this folder.",+ "Recent workspaces": "Recent workspaces",+ "Search recent workspaces": "Search recent workspaces",+ "Filter this folder": "Filter this folder",+ "Browse other folders": "Browse other folders",+ "Use this folder": "Use this folder",+ "Selected folder": "Selected folder",+ "Current folder": "Current folder",+ "Choose a folder": "Choose a folder",+ "Choose a folder to see it here next time.": "Choose a folder to see it here next time.",+ "No matching folders.": "No matching folders.",+ "No subfolders. You can use this folder.": "No subfolders. You can use this folder.",+ "Parent folder": "Parent folder",+ "Enter folder path": "Enter folder path",+ "Folder path": "Folder path",+ "Paste an absolute path": "Paste an absolute path",+ "Go to folder": "Go to folder"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.jsonindex 3b86fd99..e1821c79 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json@@ -1409,5 +1409,40 @@"cloud assistants are off here": "les assistants cloud sont désactivés ici","Offered to the network: bots on your other computers can see and message this bot.": "Proposé au réseau : les bots de vos autres ordinateurs voient ce bot et peuvent lui écrire.","Reachable by cloud assistants: ChatGPT or Claude in your Codync account can see and message this bot.": "Joignable par les assistants cloud : ChatGPT ou Claude dans votre compte Codync voit ce bot et peut lui écrire.",- "Live Activities on the Lock Screen and in the Dynamic Island turn on and off together.": "Les activités en direct sur l’écran verrouillé et dans la Dynamic Island s’activent et se désactivent ensemble."+ "Live Activities on the Lock Screen and in the Dynamic Island turn on and off together.": "Les activités en direct sur l’écran verrouillé et dans la Dynamic Island s’activent et se désactivent ensemble.",+ "The Dynamic Island shows the same Live Activity as the Lock Screen, so this switch turns off both.": "La Dynamic Island affiche la même activité en direct que l’écran verrouillé ; ce commutateur désactive donc les deux.",+ "Custom icon": "Icône personnalisée",+ "Choose image": "Choisir une image",+ "Use default": "Utiliser l’icône par défaut",+ "Image URL": "URL de l’image",+ "Use URL": "Utiliser l’URL",+ "Tint icon": "Colorer l’icône",+ "Turn off to keep the image's original colors.": "Désactivez pour conserver les couleurs d’origine.",+ "Choose an image up to 5 MiB.": "Choisissez une image de 5 MiB maximum.",+ "Cannot read this image.": "Impossible de lire cette image.",+ "Upload from desktop": "Importer depuis l’ordinateur",+ "Upload image": "Importer une image",+ "Paste URL": "Coller une URL",+ "PNG, JPEG, WebP up to 5 MiB; SVG up to 256 KiB.": "PNG, JPEG, WebP jusqu’à 5 MiB ; SVG jusqu’à 256 KiB.",+ "Saved immediately. Custom images stay still.": "Enregistrement immédiat. Les images personnalisées restent fixes.",+ "Sign in required": "Connexion requise",+ "Sign in to use custom images.": "Connectez-vous pour utiliser des images personnalisées.",+ "Choose workspace": "Choose workspace",+ "Your bot will work in this folder.": "Your bot will work in this folder.",+ "Recent workspaces": "Recent workspaces",+ "Search recent workspaces": "Search recent workspaces",+ "Filter this folder": "Filter this folder",+ "Browse other folders": "Browse other folders",+ "Use this folder": "Use this folder",+ "Selected folder": "Selected folder",+ "Current folder": "Current folder",+ "Choose a folder": "Choose a folder",+ "Choose a folder to see it here next time.": "Choose a folder to see it here next time.",+ "No matching folders.": "No matching folders.",+ "No subfolders. You can use this folder.": "No subfolders. You can use this folder.",+ "Parent folder": "Parent folder",+ "Enter folder path": "Enter folder path",+ "Folder path": "Folder path",+ "Paste an absolute path": "Paste an absolute path",+ "Go to folder": "Go to folder"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.jsonindex fabe35df..d39b3ca4 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json@@ -1409,5 +1409,40 @@"cloud assistants are off here": "ここではクラウドアシスタントがオフです","Offered to the network: bots on your other computers can see and message this bot.": "ネットワークに公開:ほかのコンピューターのボットがこのボットを見つけてメッセージを送れます。","Reachable by cloud assistants: ChatGPT or Claude in your Codync account can see and message this bot.": "クラウドアシスタントから利用可能:Codync アカウントの ChatGPT や Claude がこのボットを見つけてメッセージを送れます。",- "Live Activities on the Lock Screen and in the Dynamic Island turn on and off together.": "ロック画面とDynamic Islandのライブアクティビティは、一緒にオン・オフになります。"+ "Live Activities on the Lock Screen and in the Dynamic Island turn on and off together.": "ロック画面とDynamic Islandのライブアクティビティは、一緒にオン・オフになります。",+ "The Dynamic Island shows the same Live Activity as the Lock Screen, so this switch turns off both.": "Dynamic Islandにはロック画面と同じライブアクティビティが表示されるため、このスイッチで両方がオフになります。",+ "Custom icon": "カスタムアイコン",+ "Choose image": "画像を選択",+ "Use default": "デフォルトに戻す",+ "Image URL": "画像のURL",+ "Use URL": "URLを使用",+ "Tint icon": "アイコンに色を付ける",+ "Turn off to keep the image's original colors.": "オフにすると画像の元の色を保持します。",+ "Choose an image up to 5 MiB.": "5 MiB 以下の画像を選択してください。",+ "Cannot read this image.": "この画像を読み込めません。",+ "Upload from desktop": "パソコンからアップロード",+ "Upload image": "画像をアップロード",+ "Paste URL": "URLを貼り付け",+ "PNG, JPEG, WebP up to 5 MiB; SVG up to 256 KiB.": "PNG・JPEG・WebP は最大 5 MiB、SVG は最大 256 KiB。",+ "Saved immediately. Custom images stay still.": "変更はすぐに保存されます。カスタム画像は静止画です。",+ "Sign in required": "ログインが必要です",+ "Sign in to use custom images.": "カスタム画像を使うにはログインしてください。",+ "Choose workspace": "Choose workspace",+ "Your bot will work in this folder.": "Your bot will work in this folder.",+ "Recent workspaces": "Recent workspaces",+ "Search recent workspaces": "Search recent workspaces",+ "Filter this folder": "Filter this folder",+ "Browse other folders": "Browse other folders",+ "Use this folder": "Use this folder",+ "Selected folder": "Selected folder",+ "Current folder": "Current folder",+ "Choose a folder": "Choose a folder",+ "Choose a folder to see it here next time.": "Choose a folder to see it here next time.",+ "No matching folders.": "No matching folders.",+ "No subfolders. You can use this folder.": "No subfolders. You can use this folder.",+ "Parent folder": "Parent folder",+ "Enter folder path": "Enter folder path",+ "Folder path": "Folder path",+ "Paste an absolute path": "Paste an absolute path",+ "Go to folder": "Go to folder"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.jsonindex 85086e6d..cc12b31f 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json@@ -1409,5 +1409,40 @@"cloud assistants are off here": "여기서는 클라우드 어시스턴트가 꺼져 있습니다","Offered to the network: bots on your other computers can see and message this bot.": "네트워크에 공개: 다른 컴퓨터의 봇이 이 봇을 보고 메시지를 보낼 수 있습니다.","Reachable by cloud assistants: ChatGPT or Claude in your Codync account can see and message this bot.": "클라우드 어시스턴트가 연락 가능: Codync 계정의 ChatGPT나 Claude가 이 봇을 보고 메시지를 보낼 수 있습니다.",- "Live Activities on the Lock Screen and in the Dynamic Island turn on and off together.": "잠금 화면과 Dynamic Island의 실시간 현황은 함께 켜지거나 꺼집니다."+ "Live Activities on the Lock Screen and in the Dynamic Island turn on and off together.": "잠금 화면과 Dynamic Island의 실시간 현황은 함께 켜지거나 꺼집니다.",+ "The Dynamic Island shows the same Live Activity as the Lock Screen, so this switch turns off both.": "Dynamic Island는 잠금 화면과 같은 실시간 현황을 표시하므로 이 스위치를 끄면 둘 다 꺼집니다.",+ "Custom icon": "사용자 지정 아이콘",+ "Choose image": "이미지 선택",+ "Use default": "기본 아이콘 사용",+ "Image URL": "이미지 URL",+ "Use URL": "URL 사용",+ "Tint icon": "아이콘 색상 적용",+ "Turn off to keep the image's original colors.": "끄면 이미지의 원래 색상이 유지됩니다.",+ "Choose an image up to 5 MiB.": "5 MiB 이하의 이미지를 선택하세요.",+ "Cannot read this image.": "이 이미지를 읽을 수 없습니다.",+ "Upload from desktop": "컴퓨터에서 업로드",+ "Upload image": "이미지 업로드",+ "Paste URL": "URL 붙여넣기",+ "PNG, JPEG, WebP up to 5 MiB; SVG up to 256 KiB.": "PNG, JPEG, WebP 최대 5 MiB, SVG 최대 256 KiB.",+ "Saved immediately. Custom images stay still.": "즉시 저장됩니다. 사용자 지정 이미지는 움직이지 않습니다.",+ "Sign in required": "로그인 필요",+ "Sign in to use custom images.": "사용자 지정 이미지를 사용하려면 로그인하세요.",+ "Choose workspace": "Choose workspace",+ "Your bot will work in this folder.": "Your bot will work in this folder.",+ "Recent workspaces": "Recent workspaces",+ "Search recent workspaces": "Search recent workspaces",+ "Filter this folder": "Filter this folder",+ "Browse other folders": "Browse other folders",+ "Use this folder": "Use this folder",+ "Selected folder": "Selected folder",+ "Current folder": "Current folder",+ "Choose a folder": "Choose a folder",+ "Choose a folder to see it here next time.": "Choose a folder to see it here next time.",+ "No matching folders.": "No matching folders.",+ "No subfolders. You can use this folder.": "No subfolders. You can use this folder.",+ "Parent folder": "Parent folder",+ "Enter folder path": "Enter folder path",+ "Folder path": "Folder path",+ "Paste an absolute path": "Paste an absolute path",+ "Go to folder": "Go to folder"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.jsonindex e79d20f4..f02a2bdf 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json@@ -1409,5 +1409,40 @@"cloud assistants are off here": "这里的云端助手已关闭","Offered to the network: bots on your other computers can see and message this bot.": "提供给网络:你其他电脑上的 Bot 能看到这个 Bot 并给它发消息。","Reachable by cloud assistants: ChatGPT or Claude in your Codync account can see and message this bot.": "云端助手可联系:你 Codync 账户里的 ChatGPT 或 Claude 能看到这个 Bot 并给它发消息。",- "Live Activities on the Lock Screen and in the Dynamic Island turn on and off together.": "锁定屏幕的实时活动与灵动岛会同步开启或关闭。"+ "Live Activities on the Lock Screen and in the Dynamic Island turn on and off together.": "锁定屏幕的实时活动与灵动岛会同步开启或关闭。",+ "The Dynamic Island shows the same Live Activity as the Lock Screen, so this switch turns off both.": "灵动岛和锁定屏幕用的是同一个实时活动,所以这个开关会同时关掉两边。",+ "Custom icon": "自定义图标",+ "Choose image": "选择图片",+ "Use default": "使用默认图标",+ "Image URL": "图片网址",+ "Use URL": "使用网址",+ "Tint icon": "图标着色",+ "Turn off to keep the image's original colors.": "关闭以保留图片原色。",+ "Choose an image up to 5 MiB.": "请选择不超过 5 MiB 的图片。",+ "Cannot read this image.": "无法读取这张图片。",+ "Upload from desktop": "从电脑上传",+ "Upload image": "上传图片",+ "Paste URL": "粘贴网址",+ "PNG, JPEG, WebP up to 5 MiB; SVG up to 256 KiB.": "PNG、JPEG、WebP 最大 5 MiB;SVG 最大 256 KiB。",+ "Saved immediately. Custom images stay still.": "立即保存。自定义图片保持静态。",+ "Sign in required": "需要登录",+ "Sign in to use custom images.": "使用自定义图片需要登录账号。",+ "Choose workspace": "Choose workspace",+ "Your bot will work in this folder.": "Your bot will work in this folder.",+ "Recent workspaces": "Recent workspaces",+ "Search recent workspaces": "Search recent workspaces",+ "Filter this folder": "Filter this folder",+ "Browse other folders": "Browse other folders",+ "Use this folder": "Use this folder",+ "Selected folder": "Selected folder",+ "Current folder": "Current folder",+ "Choose a folder": "Choose a folder",+ "Choose a folder to see it here next time.": "Choose a folder to see it here next time.",+ "No matching folders.": "No matching folders.",+ "No subfolders. You can use this folder.": "No subfolders. You can use this folder.",+ "Parent folder": "Parent folder",+ "Enter folder path": "Enter folder path",+ "Folder path": "Folder path",+ "Paste an absolute path": "Paste an absolute path",+ "Go to folder": "Go to folder"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.jsonindex 8d91beaf..3dc29ac9 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json@@ -1409,5 +1409,40 @@"cloud assistants are off here": "這裡的雲端助理已關閉","Offered to the network: bots on your other computers can see and message this bot.": "提供給網路:你其他電腦上的 Bot 能看到這個 Bot 並傳訊息給它。","Reachable by cloud assistants: ChatGPT or Claude in your Codync account can see and message this bot.": "雲端助理可聯繫:你 Codync 賬戶裡的 ChatGPT 或 Claude 能看到這個 Bot 並傳訊息給它。",- "Live Activities on the Lock Screen and in the Dynamic Island turn on and off together.": "鎖定畫面的即時動態與動態島會同步開啟或關閉。"+ "Live Activities on the Lock Screen and in the Dynamic Island turn on and off together.": "鎖定畫面的即時動態與動態島會同步開啟或關閉。",+ "Choose workspace": "選擇工作資料夾",+ "Your bot will work in this folder.": "Bot 會在這個資料夾中工作。",+ "Recent workspaces": "最近使用",+ "Search recent workspaces": "搜尋最近使用的資料夾",+ "Filter this folder": "篩選此資料夾",+ "Browse other folders": "瀏覽其他資料夾",+ "Use this folder": "使用此資料夾",+ "Selected folder": "已選取的資料夾",+ "Current folder": "目前資料夾",+ "Choose a folder": "選擇一個資料夾",+ "Choose a folder to see it here next time.": "選擇資料夾後,下次會顯示在這裡。",+ "No matching folders.": "找不到符合的資料夾。",+ "No subfolders. You can use this folder.": "此處沒有子資料夾,可以直接使用此資料夾。",+ "Parent folder": "上一層資料夾",+ "Enter folder path": "輸入資料夾路徑",+ "Folder path": "資料夾路徑",+ "Paste an absolute path": "貼上完整路徑",+ "Go to folder": "前往資料夾",+ "The Dynamic Island shows the same Live Activity as the Lock Screen, so this switch turns off both.": "靈動島和鎖定螢幕用的是同一個實時活動,所以這個開關會同時關掉兩邊。",+ "Custom icon": "自訂圖示",+ "Choose image": "選擇圖片",+ "Use default": "使用預設圖示",+ "Image URL": "圖片網址",+ "Use URL": "使用網址",+ "Tint icon": "圖示套用色彩",+ "Turn off to keep the image's original colors.": "關閉以保留圖片原色。",+ "Choose an image up to 5 MiB.": "請選擇不超過 5 MiB 的圖片。",+ "Cannot read this image.": "無法讀取這張圖片。",+ "Upload from desktop": "從電腦上傳",+ "Upload image": "上傳圖片",+ "Paste URL": "貼上網址",+ "PNG, JPEG, WebP up to 5 MiB; SVG up to 256 KiB.": "PNG、JPEG、WebP 最大 5 MiB;SVG 最大 256 KiB。",+ "Saved immediately. Custom images stay still.": "立即儲存。自訂圖片維持靜態。",+ "Sign in required": "需要登入",+ "Sign in to use custom images.": "使用自訂圖片需要登入帳號。"}diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swiftindex df2f9ca2..ced4d982 100644--- a/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swift@@ -155,7 +155,7 @@ struct BotSettingsForm: View {withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { pickingAvatar.toggle() }} label: {ValueRow("Avatar") {- CharacterAvatar(shape: draft.avatarShape, color: draft.avatarColor, size: 28)+ CharacterAvatar(shape: draft.avatarShape, color: draft.avatarColor, size: 28, customIcon: draft.id.flatMap { model.icons["bot:\($0)"] }).padding(5).background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 10, style: .continuous))}@@ -164,7 +164,10 @@ struct BotSettingsForm: View {.buttonStyle(.plain).accessibilityLabel("Edit Bot avatar")if pickingAvatar {- AvatarPicker(shape: $draft.avatarShape, color: $draft.avatarColor)+ VStack(spacing: 16) {+ AvatarPicker(shape: $draft.avatarShape, color: $draft.avatarColor)+ if let id = draft.id { CustomIconEditor(target: "bot:\(id)") }+ }.transition(.opacity.combined(with: .move(edge: .top)))}}diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/ComputerFilterHeader.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/ComputerFilterHeader.swiftindex d7003293..0ed8fa83 100644--- a/apps/ios/Kit/Sources/CodyncUI/Bots/ComputerFilterHeader.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/ComputerFilterHeader.swift@@ -25,19 +25,21 @@ public struct ComputerFilterHeader: View {public var body: some View {Menu {- Button(L10n.tr("All computers"), systemImage: selection.shown.count == accounts.computers.count ? "checkmark" : "desktopcomputer") { update("") }+ Toggle(isOn: Binding(get: { selection.shown.count == accounts.computers.count }, set: { _ in update("") })) {+ Label(L10n.tr("All computers"), systemImage: "desktopcomputer")+ }ForEach(accounts.computers) { computer in- Button {- update(selection.toggling(computer.id))- } label: {- Label(computerTitle(computer), systemImage: selection.shown.contains(computer.id) ? "checkmark" : "desktopcomputer")+ Toggle(isOn: Binding(get: { selection.shown.contains(computer.id) }, set: { _ in update(selection.toggling(computer.id)) })) {+ Label { Text(computerTitle(computer)) } icon: { ComputerBadge(computer, size: 28) }}.menuActionDismissBehavior(.disabled)}if accounts.computers.count > 1 {Menu(L10n.tr("Show only")) {ForEach(accounts.computers) { computer in- Button(computer.name) { update(selection.only(computer.id)) }+ Button { update(selection.only(computer.id)) } label: {+ Label { Text(computer.name) } icon: { ComputerBadge(computer, size: 28) }+ }}}}diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/CustomIconEditor.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/CustomIconEditor.swiftnew file mode 100644index 00000000..27a31a61--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/CustomIconEditor.swift@@ -0,0 +1,84 @@+import CodyncKit+import Foundation+import SwiftUI+import UniformTypeIdentifiers++struct CustomIconEditor: View {+ @Environment(BotStore.self) private var store+ @Environment(\.customIconAccount) private var account+ @State private var needsSignIn = false+ let target: String+ @State private var editor = IconEditor()+ @State private var choosing = false+ @State private var url = ""+ @State private var showURL = false+ @FocusState private var urlFocused: Bool++ private var icon: CustomIcon? { store.icons[target] }+ var body: some View {+ if store.hello?.icons != nil { content }+ }++ private var content: some View {+ VStack(alignment: .center, spacing: 12) {+ Text("Custom icon").font(.subheadline.weight(.semibold))+ HStack(spacing: 12) {+ if let icon { CustomIconView(icon: icon, size: 40) }+ Button("Upload image") { requireAccount { Motion.animate { choosing = true } } }.buttonStyle(.secondary)+ }+ Button("Paste URL") { requireAccount { Motion.animate { showURL.toggle() }; urlFocused = showURL } }.buttonStyle(.secondary)+ if icon != nil || editor.busy { HStack {+ if icon != nil { Button("Use default") { save(.init(target: target, remove: true)) }.buttonStyle(.secondary) }+ if editor.busy { ThinkingOrb(size: 18) }+ } }+ if showURL {+ VStack(alignment: .leading, spacing: 6) {+ Text("Image URL").font(.caption).foregroundStyle(Palette.secondary)+ HStack {+ TextField("https://…", text: $url).textInputAutocapitalization(.never).autocorrectionDisabled().fieldBox()+ .keyboardType(.URL).focused($urlFocused).submitLabel(.go)+ .accessibilityLabel("Image URL").onSubmit { saveURL() }+ Button { saveURL() } label: { Image(systemName: "arrow.up") }+ .buttonStyle(.secondary).accessibilityLabel("Use URL")+ .disabled(url.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+ }+ }.transition(.opacity)+ }+ if let icon {+ Toggle("Tint icon", isOn: Binding(get: { icon.tinted }, set: { save(.init(target: target, tinted: $0)) }))+ .toggleStyle(.codync)+ }+ VStack(spacing: 2) {+ Text("PNG, JPEG, WebP up to 5 MiB; SVG up to 256 KiB.")+ Text("Saved immediately. Custom images stay still.")+ }+ .font(.caption).foregroundStyle(Palette.secondary).multilineTextAlignment(.center)+ if let error = editor.error ?? account?.error { Text(error).font(.caption).foregroundStyle(Palette.danger) }+ }+ .frame(maxWidth: .infinity)+ .disabled(editor.busy || account?.loading == true || store.connection != .online)+ .codyncDialog("Sign in required", isPresented: $needsSignIn, message: "Sign in to use custom images.") {+ [DialogAction("Continue with Apple") { account?.signInApple() },+ DialogAction("Continue with Google") { account?.signInGoogle() }]+ }+ .fileImporter(isPresented: $choosing, allowedContentTypes: [.png, .jpeg, .webP, .svg]) { result in+ switch result {+ case let .success(file): requireAccount { Task { await editor.save(.init(target: target), store: store, file: file) } }+ case let .failure(error): editor.error = error.localizedDescription+ }+ }+ }++ private func requireAccount(_ action: () -> Void) {+ guard account?.signedIn == true else { Motion.animate { needsSignIn = true }; return }+ action()+ }++ private func saveURL() {+ let value = url.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !value.isEmpty, !editor.busy, store.connection == .online else { return }+ requireAccount { save(.init(target: target, url: value)) }+ }++ private func save(_ change: IconEditor.Change) { Task { await editor.save(change, store: store) } }+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/FolderPicker.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/FolderPicker.swiftindex 31775aca..d56c661f 100644--- a/apps/ios/Kit/Sources/CodyncUI/Bots/FolderPicker.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/FolderPicker.swift@@ -1,136 +1,160 @@import CodyncKitimport SwiftUI-/// Browses folders on the host, drilling down in place.struct FolderPicker: View {let start: String?let onPick: (String) -> Void- /// The folders opened so far; the last one is shown.- @State private var stack: [String?]- @State private var forward = true- /// Where the first folder sits, so Back can climb above the starting folder ("" lists the drives).- @State private var parent: String?+ @Environment(BotStore.self) private var model@Environment(\.accessibilityReduceMotion) private var reduceMotion+ @State private var state = WorkspacePickerState()+ @State private var path: String?+ @State private var request = 0+ @State private var pathOpen = false+ @State private var pathInput = ""- init(start: String?, onPick: @escaping (String) -> Void) {- self.start = start- self.onPick = onPick- _stack = State(initialValue: [start])- }+ private var noRecent: Bool { state.mode == .recent && !state.busy && (state.listing?.recent ?? []).isEmpty }var body: some View {- let current = stack.last ?? nilVStack(spacing: 0) {- HStack(spacing: 0) {- if stack.count > 1 || parent != nil {- BackButton { go(forward: false) { stack = stack.count > 1 ? Array(stack.dropLast()) : [parent] } }- .padding(.leading, 12)- .transition(.opacity)- }- ModalHeader(current.flatMap(folderName) ?? "Folders")- }- ZStack {- FolderLevel(path: current, onPick: onPick, onParent: stack.count > 1 ? nil : { parent = $0 }) { path in- go(forward: true) { stack.append(path) }- }- .id("\(stack.count):\(current ?? "")")- .transition(.asymmetric(- insertion: .move(edge: forward ? .trailing : .leading),- removal: .move(edge: forward ? .leading : .trailing)- ).combined(with: .opacity))- }- .frame(maxHeight: .infinity, alignment: .top)- .clipped()+ ModalHeader("Choose workspace")+ ScrollView {+ VStack(alignment: .leading, spacing: 16) {+ Text("Your bot will work in this folder.").font(.subheadline).foregroundStyle(Palette.secondary)+ HStack(spacing: 10) {+ Image(systemName: "desktopcomputer")+ Text(model.hello?.name ?? "Computer").lineLimit(1)+ Spacer()+ Text(model.connection == .online ? "Connected" : "Disconnected")+ .font(.caption).foregroundStyle(Palette.secondary)+ }.padding(12).background(Palette.surface, in: RoundedRectangle(cornerRadius: 12))+ if noRecent { browseButton }+ if state.mode == .browse { navigation }+ if pathOpen {+ HStack {+ TextField("Paste an absolute path", text: $pathInput)+ .textFieldStyle(.plain).plainTextInput().onSubmit { openPath() }+ Button(action: openPath) { Image(systemName: "arrow.right") }+ .disabled(pathInput.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+ .accessibilityLabel("Go to folder")+ }.padding(12).background(Palette.surface, in: RoundedRectangle(cornerRadius: 10))+ .transition(.opacity.combined(with: .move(edge: .top)))+ }+ if !noRecent {+ SearchField(state.mode == .recent ? "Search recent workspaces" : "Filter this folder", text: $state.filter)+ Text(state.mode == .recent ? "Recent workspaces" : "Folders")+ .font(.caption).foregroundStyle(Palette.secondary)+ if state.busy { Spinner(size: 20).frame(maxWidth: .infinity).padding(24) }+ else if state.mode == .recent { recentRows }+ else { directoryRows }+ }+ if let error = state.error { Text(error).font(.subheadline).foregroundStyle(Palette.danger) }+ if state.mode == .recent && !noRecent { browseButton }+ }.padding(.horizontal, 20).padding(.bottom, 20)+ .disabled(state.saving)+ }.scrollDismissesKeyboard(.interactively)+ footer}.background(Palette.background)+ .task(id: request) { await state.load(path, model: model) }+ .onChange(of: model.connection) { _, _ in request += 1 }}- /// Sets the slide direction first, so the leaving level takes it too, then moves.- private func go(forward: Bool, _ change: @escaping () -> Void) {- self.forward = forward- Task { @MainActor in- withAnimation(Motion.reduced(Motion.layout, reduceMotion), change)- }+ private var browseButton: some View {+ Button { open(start) } label: {+ HStack {+ Image(systemName: "folder")+ Text("Browse other folders")+ Spacer()+ Image(systemName: "chevron.right").font(.caption)+ }.padding(.vertical, 12)+ }.buttonStyle(PressScale())}-}-/// One folder's subfolders.-private struct FolderLevel: View {- let path: String?- let onPick: (String) -> Void- /// Hears where this folder sits; only the first level reports it.- let onParent: ((String?) -> Void)?- let open: (String) -> Void- @Environment(BotStore.self) private var model- @State private var listing: DirListing?- @State private var error: String?- @State private var filter = ""-- var body: some View {- ScrollView {- LazyVStack(alignment: .leading, spacing: 22) {- SearchField(text: $filter)- if let listing {- // The drive list (Windows) has no folder of its own to use.- if !listing.path.isEmpty {- CardSection(footer: listing.path) {- Button {- onPick(listing.path)- } label: {- Label("Use “\(folderName(listing.path) ?? listing.path)”", systemImage: "checkmark.circle.fill")- .font(.headline)- .foregroundStyle(Palette.accent)- .frame(maxWidth: .infinity, alignment: .leading)- .contentShape(Rectangle())- }- .buttonStyle(PressScale())- }- }- let dirs = listing.dirs.filter { filter.isEmpty || $0.name.localizedCaseInsensitiveContains(filter) }- if !dirs.isEmpty {- CardSection {- ForEach(dirs) { dir in- Button {- open(dir.path)- } label: {- HStack(spacing: 10) {- Image(systemName: dir.isGit ? "arrow.triangle.branch" : "folder")- .foregroundStyle(dir.isGit ? Palette.accent : Palette.secondary)- .frame(width: 20)- Text(dir.name).foregroundStyle(Palette.text).lineLimit(1)- Spacer(minLength: 8)- Image(systemName: "chevron.right")- .font(.caption2.weight(.semibold))- .foregroundStyle(Palette.tertiary)- }- .contentShape(Rectangle())- }- .buttonStyle(PressScale())- }+ private var navigation: some View {+ HStack(spacing: 8) {+ Button {+ animate { state.mode = .recent; state.selected = ""; state.filter = ""; path = nil; pathOpen = false; request += 1 }+ } label: { Image(systemName: "chevron.left").frame(width: 32, height: 36) }+ .accessibilityLabel("Recent workspaces")+ ScrollView(.horizontal, showsIndicators: false) {+ HStack(spacing: 8) {+ if let ancestors = state.listing?.ancestors {+ ForEach(ancestors) { item in+ Button(item.name) { open(item.path) }.font(.caption)+ if item.id != ancestors.last?.id { Text("/").foregroundStyle(Palette.tertiary) }}- }- } else if let error {- Text(L10n.tr(error)).foregroundStyle(Palette.danger)- } else {- Spinner(size: 20).frame(maxWidth: .infinity)+ } else { Text(state.listing?.path ?? "Folders").font(.caption) }}}- .font(.body)- .padding(20)+ Button { if let parent = state.listing?.parent { open(parent) } } label: {+ Image(systemName: "arrow.up").frame(width: 32, height: 36)+ }.disabled(state.listing?.parent == nil || state.busy).accessibilityLabel("Parent folder")+ Button { animate { pathInput = state.listing?.path ?? ""; pathOpen.toggle() } } label: {+ Image(systemName: "pencil").frame(width: 32, height: 36)+ }.accessibilityLabel("Enter folder path")+ }.buttonStyle(PressScale())+ }++ private var recentRows: some View {+ let recent = (state.listing?.recent ?? []).filter { state.filter.isEmpty || $0.path.localizedCaseInsensitiveContains(state.filter) }+ return VStack(spacing: 4) {+ ForEach(recent) { item in+ Button { animate { state.selected = item.path } } label: {+ HStack(spacing: 12) {+ Image(systemName: "folder").foregroundStyle(Palette.secondary)+ VStack(alignment: .leading, spacing: 4) {+ Text(item.path.split(whereSeparator: { $0 == "/" || $0 == "\\" }).last.map(String.init) ?? item.path)+ .lineLimit(1)+ Text(item.path).font(.caption).foregroundStyle(Palette.secondary).lineLimit(1).truncationMode(.middle)+ }+ Spacer(minLength: 4)+ if state.selected == item.path { Image(systemName: "checkmark").font(.caption) }+ }.padding(12).frame(maxWidth: .infinity, alignment: .leading)+ .background(state.selected == item.path ? Palette.surface : .clear, in: RoundedRectangle(cornerRadius: 12))+ }.buttonStyle(PressScale()).accessibilityAddTraits(state.selected == item.path ? .isSelected : [])+ }+ if recent.isEmpty { empty(state.filter.isEmpty ? "Choose a folder to see it here next time." : "No matching folders.") }}- .scrollDismissesKeyboard(.interactively)- .background(Palette.background)- .task {- do {- let listing = try await model.listDirs(path)- self.listing = listing- onParent?(listing.parent)- } catch { self.error = error.localizedDescription }+ }++ private var directoryRows: some View {+ let dirs = (state.listing?.dirs ?? []).filter { state.filter.isEmpty || $0.name.localizedCaseInsensitiveContains(state.filter) }+ return VStack(spacing: 0) {+ ForEach(dirs) { dir in+ Button { open(dir.path) } label: {+ HStack(spacing: 12) {+ Image(systemName: dir.isGit ? "arrow.triangle.branch" : "folder").foregroundStyle(Palette.secondary)+ Text(dir.name).lineLimit(1)+ Spacer()+ Image(systemName: "chevron.right").font(.caption2).foregroundStyle(Palette.tertiary)+ }.padding(.vertical, 13).contentShape(Rectangle())+ }.buttonStyle(PressScale())+ }+ if state.listing != nil && dirs.isEmpty { empty(state.filter.isEmpty ? "No subfolders. You can use this folder." : "No matching folders.") }}}-}-/// A path's last folder, for `/` and Windows `\` paths alike.-private func folderName(_ path: String) -> String? {- path.split(whereSeparator: { $0 == "/" || $0 == "\\" }).last.map(String.init)+ private var footer: some View {+ HStack(spacing: 12) {+ VStack(alignment: .leading, spacing: 4) {+ Text(state.mode == .recent ? "Selected folder" : "Current folder").font(.caption2).foregroundStyle(Palette.secondary)+ Text(state.selected.isEmpty ? "Choose a folder" : state.selected).font(.caption).lineLimit(1).truncationMode(.middle)+ }.frame(maxWidth: .infinity, alignment: .leading)+ Button {+ Task { if let chosen = await state.confirm(model: model) { onPick(chosen) } }+ } label: {+ if state.saving { Spinner(size: 16) } else { Text("Use this folder").font(.subheadline) }+ }.buttonStyle(.primary)+ .disabled(state.selected.isEmpty || state.busy || state.saving || model.connection != .online)+ }.padding(20).background(Palette.surface)+ }++ private func empty(_ text: String) -> some View {+ Text(L10n.tr(text)).font(.subheadline).foregroundStyle(Palette.secondary).frame(maxWidth: .infinity).padding(.vertical, 24)+ }+ private func animate(_ action: () -> Void) { withAnimation(Motion.reduced(Motion.layout, reduceMotion), action) }+ private func open(_ next: String?) {+ animate { state.mode = .browse; state.selected = ""; state.filter = ""; pathOpen = false; path = next; request += 1 }+ }+ private func openPath() { let next = pathInput.trimmingCharacters(in: .whitespacesAndNewlines); if !next.isEmpty { open(next) } }}diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/WorkspacePickerState.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/WorkspacePickerState.swiftnew file mode 100644index 00000000..8979eea1--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/WorkspacePickerState.swift@@ -0,0 +1,52 @@+import CodyncKit+import SwiftUI++/// Request lifetime belongs to the picker: changing folders invalidates earlier responses.+@MainActor @Observable+final class WorkspacePickerState {+ enum Mode { case recent, browse }+ var mode = Mode.recent+ var listing: DirListing?+ var selected = ""+ var filter = ""+ var error: String?+ var busy = false+ var saving = false+ private var generation = 0++ func load(_ path: String?, model: BotStore) async {+ generation += 1+ let request = generation+ busy = true+ error = nil+ listing = nil+ do {+ let result = try await model.listDirs(path)+ guard request == generation, !Task.isCancelled else { return }+ listing = result+ if mode == .browse { selected = result.path }+ } catch {+ guard request == generation, !Task.isCancelled else { return }+ self.error = error.localizedDescription+ }+ if request == generation { busy = false }+ }++ func confirm(model: BotStore) async -> String? {+ guard !selected.isEmpty, !busy, !saving else { return nil }+ saving = true+ let request = generation+ error = nil+ defer { saving = false }+ do {+ let path: String+ if listing?.recent != nil { path = try await model.selectWorkspace(selected) }+ else { path = try await model.listDirs(selected).path }+ guard request == generation, !Task.isCancelled else { return nil }+ return path+ } catch {+ self.error = error.localizedDescription+ return nil+ }+ }+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Call/CallActivity.swift b/apps/ios/Kit/Sources/CodyncUI/Call/CallActivity.swiftindex 2ffc149a..b22b919c 100644--- a/apps/ios/Kit/Sources/CodyncUI/Call/CallActivity.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Call/CallActivity.swift@@ -33,6 +33,8 @@ public final class CallActivity {init(bot: Bot, computerId: ComputerID, link: URL?, toggleMute: @escaping @MainActor () -> Void = {},hangUp: @escaping @MainActor () -> Void = {}) {attributes = BotActivityAttributes(bot: bot, computerId: computerId, link: link)+ do { try bot.customIcon?.cacheForActivity(context: attributes.iconContext) }+ catch { log.error("Cannot cache call icon: \(error.localizedDescription)") }self.toggleMute = toggleMuteself.hangUp = hangUpSelf.calls[bot.id] = selfdiff --git a/apps/ios/Kit/Sources/CodyncUI/CustomIconAccount.swift b/apps/ios/Kit/Sources/CodyncUI/CustomIconAccount.swiftnew file mode 100644index 00000000..9b61d7af--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/CustomIconAccount.swift@@ -0,0 +1,24 @@+import SwiftUI++/// App-owned authentication intents used by the shared icon editor.+public struct CustomIconAccount: Sendable {+ public let signedIn: Bool+ public let loading: Bool+ public let error: String?+ let signInApple: @MainActor @Sendable () -> Void+ let signInGoogle: @MainActor @Sendable () -> Void++ public init(signedIn: Bool, loading: Bool, error: String?,+ signInApple: @escaping @MainActor @Sendable () -> Void,+ signInGoogle: @escaping @MainActor @Sendable () -> Void) {+ self.signedIn = signedIn+ self.loading = loading+ self.error = error+ self.signInApple = signInApple+ self.signInGoogle = signInGoogle+ }+}++public extension EnvironmentValues {+ @Entry var customIconAccount: CustomIconAccount?+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Marketplace/AgentIcon.swift b/apps/ios/Kit/Sources/CodyncUI/Marketplace/AgentIcon.swiftindex 6e16a509..9aea77aa 100644--- a/apps/ios/Kit/Sources/CodyncUI/Marketplace/AgentIcon.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Marketplace/AgentIcon.swift@@ -5,6 +5,7 @@ import UIKit/// A coding agent's logo, by ACP registry id or by Codync's id for agents outside the registry,/// tinted like text; a terminal glyph otherwise.public struct AgentIcon: View {+ @Environment(BotStore.self) private var storelet registry: String?let size: CGFloat@@ -15,7 +16,9 @@ public struct AgentIcon: View {public var body: some View {Group {- if let name = registry.map({ "agent-\($0)" }), Self.exists(name) {+ if let custom = customIcon, custom.image != nil {+ CustomIconView(icon: custom, size: size)+ } else if let name = registry.map({ "agent-\($0)" }), Self.exists(name) {Image(name, bundle: .module).resizable().scaledToFit()} else {Image(systemName: "terminal").resizable().scaledToFit().padding(size * 0.1)@@ -25,6 +28,12 @@ public struct AgentIcon: View {.foregroundStyle(tint)}+ private var customIcon: CustomIcon? {+ guard let registry else { return nil }+ let backend = store.hello?.backends.first { $0.id == registry || $0.registry == registry }+ return store.icons["agent:\(backend?.id ?? registry)"]+ }+/// Registry logos are one-color; paint the ones with a known brand color in it.private var tint: AnyShapeStyle {switch registry {diff --git a/apps/ios/Kit/Sources/CodyncUI/Marketplace/AgentSheet.swift b/apps/ios/Kit/Sources/CodyncUI/Marketplace/AgentSheet.swiftindex 22393638..7351a056 100644--- a/apps/ios/Kit/Sources/CodyncUI/Marketplace/AgentSheet.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Marketplace/AgentSheet.swift@@ -102,6 +102,7 @@ struct AgentSheet: View {private var overview: some View {CardForm {CardSection {+ CustomIconEditor(target: "agent:\(backend.id)")HStack(spacing: 14) {AgentIcon(registry: backend.registry ?? backend.id, size: 30).frame(width: 52, height: 52)diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swiftindex c51eb184..c1ad82a0 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift@@ -363,6 +363,10 @@ extension BotStore {return bot}+ public func selectWorkspace(_ path: String) async throws -> String {+ try await ready().selectWorkspace(path)+ }+public func listDirs(_ path: String?) async throws -> DirListing {try await ready().listDirs(path)}diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Cache.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Cache.swiftindex 49c47570..83a7df19 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Cache.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Cache.swift@@ -9,6 +9,7 @@ extension BotStore {var rev: Int64var bots: [Bot]var entries: [Entry]+ var icons: [String: CustomIcon]?}static let appBuild = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "0"@@ -28,6 +29,7 @@ extension BotStore {rev = cache.revbots = Dictionary(cache.bots.map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })entries = Dictionary(grouping: cache.entries, by: \.botId)+ applyIcons(cache.icons ?? [:])}func scheduleSave() {@@ -47,7 +49,8 @@ extension BotStore {list.filter { !$0.id.hasPrefix("local-") }.suffix(200)+ list.filter { $0.id.hasPrefix("local-") && ["waiting", "delivering", "failed"].contains($0.data.status) }}- let cache = Cache(stamp: "\(Self.appBuild)/\(hello?.version ?? "")", hostId: hostId, rev: rev, bots: Array(bots.values), entries: kept)+ let cachedBots = bots.values.map { bot in var bot = bot; bot.customIcon = nil; return bot }+ let cache = Cache(stamp: "\(Self.appBuild)/\(hello?.version ?? "")", hostId: hostId, rev: rev, bots: cachedBots, entries: kept, icons: icons)if let data = try? JSONEncoder().encode(cache) {try? data.write(to: cacheURL, options: .atomic)}diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Icons.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Icons.swiftnew file mode 100644index 00000000..14ce83f3--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Icons.swift@@ -0,0 +1,26 @@+import CodyncKit+import Foundation+import os++extension BotStore {+ func applyIcons(_ updated: [String: CustomIcon], revision: Int64 = 0) {+ guard revision >= iconsRevision else { return }+ iconsRevision = revision+ guard icons != updated else { return }+ for target in Set(icons.keys).union(updated.keys) where target.hasPrefix("bot:") && icons[target] != updated[target] {+ do {+ try ActivityIconCache.writeReference(updated[target], computerId: computer.id, botId: String(target.dropFirst(4)), context: storage.id)+ } catch { Logger(subsystem: "com.pokai.Codync", category: "CustomIcon").error("Cannot cache activity icon: \(error.localizedDescription)") }+ }+ do { try ActivityIconCache.prune(context: storage.id) }+ catch { Logger(subsystem: "com.pokai.Codync", category: "CustomIcon").error("Cannot prune activity icons: \(error.localizedDescription)") }+ icons = updated+ for (id, var bot) in bots {+ guard bot.customIcon != updated["bot:\(id)"] else { continue }+ bot.customIcon = updated["bot:\(id)"]+ bots[id] = bot+ onBotUpdated?(bot)+ }+ onRosterChanged?()+ }+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swiftindex a316b88e..669b65ac 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift@@ -44,6 +44,8 @@ extension BotStore {/// Asked on every (re)connect: the host may have been updated while this app was away.private func refreshHello(_ client: HostClient) async throws {+ iconsEpoch &+= 1+ let epoch = iconsEpochlet h: Hellodo {h = try await client.hello()@@ -59,7 +61,10 @@ extension BotStore {}guard !Task.isCancelled, !retired else { return }// hello first: whatever the version change shows (notices, reminders) reads it.+ guard epoch == iconsEpoch else { return }+ iconsRevision = -1hello = h+ applyIcons(h.icons ?? [:], revision: h.iconsRevision ?? 0)noteHostVersion(HostVersion(version: h.version, minApp: h.minApp))}@@ -79,6 +84,8 @@ extension BotStore {private func apply(_ event: HostEvent) {switch event {+ case let .icons(icons, revision):+ applyIcons(icons, revision: revision)case let .hello(id, hostRev, newUsage, newScreen, newNetwork):if let hostId, hostId != id {// Different host database: start over.@@ -93,7 +100,8 @@ extension BotStore {windowFloors = requestedSince > 0 && !hostRewound ? loadedFloors() : [:]catchUpRev = hostRevbump(rev)- case let .bot(bot):+ case .bot(var bot):+ bot.customIcon = icons["bot:\(bot.id)"]bots[bot.id] = botbump(bot.rev)onBotUpdated?(bot)@@ -148,6 +156,7 @@ extension BotStore {}private func resetMirror() {+ iconsRevision = -1composerDrafts = [:]persistComposerDrafts()bots = [:]diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swiftindex 7f184d90..86c32935 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift@@ -21,6 +21,9 @@ public enum SendProgress: Sendable {@MainActor@Observablepublic final class BotStore {+ public internal(set) var icons: [String: CustomIcon] = [:]+ var iconsRevision: Int64 = -1+ var iconsEpoch: UInt64 = 0public enum Connection: Equatable {case unpairedcase connectingdiff --git a/apps/ios/Kit/Sources/CodyncUI/Store/IconEditor.swift b/apps/ios/Kit/Sources/CodyncUI/Store/IconEditor.swiftnew file mode 100644index 00000000..2be7d363--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Store/IconEditor.swift@@ -0,0 +1,51 @@+import CodyncKit+import Foundation+import Observation++@MainActor @Observable+final class IconEditor {+ var busy = false+ var error: String?++ struct Change: Encodable {+ var target: String+ var data: String?+ var url: String?+ var tinted: Bool?+ var remove: Bool?+ }++ func save(_ change: Change, store: BotStore, file: URL? = nil) async {+ guard !busy else { return }+ busy = true+ error = nil+ defer { busy = false }+ do {+ guard let client = store.client, store.connection == .online else {+ throw HostError.unreachable+ }+ let epoch = store.iconsEpoch+ var change = change+ if let file { change.data = try await Self.read(file).base64EncodedString() }+ struct Reply: Decodable { var icons: [String: CustomIcon]; var iconsRevision: Int64 }+ let reply: Reply = try await client.call("setIcon", change, timeout: 60)+ guard epoch == store.iconsEpoch else { return }+ store.applyIcons(reply.icons, revision: reply.iconsRevision)+ store.scheduleSave()+ } catch { self.error = error.localizedDescription }+ }++ nonisolated private static func read(_ url: URL) async throws -> Data {+ try await Task.detached {+ let scoped = url.startAccessingSecurityScopedResource()+ defer { if scoped { url.stopAccessingSecurityScopedResource() } }+ let handle = try FileHandle(forReadingFrom: url)+ defer { try? handle.close() }+ let data = try handle.read(upToCount: 5 * 1024 * 1024 + 1) ?? Data()+ guard !data.isEmpty, data.count <= 5 * 1024 * 1024 else {+ throw NSError(domain: "CustomIcon", code: 1, userInfo: [NSLocalizedDescriptionKey: "Choose an image up to 5 MiB."])+ }+ return data+ }.value+ }+}diff --git a/apps/ios/Kit/Tests/CodyncKitTests/CustomIconTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/CustomIconTests.swiftnew file mode 100644index 00000000..3e8ed084--- /dev/null+++ b/apps/ios/Kit/Tests/CodyncKitTests/CustomIconTests.swift@@ -0,0 +1,31 @@+import CodyncKit+import Foundation+import Testing++@Test func customIconsUseStaticLocalPngNames() throws {+ let icon = try JSONDecoder().decode(CustomIcon.self, from: Data(#"{"dataUrl":"data:image/png;base64,iVBORw0KGgo=","tinted":false}"#.utf8))+ #expect(icon.pngData?.count == 8)+ #expect(icon.filename?.count == 68)+ #expect(icon.filename?.hasSuffix(".png") == true)+ var bot = try JSONDecoder().decode(Bot.self, from: Data(#"{"id":"b"}"#.utf8))+ #expect(BotActivityAttributes(bot: bot, computerId: "test").customIconName == nil)+ bot.customIcon = icon+ let attributes = BotActivityAttributes(bot: bot, computerId: "test")+ #expect(attributes.customIconName == icon.filename)+ #expect(attributes.customIconTinted == false)+ #expect(try JSONEncoder().encode(attributes).count < 1024)+}++@Test func remoteAndSvgDataAreNotRenderedAsCustomIcons() throws {+ for value in ["https://example.com/image.png", "data:image/svg+xml,<svg/>", "data:image/png;base64,abcd"] {+ let data = try JSONSerialization.data(withJSONObject: ["dataUrl": value, "tinted": false])+ let icon = try JSONDecoder().decode(CustomIcon.self, from: data)+ #expect(icon.pngData == nil)+ }+}++@Test func iconEventsRetainColorMode() throws {+ let data = Data(#"{"type":"icons","icons":{"bot:b":{"dataUrl":"data:image/png;base64,iVBORw0KGgo=","tinted":true}}}"#.utf8)+ guard case let .icons(icons, _) = HostClient.parseEvent(data) else { Issue.record("Expected icons event"); return }+ #expect(icons["bot:b"]?.tinted == true)+}diff --git a/apps/ios/NotificationService/NotificationService.swift b/apps/ios/NotificationService/NotificationService.swiftindex ce995917..74ac337d 100644--- a/apps/ios/NotificationService/NotificationService.swift+++ b/apps/ios/NotificationService/NotificationService.swift@@ -35,7 +35,11 @@ final class NotificationService: UNNotificationServiceExtension {private static func fromBot(_ content: UNMutableNotificationContent, alert: PushAlert, botId: String?, computerId: String, ctx: String) -> UNNotificationContent {let store = SharedStore.activeContextlet snapshot = store.id == ctx ? store.bots.filter { $0.computerId == computerId }.map(\.bot) : []- let bots = (alert.faces ?? []) + snapshot+ let bots = (alert.faces ?? []).map { face in+ var face = face+ face.customIcon = snapshot.first { $0.id == face.id }?.customIcon+ return face+ } + snapshotguard let botId, let chat = bots.first(where: { $0.id == botId }) else { return content }let members = chat.members.compactMap { id in bots.first { $0.id == id } }let conversation = "\(computerId)/\(chat.id)"diff --git a/apps/ios/Views/AccountSwitcherView.swift b/apps/ios/Views/AccountSwitcherView.swiftindex df2f5acf..111d484a 100644--- a/apps/ios/Views/AccountSwitcherView.swift+++ b/apps/ios/Views/AccountSwitcherView.swift@@ -8,7 +8,11 @@ struct AccountSwitcherButton: View {var body: some View {Button { account.showSwitcher = true } label: {HStack(spacing: 4) {- AccountAvatar(url: account.avatarURL, email: account.email, size: 30)+ if account.isBusy || !account.isReady {+ Spinner(size: 18).frame(width: 30, height: 30)+ } else {+ AccountAvatar(url: account.avatarURL, email: account.email, size: 30)+ }Image(systemName: "chevron.down").font(.system(size: 10, weight: .semibold)).foregroundStyle(Palette.secondary)diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.mdindex 619e32e3..ae0fc741 100644--- a/apps/ios/WhatsNew.md+++ b/apps/ios/WhatsNew.md@@ -7,21 +7,18 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o-->## 2.33.2-### zh-Hant+- 可上傳或貼上網址設定 bot 與 agent 圖示,支援原色、單色與離線快取;自訂圖片維持靜態。+- 自訂圖片需要登入帳號;登入載入時只顯示進度。電腦選單新增裝置圖示。+- 選擇工作資料夾時可直接使用最近紀錄、貼上路徑,並在底部確認選擇。- 即時動態與動態島的設定頁會說明兩者同步開啟或關閉。- 電腦的推送通知設定會顯示系統權限狀態;未允許通知時,可直接前往開啟權限。- 語音輸入尚未設定 API key 時,會直接開啟語音設定。### en-US+- Upload images or paste URLs for bot and agent icons, with original colors, tinting and offline caching. Custom images stay still.+- Custom images require sign-in. Account loading shows progress, and computer menus include device icons.+- Choose workspaces from recent folders, paste a path, and confirm your selection at the bottom.- Live Activity and Dynamic Island settings explain that both turn on and off together.- Computer push settings show when notification permission is missing and help you enable it.- Dictation opens voice settings when your provider API key is missing.--## 2.33.1--### zh-Hant-- 選專案資料夾時,返回鍵可以往上走到家目錄以外的資料夾,Windows 電腦還能切換磁碟;連結(symlink)的資料夾也會出現在清單中。--### en-US-- When you choose a project folder, Back climbs above your home folder and, on a Windows computer, to its other drives; linked folders now show up too.diff --git a/apps/ios/Widgets/CallLiveActivity.swift b/apps/ios/Widgets/CallLiveActivity.swiftindex 23e99db8..357d0091 100644--- a/apps/ios/Widgets/CallLiveActivity.swift+++ b/apps/ios/Widgets/CallLiveActivity.swift@@ -13,8 +13,12 @@ struct CallActivityViews {private var since: Date { context.state.callStartedAt ?? .now }private var muted: Bool { context.state.callMuted == true }- func avatar(_ size: CGFloat) -> some View {- ActivityAvatar(shape: context.attributes.avatarShape, color: context.attributes.avatarColor, state: state, size: size)+ @ViewBuilder func avatar(_ size: CGFloat) -> some View {+ if context.attributes.currentCustomIconName != nil {+ CustomActivityIcon(attributes: context.attributes, size: size)+ } else {+ ActivityAvatar(shape: context.attributes.avatarShape, color: context.attributes.avatarColor, state: state, size: size)+ }}func timer(size: CGFloat) -> some View {diff --git a/apps/ios/Widgets/CodyncWidgets.swift b/apps/ios/Widgets/CodyncWidgets.swiftindex af68fe16..8a7a1f72 100644--- a/apps/ios/Widgets/CodyncWidgets.swift+++ b/apps/ios/Widgets/CodyncWidgets.swift@@ -665,7 +665,9 @@ struct BotLiveActivity: Widget {@ViewBuilderprivate func indicator(_ context: ActivityViewContext<BotActivityAttributes>, state: BotActivityPresentation, size: CGFloat) -> some View {ZStack {- if state.phase == .working {+ if context.attributes.currentCustomIconName != nil {+ BotActivityIndicator(state: state, size: size)+ } else if state.phase == .working {WorkingOrb(since: context.state.startedAt ?? .now, color: state.tint, size: size).transition(.opacity)} else {@@ -680,7 +682,9 @@ struct BotLiveActivity: Widget {@ViewBuilderprivate func avatar(_ context: ActivityViewContext<BotActivityAttributes>, state: BotActivityPresentation, size: CGFloat) -> some View {ZStack {- if state.phase == .working {+ if context.attributes.currentCustomIconName != nil {+ CustomActivityIcon(attributes: context.attributes, size: size)+ } else if state.phase == .working {WorkingBotFace(shape: context.attributes.avatarShape, color: context.attributes.avatarColor,since: context.state.startedAt ?? .now, size: size).transition(.opacity)diff --git a/apps/ios/Widgets/CustomActivityIcon.swift b/apps/ios/Widgets/CustomActivityIcon.swiftnew file mode 100644index 00000000..15a43582--- /dev/null+++ b/apps/ios/Widgets/CustomActivityIcon.swift@@ -0,0 +1,18 @@+import CodyncKit+import SwiftUI++/// A missing custom asset also falls back to a still frame, never the timer/sprite loop.+struct CustomActivityIcon: View {+ let attributes: BotActivityAttributes+ let size: CGFloat++ var body: some View {+ if let filename = attributes.currentCustomIconName, let image = ActivityIconCache.image(filename: filename, context: attributes.iconContext) {+ Image(uiImage: image).resizable().renderingMode(attributes.currentCustomIconTinted ? .template : .original)+ .scaledToFit().foregroundStyle(AvatarPalette.color(attributes.avatarColor))+ .frame(width: size, height: size)+ } else {+ CharacterAvatar(shape: attributes.avatarShape, color: attributes.avatarColor, size: size, still: true)+ }+ }+}diff --git a/cloud/src/index.ts b/cloud/src/index.tsindex f8420a83..0ba2116c 100644--- a/cloud/src/index.ts+++ b/cloud/src/index.ts@@ -6,10 +6,14 @@ import * as api from "./api";import { ApiError, type Ctx } from "./api";import type { ComputerRelay } from "./relay";import { nudgeReleaseGate } from "./release-gate";+import { icon, MAX_ICON_BYTES } from "./routes/icons";+import { readBody } from "./request-body";export { ComputerRelay } from "./relay";export interface Env {+ ICONS?: R2Bucket;+ ICON_LIMITER?: RateLimit;DB: D1Database;RELAY: DurableObjectNamespace<ComputerRelay>;/** Workers Rate Limiting binding for new computer registrations. */@@ -43,6 +47,9 @@ const RELEASE_GATE_CRON = "*/5 * * * *";const ID = "([A-Za-z0-9_-]{1,64})";const routes: [string, RegExp, Handler][] = [+ ["PUT", /^\/v1\/host\/icons\/([^/]+)$/, icon],+ ["GET", /^\/v1\/host\/icons\/([^/]+)$/, icon],+ ["DELETE", /^\/v1\/host\/icons\/([^/]+)$/, icon],["GET", /^\/v1\/health$/, api.health],["GET", /^\/v1\/oauth\/callback$/, api.oauthCallback],["GET", /^\/v1\/oauth\/callback\/dev$/, api.oauthDevCallback],@@ -90,9 +97,7 @@ export default {const m = pattern.exec(url.pathname);if (!m || req.method !== method) continue;// Every route takes small bodies; refuse a big one before reading it.- if (Number(req.headers.get("content-length") ?? 0) > MAX_REQUEST) throw new ApiError("tooLarge");- const raw = new Uint8Array(await req.arrayBuffer());- if (raw.length > MAX_REQUEST) throw new ApiError("tooLarge");+ const raw = await readBody(req, handler === icon ? MAX_ICON_BYTES : MAX_REQUEST);const out = await handler({ req, env, exec, url, raw, now: Date.now() }, m.slice(1));return out instanceof Response ? out : Response.json(out);}diff --git a/cloud/src/request-body.ts b/cloud/src/request-body.tsnew file mode 100644index 00000000..34f7aeb4--- /dev/null+++ b/cloud/src/request-body.ts@@ -0,0 +1,31 @@+import { ApiError } from "./routes/common";++/** Enforce limits while reading, including requests without Content-Length. */+export async function readBody(req: Request, limit: number): Promise<Uint8Array> {+ if (Number(req.headers.get("content-length") ?? 0) > limit) throw new ApiError("tooLarge");+ if (!req.body) return new Uint8Array();+ const reader = req.body.getReader();+ const chunks: Uint8Array[] = [];+ let length = 0;+ try {+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ length += value.length;+ if (length > limit) {+ await reader.cancel();+ throw new ApiError("tooLarge");+ }+ chunks.push(value);+ }+ } finally {+ reader.releaseLock();+ }+ const result = new Uint8Array(length);+ let offset = 0;+ for (const chunk of chunks) {+ result.set(chunk, offset);+ offset += chunk.length;+ }+ return result;+}diff --git a/cloud/src/routes/icons.ts b/cloud/src/routes/icons.tsnew file mode 100644index 00000000..dfee6acf--- /dev/null+++ b/cloud/src/routes/icons.ts@@ -0,0 +1,46 @@+// Private, host-encrypted icon storage. Fixed slots bound storage to 8 MiB per computer;+// neither filenames, image URLs nor encryption keys are sent to the cloud.+import { ApiError, host, type Ctx } from "./common";++export const MAX_ICON_BYTES = 64 * 1024;+const ICON_SLOTS = 128;++export async function deleteComputerIcons(env: Ctx["env"], computerId: string): Promise<void> {+ if (env.ICONS) await env.ICONS.delete(Array.from({ length: ICON_SLOTS }, (_, slot) => `${computerId}/${slot}`));+}++export async function icon(c: Ctx, [slot]: string[]): Promise<Response> {+ if (!/^(0|[1-9]\d{0,2})$/.test(slot) || Number(slot) >= ICON_SLOTS) throw new ApiError("badRequest");+ const computer = await host(c);+ if (!computer.owner_user_id) throw new ApiError("forbidden", "Sign in and claim this computer to store custom icons");+ const account = await c.env.DB.prepare("SELECT status FROM accounts WHERE user_id = ?")+ .bind(computer.owner_user_id).first<{ status: string }>();+ if (account?.status !== "active") throw new ApiError("forbidden");+ if (!c.env.ICONS) throw new ApiError("unavailable", "Icon storage is not configured", 503);+ if (c.req.method !== "GET" && c.env.ICON_LIMITER &&+ !(await c.env.ICON_LIMITER.limit({ key: computer.owner_user_id })).success) throw new ApiError("rateLimited");+ const key = `${computer.id}/${slot}`;+ const headers = { "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" };+ if (c.req.method === "PUT") {+ if (c.raw.length > MAX_ICON_BYTES) throw new ApiError("tooLarge");+ // Version byte + nonce + AEAD tag. Only the host can validate the encrypted image.+ if (c.raw.length < 30 || c.raw[0] !== 1) throw new ApiError("badRequest", "Invalid encrypted icon");+ await c.env.ICONS.put(key, c.raw, { httpMetadata: { contentType: "application/octet-stream" } });+ // Account deletion may race the upload after authentication; don't leave that image behind.+ const stillOwned = await c.env.DB.prepare(+ "SELECT 1 FROM computers c JOIN accounts a ON a.user_id = c.owner_user_id WHERE c.id = ? AND c.owner_user_id = ? AND c.status = 'active' AND a.status = 'active'",+ ).bind(computer.id, computer.owner_user_id).first();+ if (!stillOwned) {+ await c.env.ICONS.delete(key);+ throw new ApiError("forbidden");+ }+ return new Response(null, { status: 204, headers });+ }+ if (c.req.method === "DELETE") {+ await c.env.ICONS.delete(key);+ return new Response(null, { status: 204, headers });+ }+ const object = await c.env.ICONS.get(key);+ if (!object) throw new ApiError("notFound");+ return new Response(object.body, { headers: { ...headers, "Content-Type": "application/octet-stream" } });+}diff --git a/cloud/src/routes/webhooks.ts b/cloud/src/routes/webhooks.tsindex 554cbc2b..b6d7dcec 100644--- a/cloud/src/routes/webhooks.ts+++ b/cloud/src/routes/webhooks.ts@@ -3,6 +3,7 @@import { Webhook } from "svix";import type { Env } from "../index";import { ApiError, audit, notify, revokeGrants, type Ctx } from "./common";+import { deleteComputerIcons } from "./icons";export async function clerkWebhook(c: Ctx) {if (!c.env.CLERK_WEBHOOK_SECRET) throw new ApiError("internal", "Webhook secret not configured");@@ -40,6 +41,8 @@ async function deleteAccount(env: Env, userId: string, now: number): Promise<voinow,);const owned = await env.DB.prepare("SELECT id FROM computers WHERE owner_user_id = ?").bind(userId).all<{ id: string }>();+ // Revoke access first. R2 availability must never keep a deleted account's sockets alive.+ // Retain computer ownership until storage cleanup succeeds so retries can find every slot.await env.DB.batch([...stmts,env.DB.prepare(@@ -51,12 +54,12 @@ async function deleteAccount(env: Env, userId: string, now: number): Promise<voi`UPDATE access_requests SET status = 'cancelled', decided_at = ?1WHERE status = 'pending' AND (user_id = ?2 OR computer_id IN (SELECT id FROM computers WHERE owner_user_id = ?2))`,).bind(now, userId),- env.DB.prepare("UPDATE computers SET owner_user_id = NULL, claimed_at = NULL, updated_at = ? WHERE owner_user_id = ?").bind(- now,- userId,- ),audit(env, "system", "account.delete", userId, "ok", now),]);const computers = new Set([...blocks.keys(), ...owned.results.map((r) => r.id)]);await Promise.all([...computers].map((id) => notify(env, id, blocks.get(id))));+ for (const computer of owned.results) await deleteComputerIcons(env, computer.id);+ await env.DB.prepare("UPDATE computers SET owner_user_id = NULL, claimed_at = NULL, updated_at = ? WHERE owner_user_id = ?")+ .bind(now, userId).run();+ await Promise.all(owned.results.map(({ id }) => notify(env, id)));}diff --git a/cloud/test/api.test.ts b/cloud/test/api.test.tsindex edaa8ecb..05b76cde 100644--- a/cloud/test/api.test.ts+++ b/cloud/test/api.test.ts@@ -504,6 +504,32 @@ describe("Clerk webhook", () => {});};+ it("revokes access before failed R2 cleanup and retries the retained ownership", async () => {+ const u = await newUser();+ const host = await newHost();+ await claim(u, host);+ await grantAccess(u, host);+ const id = `msg_${crypto.randomUUID()}`;+ const payload = { type: "user.deleted", data: { id: u.userId } };+ const body = JSON.stringify(payload);+ const now = new Date();+ const response = await worker.fetch(new Request("https://cloud.test/v1/webhooks/clerk", {+ method: "POST", body,+ headers: {+ "svix-id": id,+ "svix-timestamp": String(Math.floor(now.getTime() / 1000)),+ "svix-signature": new Webhook(env.CLERK_WEBHOOK_SECRET!).sign(id, now, body),+ },+ }), { ...env, ICONS: { delete: async () => { throw new Error("R2 unavailable") } } as unknown as R2Bucket }, {} as ExecutionContext);+ expect(response.status).toBe(500);+ const state = (await call("GET", "/v1/host/state", { key: host.sign })).body;+ expect(state.grants).toEqual([]);+ expect((await env.DB.prepare("SELECT COUNT(*) AS n FROM devices WHERE owner_user_id=? AND revoked_at IS NULL").bind(u.userId).first<{n:number}>())?.n).toBe(0);+ expect((await env.DB.prepare("SELECT owner_user_id FROM computers WHERE id=?").bind(host.cid).first<{owner_user_id:string}>())?.owner_user_id).toBe(u.userId);+ expect((await deliver(id, payload)).status).toBe(200);+ expect((await call("GET", "/v1/host/state", { key: host.sign })).body.owner).toBeNull();+ });+it("rejects bad signatures", async () => {const r = await deliver("msg_bad", { type: "user.deleted", data: { id: "x" } }, `whsec_${btoa("0".repeat(24))}`);expect(r.status).toBe(401);diff --git a/cloud/test/e2e/icons.ts b/cloud/test/e2e/icons.tsnew file mode 100644index 00000000..e0a255f7--- /dev/null+++ b/cloud/test/e2e/icons.ts@@ -0,0 +1,27 @@+import { strict as assert } from 'node:assert';+import type { Json } from './phone.ts';++type Call = (method: string, body?: unknown) => Promise<Json>;++/** Real host importer/encryption against Wrangler's R2 binding, over the encrypted phone channel. */+export async function exerciseIcons(call: Call, target: string): Promise<string> {+ const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="red"/></svg>';+ const uploaded = await call('setIcon', { target, data: Buffer.from(svg).toString('base64'), tinted: false });+ const png = uploaded.icons[target].dataUrl as string;+ assert.match(png, /^data:image\/png;base64,/);+ assert.equal(uploaded.icons[target].tinted, false);+ // A valid PNG with trailing padding exercises authenticated inbound chunking above 1 MiB.+ const padded = Buffer.concat([Buffer.from(png.split(',')[1], 'base64'), Buffer.alloc(1100 * 1024)]);+ const large = await call('setIcon', { target, data: padded.toString('base64') });+ assert.equal(large.icons[target].dataUrl, png);+ const tinted = await call('setIcon', { target, tinted: true });+ assert.equal(tinted.icons[target].dataUrl, png);+ assert.ok(tinted.iconsRevision > large.iconsRevision, "snapshot revisions advance for color-only changes");+ assert.equal(tinted.icons[target].tinted, true);+ await assert.rejects(call('setIcon', { target, data: Buffer.from('bad image').toString('base64') }));+ assert.equal((await call('hello')).icons[target].dataUrl, png, 'failed import preserves the local image');+ assert.equal((await call('setIcon', { target, remove: true })).icons[target], undefined);+ await call('setIcon', { target, data: Buffer.from(svg).toString('base64') });+ console.log(' ✓ icon upload, large encrypted request, tint, failed replacement, reset and re-upload');+ return png;+}diff --git a/cloud/test/e2e/phone.ts b/cloud/test/e2e/phone.tsindex f50aa0a4..6c21c229 100644--- a/cloud/test/e2e/phone.ts+++ b/cloud/test/e2e/phone.ts@@ -79,7 +79,7 @@ export interface PairingInfo {export function parsePairing(link: string): PairingInfo {const u = new URL(link);const q = u.searchParams;- if (u.protocol !== "codync:" || q.get("v") !== "3") throw new Error(`not a v3 pairing link: ${link}`);+ if (!["codync:", "codync-dev:"].includes(u.protocol) || q.get("v") !== "3") throw new Error(`not a v3 pairing link: ${link}`);const signKey = ref.unb64url(q.get("sk") ?? "");if (ref.computerId(signKey) !== q.get("id")) throw new Error("pairing link id doesn't match sk");return {diff --git a/cloud/test/e2e/relay.e2e.ts b/cloud/test/e2e/relay.e2e.tsindex d46f856e..da91b02b 100644--- a/cloud/test/e2e/relay.e2e.ts+++ b/cloud/test/e2e/relay.e2e.ts@@ -13,6 +13,7 @@ import { networkInterfaces, tmpdir } from "node:os";import { join } from "node:path";import { fileURLToPath } from "node:url";import * as ref from "../ref.ts";+import { exerciseIcons } from "./icons.ts";import { Channel, FakePhone, parsePairing, waitFor, type Json, type PairingInfo, type Wire } from "./phone.ts";const CLOUD_DIR = fileURLToPath(new URL("../..", import.meta.url));@@ -170,9 +171,23 @@ async function main() {let ch = await phone.relay(CLOUD, computerId, pairing.signKey);const hello = await ch.call("hello", {});check(hello.computerId === computerId && hello.boxKey === ref.b64url(pairing.boxKey), "inner hello returns computerId and boxKey");- for (let i = 0; i < 20; i++) await ch.call("sync", { since: 0 });+ for (let i = 0; i < 20; i++) await ch.call("hello", {});check(true, "more than 16 messages on the regular link");+ if (process.env.CODYNC_E2E_ICONS_ONLY === "1") {+ const userId = "user_icons_e2e";+ const token = await clerkToken(userId);+ const claim = await cloud("POST", "/v1/claims", { token });+ const signed = await loopback("claimSign", { claimId: claim.body.claimId, nonce: claim.body.nonce, userId });+ check((await cloud("POST", `/v1/claims/${claim.body.claimId}/complete`, { token, body: signed })).status === 200, "icon test computer claimed");+ await waitFor("icon host sees its owner", async () => (await loopback("cloudStatus")).owner?.userId === userId || undefined);+ const png = await exerciseIcons((method, body) => ch.call(method, body, 60_000), "agent:claude");+ await stop(host!);+ await startHost();+ check((await loopback("hello")).icons["agent:claude"].dataUrl === png, "icon remains cached after host restart");+ return;+ }+const bot = (await ch.call("createBot", { name: "Tester", backend: "custom", command: `python3 '${FAKE_AGENT}'`, cwd: tmp, permission: "ask" })).bot.id;ch.subscribe("events", { since: 0, client: "ios" });await ch.call("send", { botId: bot, text: "go", clientNonce: "e2e-1" });@@ -280,6 +295,8 @@ async function main() {const ch2 = await phone2.relay(CLOUD, computerId, ref.unb64url(listed.signKey));check((await ch2.call("hello", {})).computerId === computerId, "phone 2 connected through the relay");+ const cachedIcon = await exerciseIcons((method, body) => ch2.call(method, body, 60_000), `bot:${bot}`);+const started = Date.now();await cloud("DELETE", `/v1/computers/${computerId}/grants/${approved.grantId}`, { token });const code = await ch2.wire.closed(5000);@@ -289,6 +306,7 @@ async function main() {await startHost();await waitFor("host back online", () => computerOnline(computerId), 20_000);check(await refused(phone2.relayWire(CLOUD, computerId)), "still refused after the host reconnects");+ check((await loopback("hello")).icons[`bot:${bot}`].dataUrl === cachedIcon, "icon survives a real host restart in its local cache");step("6b. a grant injected into D1 is ignored by the host");const phone3 = new FakePhone();diff --git a/cloud/test/icons.test.ts b/cloud/test/icons.test.tsnew file mode 100644index 00000000..eeebbb0e--- /dev/null+++ b/cloud/test/icons.test.ts@@ -0,0 +1,61 @@+import { SELF } from "cloudflare:test";+import { describe, expect, it } from "vitest";+import { env, newHost, ORIGIN, AUTHORITY, type TestHost } from "./helpers";+import { signRequest } from "./ref";++async function claimedHost() {+ const h = await newHost();+ const owner = `user_${h.cid}`;+ await env.DB.prepare("INSERT INTO accounts(user_id, created_at) VALUES (?, 0)").bind(owner).run();+ await env.DB.prepare("UPDATE computers SET owner_user_id = ? WHERE id = ?").bind(owner, h.cid).run();+ return h;+}++function request(h: TestHost, method: string, slot: string, bytes?: Uint8Array) {+ const path = `/v1/host/icons/${slot}`;+ return SELF.fetch(ORIGIN + path, {+ method,+ headers: { "Codync-Sig": signRequest(h.sign, { method, authority: AUTHORITY, pathAndQuery: path, body: bytes }) },+ body: bytes,+ });+}++describe("private icon storage", () => {+ it("round trips encrypted bytes, replaces the slot, and removes it idempotently", async () => {+ const h = await claimedHost();+ const bytes = new Uint8Array(100).fill(1);+ expect((await request(h, "PUT", "0", bytes)).status).toBe(204);+ const read = await request(h, "GET", "0");+ expect(read.status).toBe(200);+ expect(read.headers.get("Cache-Control")).toBe("no-store");+ expect(new Uint8Array(await read.arrayBuffer())).toEqual(bytes);+ bytes[50] = 9;+ expect((await request(h, "PUT", "0", bytes)).status).toBe(204);+ expect(new Uint8Array(await (await request(h, "GET", "0")).arrayBuffer())).toEqual(bytes);+ expect((await request(h, "DELETE", "0")).status).toBe(204);+ expect((await request(h, "DELETE", "0")).status).toBe(204);+ expect((await request(h, "GET", "0")).status).toBe(404);+ });++ it("isolates computers and requires a claimed active account", async () => {+ const a = await claimedHost();+ const b = await claimedHost();+ expect((await request(a, "PUT", "1", new Uint8Array(40).fill(1))).status).toBe(204);+ expect((await request(b, "GET", "1")).status).toBe(404);+ expect((await request(await newHost(), "PUT", "0", new Uint8Array(40).fill(1))).status).toBe(403);+ expect((await SELF.fetch(ORIGIN + "/v1/host/icons/1")).status).toBe(401);+ await env.DB.prepare("UPDATE accounts SET status = 'deleted' WHERE user_id = ?").bind(`user_${a.cid}`).run();+ expect((await request(a, "GET", "1")).status).toBe(403);+ });++ it("bounds slot count and bytes and rejects malformed envelopes", async () => {+ const h = await claimedHost();+ for (const slot of ["128", "999", "-1", "01", "abc"]) {+ expect((await request(h, "PUT", slot, new Uint8Array(40).fill(1))).status).toBe(400);+ }+ expect((await request(h, "PUT", "127", new Uint8Array(65536).fill(1))).status).toBe(204);+ expect((await request(h, "PUT", "0", new Uint8Array(65537).fill(1))).status).toBe(413);+ expect((await request(h, "PUT", "0", new Uint8Array(29).fill(1))).status).toBe(400);+ expect((await request(h, "PUT", "0", new Uint8Array(40))).status).toBe(400);+ });+});diff --git a/cloud/wrangler.toml b/cloud/wrangler.tomlindex 1bd5ddf9..111bf2af 100644--- a/cloud/wrangler.toml+++ b/cloud/wrangler.toml@@ -11,6 +11,15 @@ routes = [{ pattern = "api.codync.dev", custom_domain = true }, { pattern = "mcptag = "v1"new_sqlite_classes = ["ComputerRelay"]+[[r2_buckets]]+binding = "ICONS"+bucket_name = "codync-icons"++[[ratelimits]]+name = "ICON_LIMITER"+namespace_id = "1041"+simple = { limit = 30, period = 60 }+[vars]CLERK_ISSUER = "https://clerk.codync.dev"@@ -56,18 +65,20 @@ crons = ["*/15 * * * *", "*/5 * * * *"]# dev: the deployed test environment at dev-api.codync.dev and dev-mcp.codync.dev (Clerk development instance).[env.dev]name = "codync-cloud-dev"+r2_buckets = [{ binding = "ICONS", bucket_name = "codync-icons-dev" }]routes = [{ pattern = "dev-api.codync.dev", custom_domain = true }, { pattern = "dev-mcp.codync.dev", custom_domain = true }]vars = { CLERK_ISSUER = "https://sunny-mollusk-8651.clerk.accounts.dev" }d1_databases = [{ binding = "DB", database_name = "codync-dev", database_id = "0c03c398-3cec-4f06-a76e-998176ca19ae", migrations_dir = "migrations" }]durable_objects.bindings = [{ name = "RELAY", class_name = "ComputerRelay" }]-ratelimits = [{ name = "REGISTER_LIMITER", namespace_id = "1002", simple = { limit = 10, period = 60 } }, { name = "TURN_LIMITER", namespace_id = "1012", simple = { limit = 12, period = 60 } }, { name = "HOOK_LIMITER", namespace_id = "1022", simple = { limit = 60, period = 60 } }, { name = "ASSISTANT_LIMITER", namespace_id = "1032", simple = { limit = 120, period = 60 } }]+ratelimits = [{ name = "ICON_LIMITER", namespace_id = "1042", simple = { limit = 30, period = 60 } }, { name = "REGISTER_LIMITER", namespace_id = "1002", simple = { limit = 10, period = 60 } }, { name = "TURN_LIMITER", namespace_id = "1012", simple = { limit = 12, period = 60 } }, { name = "HOOK_LIMITER", namespace_id = "1022", simple = { limit = 60, period = 60 } }, { name = "ASSISTANT_LIMITER", namespace_id = "1032", simple = { limit = 120, period = 60 } }]triggers = { crons = ["*/15 * * * *"] }# local: wrangler dev / e2e with a local D1; CLERK_JWT_KEY is injected by the test (--var).[env.local]name = "codync-cloud-local"+r2_buckets = [{ binding = "ICONS", bucket_name = "codync-icons-local" }]routes = []vars = { CLERK_ISSUER = "https://clerk.test.local" }d1_databases = [{ binding = "DB", database_name = "codync-local", database_id = "local", migrations_dir = "migrations" }]durable_objects.bindings = [{ name = "RELAY", class_name = "ComputerRelay" }]-ratelimits = [{ name = "REGISTER_LIMITER", namespace_id = "1003", simple = { limit = 10, period = 60 } }, { name = "TURN_LIMITER", namespace_id = "1013", simple = { limit = 12, period = 60 } }, { name = "HOOK_LIMITER", namespace_id = "1023", simple = { limit = 60, period = 60 } }, { name = "ASSISTANT_LIMITER", namespace_id = "1033", simple = { limit = 120, period = 60 } }]+ratelimits = [{ name = "ICON_LIMITER", namespace_id = "1043", simple = { limit = 30, period = 60 } }, { name = "REGISTER_LIMITER", namespace_id = "1003", simple = { limit = 10, period = 60 } }, { name = "TURN_LIMITER", namespace_id = "1013", simple = { limit = 12, period = 60 } }, { name = "HOOK_LIMITER", namespace_id = "1023", simple = { limit = 60, period = 60 } }, { name = "ASSISTANT_LIMITER", namespace_id = "1033", simple = { limit = 120, period = 60 } }]diff --git a/docs/features/bot-workspaces.md b/docs/features/bot-workspaces.mdindex 50524b45..21409593 100644--- a/docs/features/bot-workspaces.md+++ b/docs/features/bot-workspaces.md@@ -21,3 +21,13 @@ Changing the default project in settings deliberately reconfigures the agent ses- Existing bots are not silently moved out of their configured project directories.Swift settings offer Personal or Choose project folder; desktop quick creation and the terminal's new-bot flow default to Personal. Directory selection is optional. Separate workspaces do not prevent conflicts when multiple bots edit the same external project; automatic Git worktrees are not implemented here.++## Workspace picker++The desktop, iPhone and Android picker starts with recent selections for the bot's computer. The host keeps the last 12 unique selections in SQLite (`recent_workspaces`); `selectWorkspace` validates the absolute folder path and its readability before recording it. Selection alone does not update a bot: existing settings save behavior applies. Browsing never adds history.++`listDirs` includes optional `recent` and `ancestors` arrays. Clients use absence of `recent` to detect older hosts and validate selection through `listDirs`. The browser supports home expansion (`~`, `~/`, `~\\`), parent navigation, breadcrumbs, filtering within the current folder, empty states and inline errors. An empty Windows drive-list path cannot be selected. Paths belong to the current bot's host; the computer label is informational, not a host-switch action.++The terminal picker uses Ctrl+R for recent workspaces, Ctrl+B to browse and Ctrl+L to enter a path. Right enters a highlighted folder, Left goes to its parent, Enter confirms the highlighted folder, and `.` uses the current folder. Selection errors keep the picker open.++With no recent selections, Browse other folders is the first action below the computer context. The empty Recent section and search stay hidden until there is history; filtering existing history to zero matches keeps search visible. The terminal promotes the Ctrl+B browse shortcut when history is empty.diff --git a/docs/features/custom-icons.md b/docs/features/custom-icons.mdnew file mode 100644index 00000000..8660272a--- /dev/null+++ b/docs/features/custom-icons.md@@ -0,0 +1,82 @@+# Custom agent and bot icons++Issue: [#114](https://github.com/leepokai/Codync/issues/114).++The host owns image import and persistence (`host/src/icons/`). Clients send `setIcon`+with `target: "agent:<backend-id>"` or `"bot:<bot-id>"` and either standard-base64+`data`, an HTTPS `url`, a `tinted` flag, or `remove: true`. Changes save immediately;+they are separate from a bot's draft settings. Authorized control devices may use it;+pairing-only and screen-only devices may not. The terminal reads its local file before+calling the API; remote clients cannot make the host read a local path.++## Limits and validation++- PNG, JPEG, WebP: 5 MiB input, at most 4096 pixels on either axis, bounded decoder allocation.+- SVG: 256 KiB input, at most 4096 pixels on either axis. Rasterized with resvg;+ no external images/fonts, system fonts, scripts, or network resources.+- EXIF orientation is applied, metadata is discarded, and animations become still images.+- The output fits 256 × 256, preserving aspect ratio and transparency. If PNG exceeds+ 48 KiB, its dimensions are halved until it fits.+- URL imports use HTTPS/443, no credentials or proxies, a total timeout, bounded streaming+ reads, at most three redirects, and public IPs pinned after DNS validation for every hop.+- One import per host at a time. The cloud limits mutations to 30/minute/account.+- 128 fixed R2 slots per computer, at most 64 KiB of ciphertext per slot (8 MiB maximum).++## Storage and caches++Normalized PNGs and color modes are cached in the host's SQLite `custom_icons_v1` value.+The host encrypts each PNG with ChaCha20-Poly1305 using a key separated from its identity+box key by SHA-256 and a fresh nonce. AEAD binds it to its slot. R2 receives only a version+byte, nonce and ciphertext; original filenames and source URLs are not retained.++`PUT/GET/DELETE /v1/host/icons/<0..127>` requires a valid host signature, a claimed computer+and an active account. R2 is private; clients receive images over the host's authenticated+loopback or end-to-end encrypted channel. R2 is the remote stored copy; ordinary display+and reconnect use the persistent host cache and do not make R2 GET requests.++Snapshots carry a monotonic revision; clients ignore delayed older replies/events before updating their local caches.++An R2 write must succeed before replacing the local icon. Failed imports keep the previous+cache; color-only changes need no R2 write. Removal deletes R2 first. Deleted bots' slots+are swept in small batches, retrying failed cleanup each minute. Account deletion revokes device access and blocks+new writes before removing encrypted images, then finishes unclaiming computers; an R2 error+leaves ownership available for webhook retry. Unclaiming alone retains the encrypted cache+for the same computer identity; it cannot read/write R2 while unclaimed.++The `icons` snapshot/event carries the bounded images once per connection/change rather+than duplicating them in every bot status event. Desktop persists a separate IndexedDB+cache keyed by account and computer; iOS saves the icon map with its per-computer disk+mirror; Android keeps the map in its mirror database. Replacements overwrite the cache+snapshot and removals clear the reference. No client renders arbitrary remote SVG/URLs.++## Live Activity and Dynamic Island++Custom images remain static. Built-in characters keep their existing animation mechanism.+iOS stores content-addressed PNGs in an account-scoped App Group directory (erased on sign-out); ActivityKit carries only the filename.+A small per-computer/bot local pointer lets a running activity follow replacement/removal.+Local state revisions trigger redraws without putting image bytes into APNs payloads.+An offline activity keeps its last cached image until the app reconnects and receives the new snapshot.+Missing custom assets show a still built-in fallback. The desktop island receives the+same normalized image and also renders it statically.++## Deployment and verification++Before deploying cloud code, create private buckets `codync-icons` and `codync-icons-dev`+in the existing Cloudflare account, matching `cloud/wrangler.toml`. Do not enable public+bucket access. Local Wrangler and Worker tests emulate R2 using their environment binding.+Deploy the cloud worker before releasing clients/host; missing storage returns 503 and+leaves previous icons intact. Private relays do not provide this hosted storage service.++Checks: host image/URL/encryption/cache tests, cloud signed R2 isolation/limit tests,+desktop and phone model tests, client builds, and real-app upload, URL, tint, reset,+offline-cache and Live Activity flows. Builds alone do not prove the app flows.++Focused host + local R2 integration check: after `cargo build` in `host/`, run+`CODYNC_E2E_ICONS_ONLY=1 npm run e2e` in `cloud/`. This uses isolated local D1/R2,+a real host and encrypted paired-device requests; it does not verify deployed R2.++The graphical editors show upload and Paste URL actions first. Paste URL reveals the labeled address field and an accessible arrow submit button. The terminal retains its combined file-path-or-URL keyboard field because it has no graphical file picker or icon-only controls.++Computer menus reuse device badges (laptop, Mac mini, Linux, or a generic desktop when unknown). Desktop and Android show connection status as secondary text; iOS keeps native menu typography and selection marks. Terminal UI targets a single host and has no multi-computer filter menu.++Graphical clients require a signed-in app session before selecting a custom image or URL and offer sign-in when needed. Cloud still independently requires a claimed computer and active account. Missing storage routes and server errors are reported as storage availability failures, not authentication failures.diff --git a/docs/features/marketplace.md b/docs/features/marketplace.mdindex 87aab2f3..6347c047 100644--- a/docs/features/marketplace.md+++ b/docs/features/marketplace.md@@ -132,3 +132,7 @@ See [Connector setup and credentials](connector-credentials.md) for the sharedmacOS/Linux vault, optional 1Password references, in-chat connection requests andMCP readiness checks. Single-option connectors without setup fields start addingimmediately; setup failures remain visible for retry.++## Custom icons++Agents and bots support per-computer image overrides. See [custom icons](custom-icons.md) for the API, storage limits, cache behavior and deployment.diff --git a/docs/reference/remote-relay.md b/docs/reference/remote-relay.mdindex 09526104..5e79110d 100644--- a/docs/reference/remote-relay.md+++ b/docs/reference/remote-relay.md@@ -269,7 +269,7 @@ d = ChaCha20-Poly1305(kDir, nonce, plaintext, aad) (密文 ‖ 16-byte```- 每個方向各自從 `c = 0` 起算,每 frame +1;接收方要求 `c` 恰為預期值,否則關閉(close `4002 protocolError`)。這同時提供重放與重排保護。- 一則 inner 訊息(§6.5 的 JSON)UTF-8 編碼後切成 ≤ 256 KiB 的 chunk;接收方串接直到 flag `0x00`,再 JSON parse。-- 重組上限:device→host 1 MiB;host→device 16 MiB。超過 → 關閉 `4013 tooLarge`。+- 重組上限:已授權 device→host 8 MiB(含 5 MiB 自訂圖片的 base64/JSON);僅供配對的 channel 維持 1 MiB;host→device 16 MiB。超過 → 關閉 `4013 tooLarge`。單一 WebSocket 訊息仍使用 256 KiB chunks。### 6.4 Mailbox 封裝(device → 離線 host)diff --git a/host/Cargo.lock b/host/Cargo.lockindex 750e3f23..5a3cb64f 100644--- a/host/Cargo.lock+++ b/host/Cargo.lock@@ -151,6 +151,12 @@ dependencies = ["rustversion",]+[[package]]+name = "arrayref"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"+[[package]]name = "arrayvec"version = "0.7.8"@@ -508,12 +514,24 @@ version = "1.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06"+[[package]]+name = "bytemuck"+version = "1.25.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"+[[package]]name = "byteorder"version = "1.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"+[[package]]+name = "byteorder-lite"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"+[[package]]name = "bytes"version = "1.12.1"@@ -735,12 +753,14 @@ dependencies = ["iana-time-zone","icu_normalizer","if-addrs",+ "image","keyring","libc","portable-pty","qrcode","ratatui","reqwest",+ "resvg","rusqlite","rustls","semver",@@ -1116,9 +1136,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c54e03a951783e8b327515db3f2a2fd0e3bed362a96b066f341ce66ed49b4ead"dependencies = ["data-encoding",- "syn 2.0.119",+ "syn 3.0.6",]+[[package]]+name = "data-url"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"+[[package]]name = "dbus"version = "0.9.12"@@ -1424,6 +1450,15 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "euclid"+version = "0.22.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06"+dependencies = [+ "num-traits",+]+[[package]]name = "event-listener"version = "5.4.2"@@ -1462,6 +1497,15 @@ version = "2.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"+[[package]]+name = "fdeflate"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"+dependencies = [+ "simd-adler32",+]+[[package]]name = "fiat-crypto"version = "0.3.0"@@ -1502,10 +1546,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"dependencies = ["crc32fast",- "miniz_oxide",+ "miniz_oxide 0.9.1","zlib-rs",]+[[package]]+name = "float-cmp"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"+[[package]]name = "fnv"version = "1.0.7"@@ -2157,6 +2207,38 @@ dependencies = ["xmltree",]+[[package]]+name = "image"+version = "0.25.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"+dependencies = [+ "bytemuck",+ "byteorder-lite",+ "image-webp",+ "moxcms",+ "num-traits",+ "png",+ "zune-core",+ "zune-jpeg",+]++[[package]]+name = "image-webp"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"+dependencies = [+ "byteorder-lite",+ "quick-error",+]++[[package]]+name = "imagesize"+version = "0.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65b27460c2c92b037f3f94c538ed9a3342f3fdf923606781629ccb35f82d042a"+[[package]]name = "indexmap"version = "2.14.2"@@ -2535,6 +2617,18 @@ dependencies = ["zeroize",]+[[package]]+name = "kurbo"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2"+dependencies = [+ "arrayvec",+ "euclid",+ "polycool",+ "smallvec",+]+[[package]]name = "lazy_static"version = "1.5.0"@@ -2695,6 +2789,16 @@ version = "0.3.17"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"+[[package]]+name = "miniz_oxide"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"+dependencies = [+ "adler2",+ "simd-adler32",+]+[[package]]name = "miniz_oxide"version = "0.9.1"@@ -2717,6 +2821,16 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "moxcms"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"+dependencies = [+ "num-traits",+ "pxfm",+]+[[package]]name = "n0-dns-resolver"version = "0.1.0"@@ -3474,6 +3588,12 @@ dependencies = ["siphasher",]+[[package]]+name = "pico-args"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315"+[[package]]name = "pin-project"version = "1.1.13"@@ -3540,6 +3660,19 @@ dependencies = ["time",]+[[package]]+name = "png"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"+dependencies = [+ "bitflags 2.13.2",+ "crc32fast",+ "fdeflate",+ "flate2",+ "miniz_oxide 0.8.9",+]+[[package]]name = "polling"version = "3.11.0"@@ -3564,6 +3697,15 @@ dependencies = ["universal-hash 0.6.1",]+[[package]]+name = "polycool"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6"+dependencies = [+ "arrayvec",+]+[[package]]name = "polyval"version = "0.6.2"@@ -3701,12 +3843,24 @@ dependencies = ["unicode-ident",]+[[package]]+name = "pxfm"+version = "0.1.30"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"+[[package]]name = "qrcode"version = "0.14.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec"+[[package]]+name = "quick-error"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"+[[package]]name = "quick-xml"version = "0.42.0"@@ -4021,6 +4175,30 @@ dependencies = ["web-sys",]+[[package]]+name = "resvg"+version = "0.49.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1572844b6727a1bf842190e9947641a68ac44bed83f50afb4bd1407a2564bee8"+dependencies = [+ "bytemuck",+ "log",+ "pico-args",+ "rgb",+ "svgtypes",+ "tiny-skia",+ "usvg",+]++[[package]]+name = "rgb"+version = "0.8.53"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4"+dependencies = [+ "bytemuck",+]+[[package]]name = "ring"version = "0.17.14"@@ -4035,6 +4213,15 @@ dependencies = ["windows-sys 0.52.0",]+[[package]]+name = "roxmltree"+version = "0.21.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907"+dependencies = [+ "memchr",+]+[[package]]name = "rsqlite-vfs"version = "0.1.1"@@ -4530,6 +4717,15 @@ dependencies = ["bitflags 2.13.2",]+[[package]]+name = "simplecss"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c"+dependencies = [+ "log",+]+[[package]]name = "siphasher"version = "1.0.4"@@ -4624,6 +4820,15 @@ version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"+[[package]]+name = "strict-num"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"+dependencies = [+ "float-cmp",+]+[[package]]name = "strsim"version = "0.11.1"@@ -4678,6 +4883,16 @@ version = "2.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"+[[package]]+name = "svgtypes"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "695b5790b3131dafa99b3bbfd25a216edb3d216dad9ca208d4657bfb8f2abc3d"+dependencies = [+ "kurbo",+ "siphasher",+]+[[package]]name = "syn"version = "2.0.119"@@ -4847,6 +5062,32 @@ dependencies = ["time-core",]+[[package]]+name = "tiny-skia"+version = "0.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47ffee5eaaf5527f630fb0e356b90ebdec84d5d18d937c5e440350f88c5a91ea"+dependencies = [+ "arrayref",+ "arrayvec",+ "bytemuck",+ "cfg-if",+ "log",+ "png",+ "tiny-skia-path",+]++[[package]]+name = "tiny-skia-path"+version = "0.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "edca365c3faccca67d06593c5980fa6c57687de727a03131735bb85f01fdeeb9"+dependencies = [+ "arrayref",+ "bytemuck",+ "strict-num",+]+[[package]]name = "tinystr"version = "0.8.4"@@ -5221,6 +5462,25 @@ dependencies = ["serde_derive",]+[[package]]+name = "usvg"+version = "0.49.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d09b73ee83641d390ad7ffd9000f347b16eb128e437675b6ff277ea5c7fcf22c"+dependencies = [+ "data-url",+ "imagesize",+ "kurbo",+ "log",+ "pico-args",+ "roxmltree",+ "simplecss",+ "siphasher",+ "strict-num",+ "svgtypes",+ "tiny-skia-path",+]+[[package]]name = "utf8_iter"version = "1.0.4"@@ -6095,6 +6355,21 @@ version = "1.0.23"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"+[[package]]+name = "zune-core"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"++[[package]]+name = "zune-jpeg"+version = "0.5.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"+dependencies = [+ "zune-core",+]+[[package]]name = "zvariant"version = "4.2.0"diff --git a/host/Cargo.toml b/host/Cargo.tomlindex ea8751fb..13b31d2c 100644--- a/host/Cargo.toml+++ b/host/Cargo.toml@@ -64,6 +64,8 @@ uuid = { version = "1.26.1", features = ["v4", "v7"] }x25519-dalek = { version = "3.0.0", features = ["static_secrets"] }zeroize = "1"+image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] }+resvg = { version = "0.49", default-features = false }[target.'cfg(target_os = "macos")'.dependencies]keyring = { version = "3.6.3", features = ["apple-native"] }diff --git a/host/src/api/events.rs b/host/src/api/events.rsindex 7ec5d147..c06760f3 100644--- a/host/src/api/events.rs+++ b/host/src/api/events.rs@@ -67,6 +67,8 @@ pub fn events_stream(catch_up.push(json!({"type": "entry", "rev": e.rev, "entry": e}));}catch_up.extend(crate::chat::artifacts::since(&hub.store, since));+ let icons = crate::icons::snapshot(&hub.store)?;+ catch_up.push(json!({"type": "icons", "icons": icons.icons, "iconsRevision": icons.icons_revision}));catch_up.sort_by_key(|v| v["rev"].as_i64().unwrap_or(0));// What the voice of a call this device holds should have heard while it was away.catch_up.extend(crate::chat::calls::replay(caller.device_key()));diff --git a/host/src/api/events/tests.rs b/host/src/api/events/tests.rsindex 301eee8d..d92f762c 100644--- a/host/src/api/events/tests.rs+++ b/host/src/api/events/tests.rs@@ -52,9 +52,10 @@ async fn full_sync_removes_a_bot_deleted_while_the_client_was_offline() {// An app/host update rewinds the cursor to zero while keeping the cached roster.let events = f.catch_up(0).await;+ assert_eq!(events[1], json!({"type": "icons", "icons": {}, "iconsRevision": 0}));assert_eq!(events[0]["type"], "hello");let mut cached = std::collections::HashSet::from(["deleted".to_owned()]);- for event in &events[1..] {+ for event in &events[2..] {let bot = &event["bot"];let id = bot["id"].as_str().unwrap();if bot["deleted"] == true {@@ -65,7 +66,7 @@ async fn full_sync_removes_a_bot_deleted_while_the_client_was_offline() {}}assert_eq!(cached, std::collections::HashSet::from(["kept".to_owned()]));- assert!(events[1..].windows(2).all(|pair| pair[0]["rev"].as_i64() < pair[1]["rev"].as_i64()));+ assert!(events[2..].windows(2).all(|pair| pair[0]["rev"].as_i64() < pair[1]["rev"].as_i64()));}#[tokio::test]@@ -74,10 +75,10 @@ async fn incremental_sync_replays_deletions_only_after_the_saved_cursor() {let before = f.add_bot("deleted");let deleted_rev = f.hub.store.delete_bot("deleted").unwrap();let events = f.catch_up(before).await;- assert_eq!(events.len(), 2);- assert_eq!(events[1]["bot"]["deleted"], true);- assert_eq!(events[1]["rev"], deleted_rev);- assert_eq!(f.catch_up(deleted_rev).await.len(), 1);+ assert_eq!(events.len(), 3);+ assert_eq!(events[2]["bot"]["deleted"], true);+ assert_eq!(events[2]["rev"], deleted_rev);+ assert_eq!(f.catch_up(deleted_rev).await.len(), 2);}#[tokio::test]@@ -98,7 +99,7 @@ async fn catch_up_brings_an_artifact_renamed_while_the_client_was_offline() {"entryId": card.id});f.hub.store.kv_set(&format!("artifact.b.{id}"), &saved.to_string()).unwrap();let cursor = f.hub.store.current_rev();- assert_eq!(f.catch_up(cursor).await[1..], [] as [Value; 0], "details without a rev default to 0, never replayed");+ assert_eq!(f.catch_up(cursor).await[2..], [] as [Value; 0], "details without a rev default to 0, never replayed");crate::chat::artifacts::api(&f.hub, "renameArtifact", &json!({"botId": "b", "artifactId": id, "title": "New"})).await@@ -110,8 +111,8 @@ async fn catch_up_brings_an_artifact_renamed_while_the_client_was_offline() {let entry = events.iter().find(|e| e["type"] == "entry").expect("its card was retitled");assert_eq!(entry["entry"]["data"]["text"], "Artifact: New");assert_eq!(entry["entry"]["data"]["artifact"]["title"], "New");- assert!(events[1..].windows(2).all(|pair| pair[0]["rev"].as_i64() < pair[1]["rev"].as_i64()), "in rev order");- assert_eq!(f.catch_up(f.hub.store.current_rev()).await[1..], [] as [Value; 0]);+ assert!(events[2..].windows(2).all(|pair| pair[0]["rev"].as_i64() < pair[1]["rev"].as_i64()), "in rev order");+ assert_eq!(f.catch_up(f.hub.store.current_rev()).await[2..], [] as [Value; 0]);}#[tokio::test(flavor = "multi_thread", worker_threads = 2)]diff --git a/host/src/api/folders.rs b/host/src/api/folders.rsnew file mode 100644index 00000000..7a950c91--- /dev/null+++ b/host/src/api/folders.rs@@ -0,0 +1,140 @@+//! Host-owned folder browsing and recent workspace selections.+use crate::store::Store;+use anyhow::{Context, Result, anyhow, bail};+use serde_json::{Value, json};+use std::path::{Path, PathBuf};++pub(super) fn listing(store: &Store, path: Option<PathBuf>) -> Result<Value> {+ let mut result = list_dirs(path)?;+ result["recent"] = serde_json::to_value(store.recent_workspaces()?)?;+ Ok(result)+}++pub(super) fn select(store: &Store, path: &str) -> Result<Value> {+ if path.trim().is_empty() {+ bail!("choose a folder first");+ }+ let path = resolve(Path::new(path))?;+ // Check readability before recording a selection; never remember invalid paths.+ std::fs::read_dir(&path).with_context(|| format!("opening {}", path.display()))?;+ let path = path.to_string_lossy().into_owned();+ store.remember_workspace(&path)?;+ Ok(json!({"path": path}))+}++fn resolve(path: &Path) -> Result<PathBuf> {+ let text = path.to_string_lossy();+ let expanded = if text == "~" {+ dirs::home_dir().context("no home directory")?+ } else if let Some(tail) = text.strip_prefix("~/").or_else(|| text.strip_prefix("~\\")) {+ dirs::home_dir().context("no home directory")?.join(tail)+ } else {+ path.to_path_buf()+ };+ if !expanded.is_absolute() {+ bail!("enter an absolute folder path");+ }+ // Preserve symlink names the user chose, while rejecting nonexistent folders.+ if !expanded.is_dir() {+ bail!("folder does not exist: {}", expanded.display());+ }+ Ok(expanded)+}++/// Blocking (`std::fs`): call through `spawn_blocking`. An empty path lists the drives (Windows),+/// which is also the parent a drive root reports, so pickers can move between drives.+fn list_dirs(path: Option<PathBuf>) -> Result<Value> {+ let dir = match path {+ Some(p) if p.as_os_str().is_empty() && cfg!(windows) => return Ok(list_drives()),+ Some(p) if !p.as_os_str().is_empty() => resolve(&p)?,+ _ => dirs::home_dir().ok_or_else(|| anyhow!("no home directory"))?,+ };+ let mut dirs: Vec<Value> = std::fs::read_dir(&dir)+ .with_context(|| format!("listing {}", dir.display()))?+ .filter_map(Result::ok)+ .filter_map(|e| {+ let name = e.file_name().to_string_lossy().into_owned();+ let p = e.path();+ // `is_dir` follows symlinks, junctions and mount points; `file_type` would drop them.+ if name.starts_with('.') || !p.is_dir() {+ return None;+ }+ Some(json!({"name": name, "path": p.to_string_lossy(), "isGit": p.join(".git").exists()}))+ })+ .collect();+ dirs.sort_by_key(|d| d["name"].as_str().unwrap_or_default().to_lowercase());+ let parent = match dir.parent() {+ Some(p) => Some(p.to_string_lossy().into_owned()),+ None if cfg!(windows) => Some(String::new()),+ None => None,+ };+ Ok(json!({+ "path": dir.to_string_lossy(),+ "parent": parent,+ "isGit": dir.join(".git").exists(),+ "dirs": dirs,+ "ancestors": dir.ancestors().collect::<Vec<_>>().into_iter().rev().map(|p| json!({+ "path": p.to_string_lossy(),+ "name": p.file_name().map_or_else(|| p.to_string_lossy().into_owned(), |n| n.to_string_lossy().into_owned()),+ "isGit": false,+ })).collect::<Vec<_>>(),+ }))+}++/// The drives that are mounted (`C:\`, `D:\`, …), as a listing with no path of its own.+fn list_drives() -> Value {+ let dirs: Vec<Value> = (b'A'..=b'Z')+ .map(|letter| format!("{}:\\", char::from(letter)))+ .filter(|root| Path::new(root).is_dir())+ .map(|root| json!({"name": root.trim_end_matches('\\'), "path": root, "isGit": false}))+ .collect();+ json!({"path": "", "parent": null, "isGit": false, "dirs": dirs})+}++#[cfg(all(test, unix))]+mod tests {+ #[test]+ fn folder_listing_follows_linked_folders() {+ let dir = std::env::temp_dir().join(format!("codync-dirs-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(dir.join("real")).unwrap();+ std::os::unix::fs::symlink(dir.join("real"), dir.join("linked")).unwrap();+ std::fs::write(dir.join("file"), "").unwrap();+ let listing = super::list_dirs(Some(dir.clone())).unwrap();+ let names: Vec<&str> = listing["dirs"].as_array().unwrap().iter().filter_map(|d| d["name"].as_str()).collect();+ assert_eq!(names, ["linked", "real"]);+ std::fs::remove_dir_all(dir).unwrap();+ }+}++#[cfg(test)]+mod selection_tests {+ use super::*;+ #[test]+ fn selection_is_validated_and_survives_reopening_store() {+ let root = std::env::temp_dir().join(format!("codync-workspace-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(root.join("project")).unwrap();+ let db = root.join("test.db");+ let store = Store::open(&db).unwrap();+ assert!(select(&store, "").is_err());+ assert!(select(&store, "relative/path").is_err());+ assert!(select(&store, root.join("missing").to_str().unwrap()).is_err());+ assert!(store.recent_workspaces().unwrap().is_empty());+ let path = root.join("project").to_string_lossy().into_owned();+ assert_eq!(select(&store, &path).unwrap()["path"], path);+ #[cfg(unix)]+ {+ let spaced = root.join("project ");+ std::fs::create_dir(&spaced).unwrap();+ let spaced = spaced.to_string_lossy().into_owned();+ assert_eq!(select(&store, &spaced).unwrap()["path"], spaced);+ select(&store, &path).unwrap();+ }+ drop(store);+ let reopened = Store::open(&db).unwrap();+ let result = listing(&reopened, Some(root.clone())).unwrap();+ assert_eq!(result["recent"][0]["path"], path);+ assert_eq!(result["ancestors"].as_array().unwrap().last().unwrap()["path"], root.to_string_lossy().as_ref());+ drop(reopened);+ std::fs::remove_dir_all(root).unwrap();+ }+}diff --git a/host/src/api/host.rs b/host/src/api/host.rsindex 12c501c0..5be526fe 100644--- a/host/src/api/host.rs+++ b/host/src/api/host.rs@@ -57,6 +57,7 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value}"hello" => {let port = hub.port;+ let icons = crate::icons::snapshot(&hub.store)?;json!({"hostId": hub.host_id,"computerId": hub.identity.computer_id(),@@ -74,6 +75,8 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value"device": tokio::task::spawn_blocking(crate::service::device).await?,"home": dirs::home_dir().map(|p| p.to_string_lossy().into_owned()),"backends": backends::list(),+ "icons": icons.icons,+ "iconsRevision": icons.icons_revision,"rev": hub.store.current_rev(),"screen": hub.screen.state(),"analytics": hub.analytics.state(),@@ -94,7 +97,13 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value}"listDirs" => {let path = b["path"].as_str().map(std::path::PathBuf::from);- tokio::task::spawn_blocking(move || list_dirs(path)).await??+ let hub = hub.clone();+ tokio::task::spawn_blocking(move || super::folders::listing(&hub.store, path)).await??+ }+ "selectWorkspace" => {+ let path = str_arg(&b, "path")?.to_owned();+ let hub = hub.clone();+ tokio::task::spawn_blocking(move || super::folders::select(&hub.store, &path)).await??}"agentSetup" => {let step: crate::agent::term::Step =@@ -197,67 +206,7 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value}))}-/// Blocking (`std::fs`): call through `spawn_blocking`. An empty path lists the drives (Windows),-/// which is also the parent a drive root reports, so pickers can move between drives.-fn list_dirs(path: Option<std::path::PathBuf>) -> Result<Value> {- let dir = match path {- Some(p) if p.as_os_str().is_empty() && cfg!(windows) => return Ok(list_drives()),- Some(p) if !p.as_os_str().is_empty() => p,- _ => dirs::home_dir().ok_or_else(|| anyhow!("no home directory"))?,- };- let mut dirs: Vec<Value> = std::fs::read_dir(&dir)- .with_context(|| format!("listing {}", dir.display()))?- .filter_map(Result::ok)- .filter_map(|e| {- let name = e.file_name().to_string_lossy().into_owned();- let p = e.path();- // `is_dir` follows symlinks, junctions and mount points; `file_type` would drop them.- if name.starts_with('.') || !p.is_dir() {- return None;- }- Some(json!({"name": name, "path": p.to_string_lossy(), "isGit": p.join(".git").exists()}))- })- .collect();- dirs.sort_by_key(|d| d["name"].as_str().unwrap_or_default().to_lowercase());- let parent = match dir.parent() {- Some(p) => Some(p.to_string_lossy().into_owned()),- None if cfg!(windows) => Some(String::new()),- None => None,- };- Ok(json!({- "path": dir.to_string_lossy(),- "parent": parent,- "isGit": dir.join(".git").exists(),- "dirs": dirs,- }))-}--/// The drives that are mounted (`C:\`, `D:\`, …), as a listing with no path of its own.-fn list_drives() -> Value {- let dirs: Vec<Value> = (b'A'..=b'Z')- .map(|letter| format!("{}:\\", char::from(letter)))- .filter(|root| std::path::Path::new(root).is_dir())- .map(|root| json!({"name": root.trim_end_matches('\\'), "path": root, "isGit": false}))- .collect();- json!({"path": "", "parent": null, "isGit": false, "dirs": dirs})-}-fn term_size(b: &Value) -> (u16, u16) {let dim = |k: &str, default: u16| b[k].as_u64().and_then(|v| u16::try_from(v).ok()).unwrap_or(default);(dim("cols", 80), dim("rows", 24))}--#[cfg(all(test, unix))]-mod tests {- #[test]- fn folder_listing_follows_linked_folders() {- let dir = std::env::temp_dir().join(format!("codync-dirs-{}", uuid::Uuid::new_v4()));- std::fs::create_dir_all(dir.join("real")).unwrap();- std::os::unix::fs::symlink(dir.join("real"), dir.join("linked")).unwrap();- std::fs::write(dir.join("file"), "").unwrap();- let listing = super::list_dirs(Some(dir.clone())).unwrap();- let names: Vec<&str> = listing["dirs"].as_array().unwrap().iter().filter_map(|d| d["name"].as_str()).collect();- assert_eq!(names, ["linked", "real"]);- std::fs::remove_dir_all(dir).unwrap();- }-}diff --git a/host/src/api/http.rs b/host/src/api/http.rsindex c64ca271..974f9ca4 100644--- a/host/src/api/http.rs+++ b/host/src/api/http.rs@@ -28,6 +28,7 @@ pub fn router(hub: Arc<Hub>) -> Router {.route("/hooks/routines/{id}", post(routine_hook)).route("/events", get(events)).route("/api/{method}", post(command))+ .route("/api/setIcon", post(icon_command).layer(axum::extract::DefaultBodyLimit::max(8 * 1024 * 1024))).route("/term/{id}", get(term_stream)).route("/ingest/statusline", post(statusline)).route("/channel", get(channel))@@ -35,6 +36,21 @@ pub fn router(hub: Arc<Hub>) -> Router {.with_state(hub)}+async fn icon_command(+ State(hub): State<Arc<Hub>>,+ ConnectInfo(peer): ConnectInfo<SocketAddr>,+ headers: HeaderMap,+ Json(body): Json<Value>,+) -> Result<Json<Value>, ApiError> {+ if !authorized(&hub, &headers, peer) {+ return Err(unauthorized());+ }+ dispatch(&hub, &Caller::Local, "setIcon", body).await.map(Json).map_err(|e| {+ let (status, message) = error_status(&e);+ ApiError(status, message)+ })+}+/// Loopback, also as an IPv4-mapped IPv6 address (`::ffff:127.0.0.1` under `--bind ::`).fn is_loopback(ip: IpAddr) -> bool {ip.to_canonical().is_loopback()diff --git a/host/src/api/mod.rs b/host/src/api/mod.rsindex a98a911d..f6b9ef55 100644--- a/host/src/api/mod.rs+++ b/host/src/api/mod.rs@@ -6,6 +6,7 @@ mod bots;pub mod devices;mod events;mod files;+mod folders;mod host;mod http;mod marketplace;@@ -70,6 +71,12 @@ pub async fn dispatch(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value) -}async fn route(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value) -> Result<Value> {+ if method == "setIcon" {+ return crate::icons::set(hub, &b).await;+ }+ if method == "icons" {+ return Ok(serde_json::to_value(crate::icons::snapshot(&hub.store)?)?);+ }if method.contains("onnector")|| method.starts_with("composio")|| method == "setComposioKey"diff --git a/host/src/background.rs b/host/src/background.rsindex 2fca63e9..74a98ba4 100644--- a/host/src/background.rs+++ b/host/src/background.rs@@ -13,6 +13,7 @@ pub fn start(hub: &Arc<Hub>) {}});tokio::spawn(registry::refresh_loop());+ tokio::spawn(crate::icons::cleanup_loop(hub.clone()));tokio::spawn(market::refresh_first_page());tokio::spawn(market::automatic_loop(hub.clone()));tokio::spawn(voice::refresh_loop(hub.clone()));diff --git a/host/src/icons/cleanup.rs b/host/src/icons/cleanup.rsnew file mode 100644index 00000000..29467bc0--- /dev/null+++ b/host/src/icons/cleanup.rs@@ -0,0 +1,38 @@+//! Retry cleanup after bot deletion, including when the cloud was unavailable at deletion time.+use super::{commit, list, storage};+use crate::hub::Hub;+use anyhow::Result;+use std::sync::Arc;+use std::time::Duration;++pub(crate) async fn run(hub: Arc<Hub>) {+ let mut timer = tokio::time::interval(Duration::from_mins(1));+ timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);+ loop {+ timer.tick().await;+ if let Err(error) = sweep(&hub).await {+ tracing::warn!(error = format!("{error:#}"), "custom icon cleanup will retry");+ }+ }+}++async fn sweep(hub: &Hub) -> Result<()> {+ let Ok(_guard) = hub.store.icon_lock.try_lock() else { return Ok(()) };+ let mut icons = list(&hub.store)?;+ let mut removed = 0;+ for (target, icon) in icons.clone() {+ let Some(id) = target.strip_prefix("bot:") else { continue };+ if hub.store.bot(id)?.is_some_and(|b| !b.deleted) {+ continue;+ }+ storage::delete(hub, icon.slot).await?;+ icons.remove(&target);+ // Commit each deletion so a later network failure resumes at the next slot.+ icons = commit(hub, icons)?.icons;+ removed += 1;+ if removed == 8 {+ break;+ }+ }+ Ok(())+}diff --git a/host/src/icons/image.rs b/host/src/icons/image.rsnew file mode 100644index 00000000..66c11250--- /dev/null+++ b/host/src/icons/image.rs@@ -0,0 +1,89 @@+//! Decode untrusted input once, strip metadata, and produce a bounded PNG for every client.+use anyhow::{Context, Result, bail, ensure};+use image::{DynamicImage, ImageDecoder as _, ImageFormat, ImageReader, Limits};+use std::io::Cursor;++pub(super) const MAX_INPUT: usize = 5 * 1024 * 1024;+pub(super) const MAX_PNG: usize = 48 * 1024;+const MAX_SIDE: u32 = 4096;+const ICON_SIDE: u32 = 256;+const MAX_SVG: usize = 256 * 1024;++pub(super) fn normalize(bytes: &[u8]) -> Result<Vec<u8>> {+ ensure!(!bytes.is_empty() && bytes.len() <= MAX_INPUT, "Choose an image up to 5 MiB");+ let image = match image::guess_format(bytes) {+ Ok(format @ (ImageFormat::Png | ImageFormat::Jpeg | ImageFormat::WebP)) => {+ let mut reader = ImageReader::with_format(Cursor::new(bytes), format);+ let mut limits = Limits::default();+ limits.max_image_width = Some(MAX_SIDE);+ limits.max_image_height = Some(MAX_SIDE);+ limits.max_alloc = Some(128 * 1024 * 1024);+ reader.limits(limits);+ let mut decoder = reader.into_decoder().context("Image is damaged or exceeds 4096 × 4096 pixels")?;+ let orientation = decoder.orientation()?;+ let mut image = DynamicImage::from_decoder(decoder).context("Cannot decode image")?;+ image.apply_orientation(orientation);+ image+ }+ Ok(_) => bail!("Choose PNG, JPEG, WebP or SVG"),+ Err(_) => svg(bytes)?,+ };+ let mut side = ICON_SIDE;+ loop {+ let resized = image.resize(side, side, image::imageops::FilterType::Lanczos3);+ let mut out = Cursor::new(Vec::new());+ resized.write_to(&mut out, ImageFormat::Png)?;+ let out = out.into_inner();+ if out.len() <= MAX_PNG {+ return Ok(out);+ }+ ensure!(side > 32, "Image could not be compressed");+ side /= 2;+ }+}++fn svg(bytes: &[u8]) -> Result<DynamicImage> {+ ensure!(bytes.len() <= MAX_SVG, "SVG images must be at most 256 KiB");+ // No filesystem resources, embedded images, fonts, scripts or network resources.+ let options = resvg::usvg::Options {+ image_href_resolver: resvg::usvg::ImageHrefResolver {+ resolve_data: Box::new(|_, _, _| None),+ resolve_string: Box::new(|_, _| None),+ },+ ..Default::default()+ };+ let tree = resvg::usvg::Tree::from_data(bytes, &options).context("Choose a valid PNG, JPEG, WebP or SVG image")?;+ let size = tree.size();+ ensure!(size.width() <= 4096.0 && size.height() <= 4096.0, "SVG dimensions exceed 4096 × 4096 pixels");+ let scale = 256.0 / size.width().max(size.height());+ let pixels = size.scale_by(scale).context("Invalid SVG dimensions")?.to_int_size();+ let mut pixmap = resvg::tiny_skia::Pixmap::new(pixels.width(), pixels.height()).context("Cannot render SVG")?;+ resvg::render(&tree, resvg::tiny_skia::Transform::from_scale(scale, scale), &mut pixmap.as_mut());+ // tiny-skia holds premultiplied RGBA; encoding PNG restores straight alpha.+ Ok(image::load_from_memory_with_format(&pixmap.encode_png()?, ImageFormat::Png)?)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn svg_is_rasterized_without_external_images() {+ let png = normalize(br##"<svg xmlns="http://www.w3.org/2000/svg" width="512" height="256"><rect width="512" height="256" fill="#ff0000"/><image href="file:///etc/passwd" width="100" height="100"/></svg>"##).unwrap();+ let decoded = image::load_from_memory(&png).unwrap();+ assert_eq!((decoded.width(), decoded.height()), (256, 128));+ assert!(png.len() <= MAX_PNG);+ }++ #[test]+ fn oversized_and_broken_images_are_rejected() {+ assert!(normalize(&[]).is_err());+ assert!(normalize(&vec![0; MAX_INPUT + 1]).is_err());+ assert!(normalize(b"not an image").is_err());+ assert!(normalize(br#"<svg xmlns="http://www.w3.org/2000/svg" width="9000" height="9000"/>"#).is_err());+ let huge = DynamicImage::new_rgba8(4097, 1);+ let mut png = Cursor::new(Vec::new());+ huge.write_to(&mut png, ImageFormat::Png).unwrap();+ assert!(normalize(png.get_ref()).is_err());+ }+}diff --git a/host/src/icons/mod.rs b/host/src/icons/mod.rsnew file mode 100644index 00000000..d0c05bb3--- /dev/null+++ b/host/src/icons/mod.rs@@ -0,0 +1,110 @@+//! Custom agent/bot icons: host validation, local cache and private encrypted R2 storage.+mod cleanup;+mod image;+pub(crate) use cleanup::run as cleanup_loop;+mod source;+mod storage;+#[cfg(test)]+mod tests;++use crate::{hub::Hub, store::Store};+use anyhow::{Context, Result, ensure};+use base64::{Engine as _, engine::general_purpose::STANDARD};+use serde::{Deserialize, Serialize};+use serde_json::{Value, json};+use std::collections::BTreeMap;+use std::sync::Arc;++const KEY: &str = "custom_icons_v1";+const SLOTS: u8 = 128;++#[derive(Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub(crate) struct Icon {+ slot: u8,+ /// A normalized, metadata-free PNG. Sent only over existing authenticated channels.+ pub data_url: String,+ pub tinted: bool,+}++#[derive(Default, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub(crate) struct Snapshot {+ pub icons: BTreeMap<String, Icon>,+ pub icons_revision: i64,+}++pub(crate) fn snapshot(store: &Store) -> Result<Snapshot> {+ store.kv_read(KEY)?.map_or_else(|| Ok(Snapshot::default()), |v| Ok(serde_json::from_str(&v)?))+}++pub(crate) fn list(store: &Store) -> Result<BTreeMap<String, Icon>> {+ Ok(snapshot(store)?.icons)+}++fn commit(hub: &Hub, icons: BTreeMap<String, Icon>) -> Result<Snapshot> {+ let mut snapshot = Snapshot { icons, icons_revision: 0 };+ hub.store.kv_set_stamped(KEY, |revision| {+ snapshot.icons_revision = revision;+ Ok(serde_json::to_string(&snapshot)?)+ })?;+ let _ =+ hub.events.send(json!({"type": "icons", "icons": snapshot.icons, "iconsRevision": snapshot.icons_revision}));+ Ok(snapshot)+}++pub(crate) async fn set(hub: &Arc<Hub>, b: &Value) -> Result<Value> {+ let target = b["target"].as_str().context("Icon target is required")?;+ validate_target(hub, target)?;+ // Bound concurrent decoding and serialize R2 replacements with local commits.+ let _guard = hub.store.icon_lock.try_lock().context("Another icon is being saved; try again shortly")?;+ let mut icons = list(&hub.store)?;+ if b["remove"] == true {+ if let Some(old) = icons.get(target) {+ storage::delete(hub, old.slot).await?;+ icons.remove(target);+ }+ } else if b["data"].is_null() && b["url"].is_null() {+ let icon = icons.get_mut(target).context("Choose an image first")?;+ icon.tinted = b["tinted"].as_bool().context("Icon color mode is required")?;+ } else {+ ensure!(b["data"].is_null() || b["url"].is_null(), "Choose a file or an image URL, not both");+ let bytes = if let Some(url) = b["url"].as_str() {+ source::download(url).await?+ } else {+ let data = b["data"].as_str().context("Image data is required")?;+ ensure!(data.len() <= image::MAX_INPUT.div_ceil(3) * 4, "Choose an image up to 5 MiB");+ STANDARD.decode(data).context("Invalid image encoding")?+ };+ let png = tokio::task::spawn_blocking(move || image::normalize(&bytes)).await??;+ // Two slots per update are unnecessary: a failed local commit leaves the old local+ // cache intact, and retrying the same target replaces the same bounded remote slot.+ let slot = icons+ .get(target)+ .map(|i| i.slot)+ .or_else(|| (0..SLOTS).find(|slot| !icons.values().any(|i| i.slot == *slot)))+ .context("This computer has 128 custom icons; remove one before adding another")?;+ storage::put(hub, slot, &png).await?;+ icons.insert(+ target.to_owned(),+ Icon {+ slot,+ data_url: format!("data:image/png;base64,{}", STANDARD.encode(png)),+ tinted: b["tinted"].as_bool().unwrap_or(false),+ },+ );+ }+ Ok(serde_json::to_value(commit(hub, icons)?)?)+}++fn validate_target(hub: &Hub, target: &str) -> Result<()> {+ ensure!(target.len() <= 256, "Invalid icon target");+ if let Some(id) = target.strip_prefix("bot:") {+ ensure!(hub.store.bot(id)?.is_some_and(|b| !b.deleted), "Unknown bot");+ } else if let Some(id) = target.strip_prefix("agent:") {+ ensure!(crate::agent::backends::list().iter().any(|b| b["id"] == id), "Unknown agent");+ } else {+ anyhow::bail!("Choose an agent or bot icon");+ }+ Ok(())+}diff --git a/host/src/icons/source.rs b/host/src/icons/source.rsnew file mode 100644index 00000000..1d79cff6--- /dev/null+++ b/host/src/icons/source.rs@@ -0,0 +1,118 @@+//! Bounded HTTPS imports. Pin validated DNS answers and validate every redirect.+use anyhow::{Context, Result, bail, ensure};+use futures::StreamExt;+use reqwest::{Client, Url};+use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};+use std::time::Duration;++pub(super) async fn download(raw: &str) -> Result<Vec<u8>> {+ ensure!(raw.len() <= 2048, "Image URL is too long");+ tokio::time::timeout(Duration::from_secs(20), fetch(raw)).await.context("Image download timed out")?+}++async fn fetch(raw: &str) -> Result<Vec<u8>> {+ let mut url = Url::parse(raw).context("Invalid image URL")?;+ for _ in 0..4 {+ ensure!(+ url.scheme() == "https" && url.port_or_known_default() == Some(443),+ "Use an HTTPS image URL on port 443"+ );+ ensure!(url.username().is_empty() && url.password().is_none(), "Image URLs cannot contain credentials");+ let host = url.host_str().context("Image URL has no host")?;+ let addresses: Vec<SocketAddr> = match host.trim_matches(['[', ']']).parse::<IpAddr>() {+ Ok(ip) => vec![SocketAddr::new(ip, 443)],+ Err(_) => tokio::net::lookup_host((host, 443)).await.context("Cannot resolve image host")?.collect(),+ };+ ensure!(+ !addresses.is_empty() && addresses.iter().all(|a| public_ip(a.ip())),+ "Image URLs must use public internet addresses"+ );+ let client = Client::builder()+ .no_proxy()+ .redirect(reqwest::redirect::Policy::none())+ .timeout(Duration::from_secs(15))+ .resolve_to_addrs(host, &addresses)+ .build()?;+ let response = client.get(url.clone()).send().await.context("Cannot download image")?;+ if response.status().is_redirection() {+ let location = response+ .headers()+ .get(reqwest::header::LOCATION)+ .context("Image redirect has no destination")?+ .to_str()?;+ url = url.join(location)?;+ continue;+ }+ let response = response.error_for_status().context("Image server refused the download")?;+ ensure!(+ response.content_length().is_none_or(|n| n <= super::image::MAX_INPUT as u64),+ "Choose an image up to 5 MiB"+ );+ let mut stream = response.bytes_stream();+ let mut bytes = Vec::new();+ while let Some(chunk) = stream.next().await {+ let chunk = chunk?;+ ensure!(bytes.len() + chunk.len() <= super::image::MAX_INPUT, "Choose an image up to 5 MiB");+ bytes.extend_from_slice(&chunk);+ }+ return Ok(bytes);+ }+ bail!("Too many image redirects")+}++fn public_ip(ip: IpAddr) -> bool {+ match ip {+ IpAddr::V4(ip) => public_v4(ip),+ IpAddr::V6(ip) => public_v6(ip),+ }+}++fn public_v4(ip: Ipv4Addr) -> bool {+ let [a, b, c, _] = ip.octets();+ !(ip.is_private()+ || ip.is_loopback()+ || ip.is_link_local()+ || ip.is_broadcast()+ || ip.is_documentation()+ || a == 0+ || a >= 224+ || (a == 100 && (64..=127).contains(&b))+ || (a == 198 && (b == 18 || b == 19))+ || (a == 192 && b == 0 && (c == 0 || c == 2))+ || (a == 192 && b == 88 && c == 99))+}++fn public_v6(ip: Ipv6Addr) -> bool {+ let s = ip.segments();+ // Only global unicast; reject transition/tunneling and documentation ranges too.+ s[0] & 0xe000 == 0x2000+ && s[0] != 0x2002+ && !(s[0] == 0x2001 && (s[1] < 0x200 || s[1] == 0xdb8))+ && !(s[0] == 0x3fff && s[1] < 0x1000)+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn private_and_translation_addresses_are_not_download_targets() {+ for ip in [+ "127.0.0.1",+ "10.0.0.1",+ "169.254.169.254",+ "100.64.0.1",+ "198.18.0.1",+ "224.0.0.1",+ "::1",+ "::ffff:127.0.0.1",+ "64:ff9b::7f00:1",+ "2002:7f00::1",+ "2001:db8::1",+ "fc00::1",+ ] {+ assert!(!public_ip(ip.parse().unwrap()), "{ip}");+ }+ assert!(public_ip("8.8.8.8".parse().unwrap()));+ assert!(public_ip("2606:4700::1111".parse().unwrap()));+ }+}diff --git a/host/src/icons/storage.rs b/host/src/icons/storage.rsnew file mode 100644index 00000000..fdf1286e--- /dev/null+++ b/host/src/icons/storage.rs@@ -0,0 +1,81 @@+//! Private R2 transport; domain-separated encryption binds each blob to its slot.+use crate::hub::Hub;+use crate::remote::{cloud, crypto};+use anyhow::{Context, Result, ensure};+use chacha20poly1305::{+ ChaCha20Poly1305, Nonce,+ aead::{Aead, KeyInit, Payload},+};+use reqwest::Method;+use std::time::Duration;++pub(super) async fn put(hub: &Hub, slot: u8, png: &[u8]) -> Result<()> {+ let key = crypto::sha256(&[b"codync/custom-icons/v1", hub.identity.box_secret.as_bytes()]);+ let bytes = seal(&key, slot, png)?;+ request(hub, slot, Method::PUT, bytes).await+}++pub(super) async fn delete(hub: &Hub, slot: u8) -> Result<()> {+ request(hub, slot, Method::DELETE, Vec::new()).await+}++async fn request(hub: &Hub, slot: u8, method: Method, bytes: Vec<u8>) -> Result<()> {+ let base = cloud::codync_url(hub)?;+ let path = format!("/v1/host/icons/{slot}");+ let signature = hub.identity.sign_request(method.as_str(), &cloud::authority(&base)?, &path, &bytes);+ let response = crate::http()+ .request(method, format!("{base}{path}"))+ .header("Codync-Sig", signature)+ .header("Content-Type", "application/octet-stream")+ .timeout(Duration::from_secs(20))+ .body(bytes)+ .send()+ .await+ .context("Icon storage is unreachable; your previous icon has been kept")?;+ ensure!(response.status().is_success(), "{}; your previous icon has been kept", storage_error(response.status()));+ Ok(())+}++fn storage_error(status: reqwest::StatusCode) -> String {+ match status.as_u16() {+ 401 | 403 => "Sign in and claim this computer to store custom icons".into(),+ 404 => "Custom icon storage is not available on this server yet".into(),+ 429 => "Too many icon changes. Wait a moment and try again".into(),+ 500..=599 => "Custom icon storage is temporarily unavailable. Try again later".into(),+ _ => format!("Icon storage returned {status}"),+ }+}++fn seal(key: &[u8; 32], slot: u8, png: &[u8]) -> Result<Vec<u8>> {+ let nonce = crypto::random::<12>();+ let encrypted = ChaCha20Poly1305::new(key.into())+ .encrypt(&Nonce::from(nonce), Payload { msg: png, aad: &[1, slot] })+ .map_err(|_| anyhow::anyhow!("Cannot encrypt icon"))?;+ Ok([&[1], nonce.as_slice(), encrypted.as_slice()].concat())+}++#[cfg(test)]+mod tests {+ use super::*;+ #[test]+ fn storage_errors_only_request_sign_in_for_authentication_failures() {+ for code in [401, 403] {+ assert!(storage_error(reqwest::StatusCode::from_u16(code).unwrap()).contains("Sign in"));+ }+ for code in [404, 429, 500, 503] {+ assert!(!storage_error(reqwest::StatusCode::from_u16(code).unwrap()).contains("Sign in"));+ }+ assert!(storage_error(reqwest::StatusCode::NOT_FOUND).contains("not available on this server"));+ }++ #[test]+ fn stored_icons_are_encrypted_and_bound_to_their_slot() {+ let key = [7; 32];+ let blob = seal(&key, 3, b"private image").unwrap();+ let cipher = ChaCha20Poly1305::new((&key).into());+ let nonce = Nonce::try_from(&blob[1..13]).unwrap();+ assert_eq!(cipher.decrypt(&nonce, Payload { msg: &blob[13..], aad: &[1, 3] }).unwrap(), b"private image");+ assert!(cipher.decrypt(&nonce, Payload { msg: &blob[13..], aad: &[1, 4] }).is_err());+ assert_ne!(blob, seal(&key, 3, b"private image").unwrap());+ }+}diff --git a/host/src/icons/tests.rs b/host/src/icons/tests.rsnew file mode 100644index 00000000..5113ecfb--- /dev/null+++ b/host/src/icons/tests.rs@@ -0,0 +1,46 @@+use super::*;+use crate::remote::identity::Identity;++fn hub() -> (Arc<Hub>, std::path::PathBuf) {+ let dir = std::env::temp_dir().join(format!("codync-icons-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&dir).unwrap();+ let store = Store::open(&dir.join("t.db")).unwrap();+ let identity = Identity::load_or_create(&dir).unwrap();+ (Hub::new(store, "test".into(), identity, "token".into(), 0), dir)+}++#[tokio::test]+async fn cached_icons_and_color_changes_do_not_need_cloud_downloads() {+ let (hub, dir) = hub();+ let png = image::normalize(br##"<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#f00"/></svg>"##).unwrap();+ let icon = Icon { slot: 0, data_url: format!("data:image/png;base64,{}", STANDARD.encode(png)), tinted: false };+ commit(&hub, BTreeMap::from([("agent:claude".to_owned(), icon)])).unwrap();+ let before = list(&hub.store).unwrap()["agent:claude"].data_url.clone();+ let before_revision = snapshot(&hub.store).unwrap().icons_revision;+ let result = set(&hub, &json!({"target": "agent:claude", "tinted": true})).await.unwrap();+ assert_eq!(result["icons"]["agent:claude"]["dataUrl"], before);+ assert_eq!(result["icons"]["agent:claude"]["tinted"], true);+ assert!(result["iconsRevision"].as_i64().unwrap() > before_revision);+ // The cache survives reopening SQLite; there is no HTTP request on either read path.+ let reopened = Store::open(&dir.join("t.db")).unwrap();+ assert_eq!(list(&reopened).unwrap()["agent:claude"].data_url, before);+ assert_eq!(snapshot(&reopened).unwrap().icons_revision, result["iconsRevision"].as_i64().unwrap());+ let error = set(&hub, &json!({"target": "agent:claude", "data": STANDARD.encode(b"bad image")})).await;+ assert!(error.is_err());+ assert_eq!(list(&hub.store).unwrap()["agent:claude"].data_url, before);+ drop(reopened);+ drop(hub);+ std::fs::remove_dir_all(dir).unwrap();+}++#[tokio::test]+async fn concurrent_changes_and_unknown_targets_are_rejected_before_uploading() {+ let (hub, dir) = hub();+ assert!(set(&hub, &json!({"target": "bot:missing", "data": ""})).await.is_err());+ let guard = hub.store.icon_lock.lock().await;+ let error = set(&hub, &json!({"target": "agent:claude", "data": ""})).await.unwrap_err();+ assert!(error.to_string().contains("Another icon"));+ drop(guard);+ drop(hub);+ std::fs::remove_dir_all(dir).unwrap();+}diff --git a/host/src/main.rs b/host/src/main.rsindex 627ba9d9..c281fe98 100644--- a/host/src/main.rs+++ b/host/src/main.rs@@ -9,6 +9,7 @@ mod cloud_cli;mod compat;mod environment;mod hub;+mod icons;mod market;mod mcp;mod network;diff --git a/host/src/remote/channel.rs b/host/src/remote/channel.rsindex 65447e9d..46590249 100644--- a/host/src/remote/channel.rs+++ b/host/src/remote/channel.rs@@ -30,8 +30,8 @@ use x25519_dalek::StaticSecret;/// Largest WebSocket message accepted (and the Cloudflare limit); 256 KiB chunks fit.pub const MAX_WS_MESSAGE: usize = 1 << 20;-/// Largest reassembled device → host message.-const MAX_INBOUND: usize = 1 << 20;+/// Largest reassembled authorized device → host message (5 MiB icon + base64/JSON).+const MAX_INBOUND: usize = 8 << 20;const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);/// Channel keys are replaced (close `4011`) after this long.const MAX_AGE: Duration = Duration::from_hours(24);@@ -188,7 +188,7 @@ pub async fn run(hub: Arc<Hub>, t: Transport, kind: ChannelKind) {lease: None,online: None,};- let opener = Opener::new(hs.keys.d2h, MAX_INBOUND);+ let opener = Opener::new(hs.keys.d2h, if hs.device.is_some() { MAX_INBOUND } else { 1 << 20 });let (code, reason) = if let Some(d) = hs.device {ch.set_device(&d);ch.serve(&mut incoming, opener, &mut writer).await@@ -814,6 +814,7 @@ mod tests {p.send(json!({"id": 3, "sub": "events", "b": {"since": hub.store.current_rev(), "client": "ios"}})).await;let hello = p.recv().await.unwrap();assert_eq!((hello["id"].as_u64(), hello["ev"]["type"].as_str()), (Some(3), Some("hello")));+ assert_eq!(p.recv().await.unwrap()["ev"]["type"], "icons");assert!(hub.phone_connected());assert!(hub.revoke_device(&dk).unwrap());@@ -908,6 +909,7 @@ mod tests {p.hello(&hub, false).await;p.send(json!({"id": 7, "sub": "events", "b": {"since": 0}})).await;assert_eq!(p.recv().await.unwrap()["ev"]["type"], "hello");+ assert_eq!(p.recv().await.unwrap()["ev"]["type"], "icons");p.send(json!({"id": 7, "cancel": true})).await;assert_eq!(p.recv().await.unwrap(), json!({"id": 7, "end": true}));assert_eq!(p.call(8, "hello", json!({})).await["id"], 8, "the channel goes on");diff --git a/host/src/store/mod.rs b/host/src/store/mod.rsindex 9e18d9cc..d28391f9 100644--- a/host/src/store/mod.rs+++ b/host/src/store/mod.rs@@ -11,6 +11,7 @@ mod entries;mod memory;mod model;mod schema;+mod workspaces;pub use devices::{Device, DeviceSource, Scope};pub use model::{@@ -24,6 +25,7 @@ use rusqlite::{Connection, OptionalExtension, params};use std::sync::Mutex;pub struct Store {+ pub(crate) icon_lock: tokio::sync::Mutex<()>,db: Mutex<Connection>,pub(crate) connector_lock: Mutex<()>,pub(crate) secret_key: Mutex<Option<zeroize::Zeroizing<Vec<u8>>>>,diff --git a/host/src/store/schema.rs b/host/src/store/schema.rsindex 5ad5e79a..49b33def 100644--- a/host/src/store/schema.rs+++ b/host/src/store/schema.rs@@ -159,6 +159,7 @@ impl Store {None};Ok(Self {+ icon_lock: tokio::sync::Mutex::new(()),db: Mutex::new(c),connector_lock: Mutex::new(()),secret_key: Mutex::new(secret_key),diff --git a/host/src/store/workspaces.rs b/host/src/store/workspaces.rsnew file mode 100644index 00000000..7fde1607--- /dev/null+++ b/host/src/store/workspaces.rs@@ -0,0 +1,51 @@+//! Small, durable MRU list, shared by all clients of this computer.+use super::{Store, now_ms};+use crate::LockExt;+use anyhow::Result;+use rusqlite::OptionalExtension;+use serde::{Deserialize, Serialize};++#[derive(Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RecentWorkspace {+ pub path: String,+ pub used_at: i64,+}++impl Store {+ pub fn recent_workspaces(&self) -> Result<Vec<RecentWorkspace>> {+ self.kv_read("recent_workspaces")?.map_or_else(|| Ok(Vec::new()), |v| Ok(serde_json::from_str(&v)?))+ }++ pub fn remember_workspace(&self, path: &str) -> Result<()> {+ let db = self.db.locked();+ let existing: Option<String> =+ db.query_row("SELECT v FROM kv WHERE k = 'recent_workspaces'", [], |r| r.get(0)).optional()?;+ let mut recent: Vec<RecentWorkspace> = existing.map_or_else(|| Ok(Vec::new()), |v| serde_json::from_str(&v))?;+ recent.retain(|item| item.path != path);+ recent.insert(0, RecentWorkspace { path: path.into(), used_at: now_ms() });+ recent.truncate(12);+ db.execute(+ "INSERT INTO kv(k,v) VALUES('recent_workspaces',?1) ON CONFLICT(k) DO UPDATE SET v = excluded.v",+ [serde_json::to_string(&recent)?],+ )?;+ Ok(())+ }+}++#[cfg(test)]+mod tests {+ #[test]+ fn recent_workspaces_deduplicate_and_keep_latest_twelve() {+ let store = super::super::tests::temp_store();+ for i in 0..15 {+ store.remember_workspace(&format!("/project/{i}")).unwrap();+ }+ store.remember_workspace("/project/5").unwrap();+ let recent = store.recent_workspaces().unwrap();+ assert_eq!(recent.len(), 12);+ assert_eq!(recent[0].path, "/project/5");+ assert_eq!(recent[1].path, "/project/14");+ assert_eq!(recent.iter().filter(|r| r.path == "/project/5").count(), 1);+ }+}diff --git a/host/src/tui/app/events.rs b/host/src/tui/app/events.rsindex 69fea964..93479345 100644--- a/host/src/tui/app/events.rs+++ b/host/src/tui/app/events.rs@@ -189,9 +189,12 @@ impl App {}_ => {}},- After::Dirs => {- if let Some(Overlay::Folder(p)) = self.overlays.last_mut() {+ After::Dirs(id) | After::WorkspaceSelected(id) => {+ if let Some(Overlay::Folder(p)) = self.overlays.last_mut()+ && p.request_id == id+ {p.error = Some(e);+ p.busy = false;}}// In place of the code, which may have expired.@@ -219,6 +222,7 @@ impl App {self.call("hello", json!({}), After::Hello);}After::Hello => {+ self.custom_icons = v["icons"].is_object();self.mismatch = crate::compat::check(env!("CARGO_PKG_VERSION"), crate::compat::MIN_HOST, &v);v["name"].as_str().unwrap_or("computer").clone_into(&mut self.host);v["version"].as_str().unwrap_or_default().clone_into(&mut self.host_version);@@ -248,9 +252,30 @@ impl App {}}}- After::Dirs => {- if let Some(Overlay::Folder(p)) = self.overlays.last_mut() {+ After::WorkspaceSelected(id) => {+ if matches!(self.overlays.last(), Some(Overlay::Folder(p)) if p.request_id == id)+ && let Some(path) = v["path"].as_str().filter(|p| !p.is_empty())+ {+ self.overlays.pop();+ self.folder_chosen(path.to_owned());+ }+ }+ After::Dirs(id) => {+ if let Some(Overlay::Folder(p)) = self.overlays.last_mut()+ && p.request_id == id+ {v["path"].as_str().unwrap_or_default().clone_into(&mut p.path);+ p.busy = false;+ p.remembers = v["recent"].is_array();+ p.recent = v["recent"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|item| {+ let path = item["path"].as_str()?;+ Some(Dir { name: path.to_owned(), path: path.to_owned(), git: false })+ })+ .collect();p.parent = v["parent"].as_str().map(str::to_owned);p.dirs = v["dirs"].as_array()diff --git a/host/src/tui/app/forms.rs b/host/src/tui/app/forms.rsindex 43b7ef5d..a249db23 100644--- a/host/src/tui/app/forms.rs+++ b/host/src/tui/app/forms.rs@@ -170,6 +170,12 @@ impl App {return None;}let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);+ if ctrl && k.code == KeyCode::Char('o') && !f.saving && self.custom_icons {+ let target = format!("bot:{}", f.bot_id);+ self.overlays.push(Overlay::Form(f));+ self.overlays.push(Overlay::Fields(Box::new(crate::tui::manage::icon_fields(target))));+ return None;+ }let field = f.current();if field == Field::Fallbacks && self.fallback_key(&mut f, k) {return Some(Overlay::Form(f));diff --git a/host/src/tui/app/mod.rs b/host/src/tui/app/mod.rsindex 27e1806a..36e2eac4 100644--- a/host/src/tui/app/mod.rs+++ b/host/src/tui/app/mod.rs@@ -25,9 +25,9 @@ pub use roster::{RosterLine, cursor_line, rename_fold, roster_lines, stops};pub use slash::SlashAction;pub(super) use steps::{running_turn, working_steps};pub use ui::{- ACTIONS, Action, COLORS, Click, Confirm, ConfirmAct, Dir, FIELDS, FILTERS, Field, Focus, FolderPicker, Form, Goto,- GotoItem, GroupField, GroupForm, Hits, NewBot, NewBotField, Overlay, PairCode, SHAPES, Toast, Toggle, TraceMode,- Width,+ ACTIONS, Action, COLORS, Click, Confirm, ConfirmAct, Dir, FIELDS, FILTERS, Field, Focus, FolderMode, FolderPicker,+ Form, Goto, GotoItem, GroupField, GroupForm, Hits, NewBot, NewBotField, Overlay, PairCode, SHAPES, Toast, Toggle,+ TraceMode, Width,};use crate::tui::l10n::tr;@@ -68,6 +68,7 @@ pub struct App {/// This computer's network (`networkView`'s shape); null on hosts without one.pub network: Value,pub backends: Vec<Value>,+ pub custom_icons: bool,pub selected: Option<String>,pub focus: Focus,pub typing: bool,@@ -161,6 +162,7 @@ impl App {screen: Value::Null,network: Value::Null,backends: vec![],+ custom_icons: false,selected: None,focus: Focus::Roster,typing: false,diff --git a/host/src/tui/app/model.rs b/host/src/tui/app/model.rsindex 357d9143..2726196b 100644--- a/host/src/tui/app/model.rs+++ b/host/src/tui/app/model.rs@@ -37,7 +37,8 @@ pub enum After {Tracked,Analytics,History(String),- Dirs,+ Dirs(String),+ WorkspaceSelected(String),Pairing,Backends,Update,diff --git a/host/src/tui/app/overlay_keys.rs b/host/src/tui/app/overlay_keys.rsindex 84eb0a38..376277fe 100644--- a/host/src/tui/app/overlay_keys.rs+++ b/host/src/tui/app/overlay_keys.rs@@ -5,8 +5,8 @@ use serde_json::json;use super::super::manage::{AnalyticsSheet, Reply};use super::{- ACTIONS, Action, After, App, Bot, ConfirmAct, Dir, Editor, FILTERS, FolderPicker, Goto, GotoItem, Overlay,- PairCode, contains, fuzzy,+ ACTIONS, Action, After, App, Bot, ConfirmAct, Dir, Editor, FILTERS, FolderMode, FolderPicker, Goto, GotoItem,+ Overlay, PairCode, contains, fuzzy,};impl App {@@ -215,7 +215,13 @@ impl App {}pub(super) fn open_folder(&mut self, start: &str) {+ let request_id = uuid::Uuid::new_v4().to_string();self.overlays.push(Overlay::Folder(FolderPicker {+ request_id: request_id.clone(),+ mode: FolderMode::Recent,+ recent: vec![],+ remembers: false,+ busy: true,path: start.to_owned(),parent: None,dirs: vec![],@@ -224,14 +230,60 @@ impl App {error: None,}));let body = if start.is_empty() { json!({}) } else { json!({"path": start}) };- self.call("listDirs", body, After::Dirs);+ self.call("listDirs", body, After::Dirs(request_id));}pub fn folder_matches(p: &FolderPicker) -> Vec<&Dir> {- p.dirs.iter().filter(|d| fuzzy(&p.query.text, &[&d.name])).collect()+ let items = if p.mode == FolderMode::Recent { &p.recent } else { &p.dirs };+ items.iter().filter(|d| fuzzy(&p.query.text, &[&d.name, &d.path])).collect()}fn folder_key(&mut self, mut p: FolderPicker, k: KeyEvent) -> Option<Overlay> {+ if k.code == KeyCode::Esc && p.mode != FolderMode::Path {+ return None;+ }+ if p.busy {+ return Some(Overlay::Folder(p));+ }+ if k.modifiers.contains(KeyModifiers::CONTROL) {+ match k.code {+ KeyCode::Char('r') => {+ p.mode = FolderMode::Recent;+ p.query.clear();+ p.cursor = 0;+ }+ KeyCode::Char('b') => {+ p.mode = FolderMode::Browse;+ p.query.clear();+ p.cursor = 0;+ }+ KeyCode::Char('l') => {+ p.mode = FolderMode::Path;+ p.query.clear();+ }+ _ => {+ p.query.key(k);+ }+ }+ return Some(Overlay::Folder(p));+ }+ if p.mode == FolderMode::Path {+ match k.code {+ KeyCode::Esc => {+ p.mode = FolderMode::Browse;+ p.query.clear();+ }+ KeyCode::Enter if !p.query.text.trim().is_empty() => {+ self.call("listDirs", json!({"path": p.query.text.trim()}), After::Dirs(p.request_id.clone()));+ p.mode = FolderMode::Browse;+ p.busy = true;+ }+ _ => {+ p.query.key(k);+ }+ }+ return Some(Overlay::Folder(p));+ }let matches: Vec<Dir> = Self::folder_matches(&p).into_iter().cloned().collect();match k.code {KeyCode::Esc => return None,@@ -239,29 +291,34 @@ impl App {KeyCode::Up => p.cursor = p.cursor.saturating_sub(1),KeyCode::Right | KeyCode::Tab => {if let Some(d) = matches.get(p.cursor) {- let path = d.path.clone();- self.call("listDirs", json!({"path": path}), After::Dirs);+ self.call("listDirs", json!({"path": d.path}), After::Dirs(p.request_id.clone()));+ p.mode = FolderMode::Browse;+ p.busy = true;}}KeyCode::Left | KeyCode::Backspace if p.query.text.is_empty() => {if let Some(parent) = p.parent.clone() {- self.call("listDirs", json!({"path": parent}), After::Dirs);+ self.call("listDirs", json!({"path": parent}), After::Dirs(p.request_id.clone()));+ p.mode = FolderMode::Browse;+ p.busy = true;}}- KeyCode::Enter => {- // Enter on a highlighted child uses it; with nothing typed and no match, the current folder.- let chosen = if p.query.text.is_empty() && k.modifiers.contains(KeyModifiers::ALT) {+ KeyCode::Enter | KeyCode::Char('.') if k.code == KeyCode::Enter || p.query.text.is_empty() => {+ let current = k.code == KeyCode::Char('.') || k.modifiers.contains(KeyModifiers::ALT);+ let chosen = if current {p.path.clone()} else {- matches.get(p.cursor).map_or_else(|| p.path.clone(), |d| d.path.clone())+ matches.get(p.cursor).map_or_else(String::new, |d| d.path.clone())};- self.folder_chosen(chosen);- return None;- }- KeyCode::Char('.') if p.query.text.is_empty() => {- let chosen = p.path.clone();- self.folder_chosen(chosen);- return None;+ if !chosen.is_empty() {+ // Older hosts still validate using their existing directory endpoint.+ self.call(+ if p.remembers { "selectWorkspace" } else { "listDirs" },+ json!({"path": chosen}),+ After::WorkspaceSelected(p.request_id.clone()),+ );+ p.busy = true;+ }}_ => {if p.query.key(k) {@@ -272,7 +329,7 @@ impl App {Some(Overlay::Folder(p))}- fn folder_chosen(&mut self, path: String) {+ pub(super) fn folder_chosen(&mut self, path: String) {// The drive list (Windows) has no path of its own to use.if path.is_empty() {return;diff --git a/host/src/tui/app/ui.rs b/host/src/tui/app/ui.rsindex ee35f404..721fdac7 100644--- a/host/src/tui/app/ui.rs+++ b/host/src/tui/app/ui.rs@@ -144,7 +144,19 @@ pub struct Dir {pub git: bool,}+#[derive(PartialEq, Eq)]+pub enum FolderMode {+ Recent,+ Browse,+ Path,+}+pub struct FolderPicker {+ pub request_id: String,+ pub mode: FolderMode,+ pub recent: Vec<Dir>,+ pub remembers: bool,+ pub busy: bool,pub path: String,pub parent: Option<String>,pub dirs: Vec<Dir>,diff --git a/host/src/tui/manage/agent.rs b/host/src/tui/manage/agent.rsindex 37f89a4c..1661b25c 100644--- a/host/src/tui/manage/agent.rs+++ b/host/src/tui/manage/agent.rs@@ -59,6 +59,9 @@ impl App {}rows.push(SetupRow::Check);rows.push(SetupRow::Brings);+ if self.custom_icons {+ rows.push(SetupRow::Icon);+ }rows}@@ -73,6 +76,11 @@ impl App {let (cols, rows_n) = crossterm::terminal::size().unwrap_or((80, 24));let size = json!({"cols": cols, "rows": rows_n});match rows.get(a.cursor) {+ Some(SetupRow::Icon) => {+ self.overlays.push(Overlay::Agent(a));+ self.overlays.push(Overlay::Fields(Box::new(super::icon_fields(format!("agent:{backend}")))));+ return None;+ }Some(SetupRow::Install) => self.start_setup(&backend, "install", None, &size),Some(SetupRow::Node) => self.start_setup(&backend, "node", None, &size),Some(SetupRow::Login) => self.start_setup(&backend, "login", None, &size),diff --git a/host/src/tui/manage/fields.rs b/host/src/tui/manage/fields.rsindex c3bad606..e3320493 100644--- a/host/src/tui/manage/fields.rs+++ b/host/src/tui/manage/fields.rs@@ -57,6 +57,16 @@ impl App {f.saving = true;f.error = None;match &f.submit {+ Submit::Icon(target) => {+ let mut body = json!({"target": target, "tinted": f.choice == 1});+ if f.choice == 2 {+ body["remove"] = true.into();+ } else if let Some(source) = values.get("source").and_then(Value::as_str) {+ let key = if source.starts_with("https://") { "url" } else { "localFile" };+ body[key] = source.into();+ }+ self.sheet("setIcon", body, Reply::FieldsSaved);+ }Submit::Connection(_) => self.submit_connection(f, &values),Submit::AgentEnv(backend) => {if values.is_empty() {diff --git a/host/src/tui/manage/icons.rs b/host/src/tui/manage/icons.rsnew file mode 100644index 00000000..eedb1dc5--- /dev/null+++ b/host/src/tui/manage/icons.rs@@ -0,0 +1,17 @@+//! A terminal can choose a file or URL and color mode without pretending to render a bitmap.+use super::{Fields, Input, Submit};+use crate::tui::app::Editor;++pub fn icon_fields(target: String) -> Fields {+ Fields {+ title: "Custom icon".into(),+ note: "PNG/JPEG/WebP ≤5 MiB; SVG ≤256 KiB. Images stay still. Terminals keep the text avatar; apps show the image. Leave source empty to change only the color mode.".into(),+ choices: vec!["Original colors".into(), "Tint icon".into(), "Use default".into()],+ choice: 0,+ inputs: vec![Input {+ name: "source".into(), label: "Image".into(), secret: false, required: false,+ multiline: false, placeholder: "Local file path or https://…".into(), ed: Editor::default(),+ }],+ cursor: 0, error: None, saving: false, submit: Submit::Icon(target),+ }+}diff --git a/host/src/tui/manage/mod.rs b/host/src/tui/manage/mod.rsindex 64274820..6adc904c 100644--- a/host/src/tui/manage/mod.rs+++ b/host/src/tui/manage/mod.rs@@ -10,6 +10,7 @@ mod analytics;mod bot_chat;mod fields;mod gear;+mod icons;mod library;mod market;mod memory;@@ -25,6 +26,7 @@ mod when;pub use analytics::AnalyticsSheet;pub use fields::{handoff_fields, section_fields};pub use gear::{Gear, GearRow};+pub use icons::icon_fields;pub use library::{ArtifactTitles, LibraryItem};pub use memory::{MemoryMode, MemorySheet, Scroll, Section};pub use network::{NetReply, NetworkSheet, Recovery, Step};@@ -181,6 +183,7 @@ pub struct AgentSetup {}pub enum SetupRow {+ Icon,Install,Node,Login,@@ -201,6 +204,7 @@ pub struct Input {}pub enum Submit {+ Icon(String),AgentEnv(String),Connection(Box<super::connections::Connection>),Connector(Value),diff --git a/host/src/tui/net.rs b/host/src/tui/net.rsindex 999bb5fa..5ec71af0 100644--- a/host/src/tui/net.rs+++ b/host/src/tui/net.rs@@ -2,6 +2,7 @@pub mod artifacts;pub mod files;+mod icons;use futures::StreamExt;use serde_json::{Value, json};@@ -55,6 +56,13 @@ impl Client {}pub async fn call(&self, method: &str, body: &Value) -> Result<Value, String> {+ let prepared;+ let body = if method == "setIcon" {+ prepared = icons::prepare(body).await.map_err(|e| format!("{e:#}"))?;+ &prepared+ } else {+ body+ };let token = self.token().ok_or(NOT_INSTALLED)?;let started = std::time::Instant::now();let res = loop {diff --git a/host/src/tui/net/icons.rs b/host/src/tui/net/icons.rsnew file mode 100644index 00000000..5b3ab732--- /dev/null+++ b/host/src/tui/net/icons.rs@@ -0,0 +1,20 @@+use anyhow::{Context, Result, ensure};+use base64::{Engine as _, engine::general_purpose::STANDARD};+use serde_json::Value;+use tokio::io::AsyncReadExt;++/// Local-file access belongs to this client, never to a remotely callable host method.+pub(super) async fn prepare(body: &Value) -> Result<Value> {+ let mut body = body.clone();+ if let Some(path) = body["localFile"].as_str() {+ let file = tokio::fs::File::open(path).await.context("Cannot open image")?;+ let mut bytes = Vec::new();+ file.take(5 * 1024 * 1024 + 1).read_to_end(&mut bytes).await?;+ ensure!(!bytes.is_empty() && bytes.len() <= 5 * 1024 * 1024, "Choose an image up to 5 MiB");+ body["data"] = STANDARD.encode(bytes).into();+ if let Some(object) = body.as_object_mut() {+ object.remove("localFile");+ }+ }+ Ok(body)+}diff --git a/host/src/tui/sheets.rs b/host/src/tui/sheets.rsindex e3ac9d81..5b344318 100644--- a/host/src/tui/sheets.rs+++ b/host/src/tui/sheets.rs@@ -327,6 +327,7 @@ pub fn agent(buf: &mut Buffer, area: Rect, app: &App, a: &AgentSetup) {),SetupRow::Check => ("↻", "Check again".to_owned(), String::new()),SetupRow::Brings => ("≡", "What the agent brings".to_owned(), String::new()),+ SetupRow::Icon => ("◈", "Custom icon".to_owned(), "Choose a file or URL, tint, or use default".to_owned()),};let title = tr(&title);let detail = tr(&detail);diff --git a/host/src/tui/view/forms.rs b/host/src/tui/view/forms.rsindex 59aa0a48..844d48b3 100644--- a/host/src/tui/view/forms.rs+++ b/host/src/tui/view/forms.rs@@ -318,7 +318,13 @@ pub(super) fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {tr("Reachable by cloud assistants: ChatGPT or Claude in your Codync account can see and message this bot.");put(buf, inner.x, by - 1, inner.width, &line, t.dim.patch(t.panel));}- let save = if f.saving { " … Saving " } else { " ↵ Save " };+ let save = if f.saving {+ " … Saving "+ } else if app.custom_icons {+ " ↵ Save · ^O Icon "+ } else {+ " ↵ Save "+ };let x = put(buf, inner.x, by, 14, save, t.btn_primary) + 1;put(buf, x, by, 12, " esc Cancel ", t.text.patch(t.btn).add_modifier(Modifier::BOLD));let hint = match f.current() {diff --git a/host/src/tui/view/overlay.rs b/host/src/tui/view/overlay.rsindex 4514f119..d83909c9 100644--- a/host/src/tui/view/overlay.rs+++ b/host/src/tui/view/overlay.rs@@ -67,9 +67,15 @@ pub(super) fn overlay(buf: &mut Buffer, area: Rect, app: &mut App, top: &Overlaylet t = theme();let matches = App::folder_matches(p);let r = centered(area, 74, 22);- let inner = frame_box(buf, r, t.text, t.panel, Some(("Folder", t.text)));+ let inner = frame_box(buf, r, t.text, t.panel, Some(("Choose workspace", t.text)));let shown = tilde(&p.path, &app.home);- let path = format!("{}/", shown.trim_end_matches('/'));+ let no_recent = p.mode == crate::tui::app::FolderMode::Recent && !p.busy && p.recent.is_empty();+ let path = match p.mode {+ crate::tui::app::FolderMode::Recent if no_recent => "^B Browse other folders".to_owned(),+ crate::tui::app::FolderMode::Recent => "Recent workspaces".to_owned(),+ crate::tui::app::FolderMode::Path => "Enter folder path".to_owned(),+ crate::tui::app::FolderMode::Browse => shown.clone(),+ };let x = put(buf,inner.x,@@ -78,7 +84,9 @@ pub(super) fn overlay(buf: &mut Buffer, area: Rect, app: &mut App, top: &Overlay&truncate(&path, usize::from(inner.width / 2)),t.secondary.patch(t.panel),);- field_line(buf, Rect::new(x, inner.y, inner.right().saturating_sub(x), 1), inner.y, &p.query, "", true);+ if !no_recent {+ field_line(buf, Rect::new(x, inner.y, inner.right().saturating_sub(x), 1), inner.y, &p.query, "", true);+ }let list_h = usize::from(inner.height.saturating_sub(5));let off = p.cursor.saturating_sub(list_h.saturating_sub(1));let mut y = inner.y + 2;@@ -86,6 +94,10 @@ pub(super) fn overlay(buf: &mut Buffer, area: Rect, app: &mut App, top: &Overlayput(buf, inner.x, y, inner.width, e, t.red.patch(t.panel));y += 1;}+ if p.busy {+ put(buf, inner.x, y, inner.width, "Loading…", t.dim.patch(t.panel));+ y += 1;+ }for (i, d) in matches.iter().enumerate().skip(off).take(list_h) {let sel = i == p.cursor;let base = if sel { t.sel } else { t.panel };@@ -120,7 +132,7 @@ pub(super) fn overlay(buf: &mut Buffer, area: Rect, app: &mut App, top: &Overlayinner.x,inner.bottom() - 1,inner.width,- "→ open ← up . use this folder esc back",+ "→ open ← up . use current ^R recent ^B browse ^L path",t.dim.patch(t.panel),);}diff --git a/host/tests/fixtures/wire-shape.json b/host/tests/fixtures/wire-shape.jsonindex b05e103b..6c94b98b 100644--- a/host/tests/fixtures/wire-shape.json+++ b/host/tests/fixtures/wire-shape.json@@ -189,6 +189,10 @@"event:hello.network.networks": "array","event:hello.rev": "number","event:hello.type": "string",+ "event:icons": "object",+ "event:icons.icons": "object",+ "event:icons.iconsRevision": "number",+ "event:icons.type": "string","hello": "object","hello.analytics": "bool","hello.boxKey": "string",@@ -198,6 +202,8 @@"hello.device": "string","hello.home": "string","hello.hostId": "string",+ "hello.icons": "object",+ "hello.iconsRevision": "number","hello.latestVersion": "null","hello.minApp": "string","hello.name": "string",diff --git a/web/content/docs/agents.mdx b/web/content/docs/agents.mdxindex 23963569..5242da63 100644--- a/web/content/docs/agents.mdx+++ b/web/content/docs/agents.mdx@@ -120,3 +120,9 @@ There's no separate default-agent setting. A new bot gets Claude Code when ClaudA bot can have fallback agents that carry on the same turn when its own agent is out of usage, rate limited, signed out or won't start. See [Agent fallbacks](/docs/agent-fallbacks).++## Custom agent icons++Open an agent in **Extensions** and use **Custom icon** to upload an image, or choose **Paste URL** to reveal the address field and submit an HTTPS image URL with the arrow button. Keep the original colors or turn on **Tint icon**. Choose **Use default** to restore its bundled logo, or the terminal symbol when no logo is bundled. Each computer keeps its own overrides, shared by its paired apps.++The [custom icon limits and caching rules](/docs/bots#custom-icons) also apply to agents. In the terminal, open the agent's setup and choose **Custom icon**.diff --git a/web/content/docs/bots.mdx b/web/content/docs/bots.mdxindex bf5ffea5..fc5a6e36 100644--- a/web/content/docs/bots.mdx+++ b/web/content/docs/bots.mdx@@ -29,7 +29,7 @@ The host on your computer runs every bot. A bot's agent starts when you send it## Profile-- **Avatar:** a character shape and a color.+- **Avatar:** a character shape and a color, or your own image.- **Name:** shown in the bot list, the chat and notifications. If you create a bot without a name, it's called "New Bot" until Codync names it after its first few conversations.- **Standing instructions:** rules that always apply, such as "Reviews PRs. Never pushes without asking." Put task-specific requests in the chat instead. The bot gets your changes with its next message, and the conversation continues.@@ -49,12 +49,14 @@ Changing the agent or the model starts a new agent session. The chat history staThe **Workspace** setting is the folder the bot starts in.- **Personal workspace** (the default): a folder of its own inside Codync's data folder, `~/.codync/bots/`. It stays when you rename the bot, change its model, restart the computer or start a new session.-- **Choose project folder…**: an existing folder on the computer, such as a Git repository. The folder picker browses the computer's folders, wherever you are. It starts at your home folder; Back climbs to the folders above it and, on Windows, to the list of drives. Linked folders (symlinks, junctions, mounted drives) show up like any other folder.+- **Choose project folder…**: an existing folder on the computer, such as a Git repository. The folder picker browses the computer's folders, wherever you are. Start with **Recent workspaces**, or choose **Browse other folders**. In the browser, use the path breadcrumbs and **Parent folder** to move through folders or Windows drives, or **Enter folder path** to paste an absolute path (including `~/`). Search filters the visible recent list or the current folder, not the whole computer. Confirm with **Use this folder** at the bottom. Recent selections are stored on that computer and shared across its connected clients; older hosts support browsing without recent history. Linked folders (symlinks, junctions, mounted drives) show up like any other folder.Either way, the bot can work in other folders when you ask it to. A workspace isn't a sandbox: the bot can reach whatever its agent's own permissions allow. Several bots working in the same project folder can get in each other's way, and Codync doesn't create separate Git worktrees for them.Changing the folder starts a new agent session.+When there are no recent workspaces, **Browse other folders** appears first. After you choose a folder, recent workspaces and their search appear on your next visit.+## Permissions: Ask me or Approve automaticallyThe **Permissions** setting decides what happens when the agent asks to run a command, change files or use another tool.@@ -126,3 +128,15 @@ Confirm with **Delete bot and its conversation**. Deleting your lead bot leavesOn the iPhone details sheet or the desktop details panel, **Create template** shows the bot's settings as text you can copy, without its conversation.++## Custom icons++Open an existing bot's avatar picker and choose **Upload from desktop** (**Upload image** on phones), or choose **Paste URL** to reveal the address field, paste an HTTPS image address, and press the arrow button. Changes save immediately. **Tint icon** uses the bot's color; turn it off to keep the picture's original colors. **Use default** restores the character.++PNG, JPEG and WebP files can be up to 5 MiB and 4096 × 4096 pixels. SVG files can be up to 256 KiB; external images and fonts are not loaded. Codync turns the image into a static PNG no larger than 256 × 256 pixels and compresses it to at most 48 KiB. Animated files use a still image.++Sign in to the app and claim your computer before uploading. Choosing an image or Paste URL while signed out opens a sign-in prompt. The computer encrypts images before storing them in private Cloudflare R2 storage. Cached images remain available offline, and showing an icon does not download it from R2 again. New uploads and removals need a connection; a failed save keeps the previous icon. Each computer can have 128 custom icons.++On iPhone, custom pictures stay still in Live Activities and the Dynamic Island. Built-in characters keep their animations. If a cached custom image cannot load, a still default character takes its place.++In the **Terminal UI**, press Ctrl+O in a bot's settings. Enter a local file path or HTTPS URL, choose original colors, tint, or default, then press Enter. The terminal keeps its text avatar; graphical apps show your image.diff --git a/web/content/docs/getting-started.mdx b/web/content/docs/getting-started.mdxindex 7587e6e2..ddacd342 100644--- a/web/content/docs/getting-started.mdx+++ b/web/content/docs/getting-started.mdx@@ -45,6 +45,8 @@ The app first asks about an account. Signing in with Apple or Google is optionalSetup also offers an optional GitHub star. If you skip it, the desktop app can remind you once after seven days. That reminder has two actions: **Star on GitHub** opens the repository, and **Not now** dismisses it. You can also dismiss it by clicking outside the card or pressing Escape. Opening the repository or dismissing this reminder ends further reminders on that computer.+The computer menu shows a device icon beside each name, helping you distinguish a laptop, Mac mini, or Linux computer. Connection status appears alongside the name (on a separate secondary line on desktop and Android).+Press **⌘R** on macOS or **Ctrl+R** on Windows and Linux to refresh your computers. A small spinning “Loading…” indicator appears while Codync reconnects and updates the computer list. Repeated presses wait for the current refresh to finish.## Running only the host