Skip to content

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

feat(apps): page the Extensions lists (#218)

ForwardXub72dd865d0ff
diff --git a/apps/android/WhatsNew.md b/apps/android/WhatsNew.md
index bca1b329..c1195e88 100644
--- a/apps/android/WhatsNew.md
+++ b/apps/android/WhatsNew.md
@@ -12,10 +12,14 @@ else a generic "Bug fixes and improvements" line. Delete old sections.
### zh-Hant
- Bot 傳來的圖片會直接顯示在聊天裡,點一下可以放大看,不用先下載。
- 電腦上的 Codync 版本太舊時,更新提示多了「Update now」按鈕,直接從手機叫那台電腦更新。
+- 擴充套件一次顯示一個分類:智慧體、聯結器或技能,每個列表都分頁。點列表兩側的圓形按鈕或左右滑動翻頁,每頁可選 6、10、20 或 50 筆。
+- 「憑證」移到上方電腦名稱旁;「自定義聯結器」和「自己的技能」放在各自列表上方。
### en-US
- Images a bot sends now show right in the chat; tap one to see it full size, no download needed.
- When a computer's Codync is too old for this app, Update now on the notice updates that computer from your phone.
+- Extensions shows Agents, Connectors or Skills one at a time, in pages: tap the round buttons beside the list or swipe, with 6, 10, 20 or 50 per page.
+- Credentials sits beside the computer's name; Custom connector and Your own skill top their lists.
## 2.26.0
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ConnectorCatalog.kt b/apps/android/app/src/main/kotlin/com/codync/android/ConnectorCatalog.kt
new file mode 100644
index 00000000..07111e54
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ConnectorCatalog.kt
@@ -0,0 +1,77 @@
+package com.codync.android
+
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.setValue
+import com.codync.android.core.CatalogPage
+import com.codync.android.core.CatalogPaging
+import kotlinx.coroutines.CancellationException
+
+/**
+ * The connector list Extensions pages through (iOS `ConnectorCatalog`): the rows loaded so far, the
+ * registry cursor and the page on screen. A page that isn't full asks the registry until it is, or
+ * until the cursor ends.
+ */
+internal class ConnectorCatalog<T>(
+ private val id: (T) -> String,
+ private val fetch: suspend (search: String, cursor: String?) -> Pair<List<T>, String?>,
+) {
+ var items by mutableStateOf(CatalogPage<T>()); private set
+ /** The registry page after the ones loaded; null at the end. */
+ var cursor by mutableStateOf<String?>(null); private set
+ /** The page on screen. While the registry fills it, it can be the page past the loaded rows. */
+ var page by mutableIntStateOf(0); private set
+ var loading by mutableStateOf(true); private set
+ var loadingMore by mutableStateOf(false); private set
+ var error by mutableStateOf<String?>(null); private set
+ private var request = 0
+ private var query = ""
+
+ val hasMore: Boolean get() = cursor != null
+
+ /** The first registry page for `search`; answers to an older search are dropped. */
+ suspend fun load(search: String) {
+ val mine = ++request
+ query = search; loading = true; loadingMore = false
+ try {
+ val (rows, next) = fetch(search, null)
+ if (request != mine) return
+ items = CatalogPage<T>().append(rows, id); cursor = next?.takeIf(String::isNotBlank); page = 0; error = null
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) {
+ if (request != mine) return
+ items = CatalogPage(); cursor = null; error = failure.message ?: "Couldn't load connectors."
+ } finally { if (request == mine) loading = false }
+ }
+
+ /** Turns to `next` at once, so a swipe stays where it landed; `fill` then loads its rows. */
+ fun show(next: Int, size: Int) {
+ if (!loading) page = CatalogPaging.clamp(next, items.items.size, size, hasMore)
+ }
+
+ /**
+ * Asks the registry until the page on screen is full or the cursor ends. A page turned meanwhile
+ * is filled by the same loop. If a page fails, the list goes back to the last page with rows.
+ */
+ suspend fun fill(size: Int) {
+ if (loading || loadingMore || !hasMore || !CatalogPaging.needsFetch(items.items.size, page, size)) return
+ val mine = request
+ loadingMore = true
+ try {
+ while (true) {
+ val at = cursor ?: break
+ if (!CatalogPaging.needsFetch(items.items.size, page, size)) break
+ val (rows, next) = fetch(query, at)
+ if (request != mine) return
+ items = items.append(rows, id); cursor = next?.takeIf(String::isNotBlank)
+ }
+ page = CatalogPaging.clamp(page, items.items.size, size, hasMore); error = null
+ } catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) {
+ if (request != mine) return
+ error = failure.message ?: "Couldn't load more connectors."
+ page = CatalogPaging.clamp(page, items.items.size, size)
+ } finally { if (request == mine) loadingMore = false }
+ }
+}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MarketPager.kt b/apps/android/app/src/main/kotlin/com/codync/android/MarketPager.kt
new file mode 100644
index 00000000..0e24c83a
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/MarketPager.kt
@@ -0,0 +1,169 @@
+package com.codync.android
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxWithConstraints
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.ExperimentalLayoutApi
+import androidx.compose.foundation.layout.FlowRow
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.offset
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.pager.HorizontalPager
+import androidx.compose.foundation.pager.rememberPagerState
+import androidx.compose.foundation.selection.selectable
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.key
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.rememberUpdatedState
+import androidx.compose.runtime.snapshotFlow
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.CatalogPaging
+import com.codync.android.design.*
+import com.kyant.shapes.Capsule
+import com.kyant.shapes.RoundedRectangle
+import kotlin.math.abs
+import kotlinx.coroutines.launch
+
+// Extensions' sections and paging (iOS `MarketplaceTabs` + `CatalogPager`): the section rail, the pager a
+// list turns in, and the bar under it.
+
+/** Narrower than this, a list is a pager with previous and next beside it, and the bar keeps only the size and the page. */
+private val PhonePagerWidth = 560.dp
+
+internal enum class ExtensionSection(val title: String, val icon: String, val source: String) {
+ Agents("Agents", "terminal", "Agents come from the ACP registry and install on {name}."),
+ Connectors("Connectors", "point.3.connected.trianglepath.dotted", "Connectors come from the official MCP Registry and install on {name}."),
+ Skills("Skills", "book.pages", "Skills come from Anthropic and install on {name}."),
+}
+
+/** Agents, Connectors, Skills: the chosen row is filled, like a side tab. */
+@Composable internal fun ExtensionRail(selection: ExtensionSection, select: (ExtensionSection) -> Unit) {
+ Column(Modifier.width(168.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ for (section in ExtensionSection.entries) {
+ val on = section == selection
+ Row(Modifier.fillMaxWidth().clip(RoundedRectangle(12.dp))
+ .background(if (on) Palette.bubbleAgent else Color.Transparent)
+ .selectable(selected = on, role = Role.Tab) { select(section) }
+ .padding(horizontal = 12.dp, vertical = 8.dp),
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ Symbol(section.icon, size = 16.dp, tint = if (on) Palette.text else Palette.secondary)
+ Text(tr(section.title), style = if (on) Type.subheadline.semibold else Type.subheadline,
+ color = if (on) Palette.text else Palette.secondary, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+ }
+ }
+}
+
+/**
+ * On a phone the list is a pager: swipe or the side buttons turn it, and `settle` hears where it came to rest.
+ * When the page moves from outside (search, page size, a failed fetch), the pager follows `page` back.
+ * A wide layout shows the one page.
+ */
+@Composable internal fun FlankedPager(page: Int, count: Int, pageSize: Int, hasMore: Boolean = false, loading: Boolean = false,
+ settle: (Int) -> Unit, content: @Composable (Int) -> Unit) {
+ val scope = rememberCoroutineScope()
+ val still = reduceMotion()
+ val pages = CatalogPaging.pageCount(count, pageSize, hasMore)
+ val current = CatalogPaging.clamp(page, count, pageSize, hasMore)
+ BoxWithConstraints(Modifier.fillMaxWidth()) {
+ if (maxWidth >= PhonePagerWidth) content(current)
+ else key(pageSize) {
+ val pager = rememberPagerState(current) { pages }
+ val onSettle by rememberUpdatedState(settle)
+ LaunchedEffect(pager) { snapshotFlow { pager.settledPage }.collect { onSettle(it) } }
+ LaunchedEffect(current, loading) {
+ val from = pager.settledPage
+ if (loading || from == current) return@LaunchedEffect
+ if (still || abs(from - current) > 1) pager.scrollToPage(current) else pager.animateScrollToPage(current)
+ }
+ fun turn(by: Int) {
+ scope.launch { (pager.currentPage + by).let { if (still) pager.scrollToPage(it) else pager.animateScrollToPage(it) } }
+ }
+ Box(Modifier.fillMaxWidth()) {
+ HorizontalPager(pager, Modifier.fillMaxWidth(), pageSpacing = 20.dp, userScrollEnabled = !loading,
+ verticalAlignment = Alignment.Top) { content(it) }
+ if (pages > 1) {
+ PageEdgeButton("Previous page", "chevron.left", current > 0 && !loading, Modifier.align(Alignment.CenterStart).offset(x = (-40).dp)) { turn(-1) }
+ PageEdgeButton(if (loading) "Loading…" else "Next page", "chevron.right", CatalogPaging.canForward(count, current, hasMore, pageSize) && !loading,
+ Modifier.align(Alignment.CenterEnd).offset(x = 40.dp)) { turn(1) }
+ }
+ }
+ }
+ }
+}
+
+/** Previous or next, beside the list on a phone: filled in the text color so it reads as a control, faint when there is no page that way. */
+@Composable private fun PageEdgeButton(title: String, symbol: String, enabled: Boolean, modifier: Modifier = Modifier, action: () -> Unit) {
+ Box(modifier.size(36.dp).graphicsLayer { alpha = if (enabled) 1f else 0.25f }.clip(CircleShape).background(Palette.text)
+ .plainButton(enabled = enabled, action = action), contentAlignment = Alignment.Center) {
+ Symbol(symbol, size = 15.dp, tint = Palette.background, contentDescription = tr(title))
+ }
+}
+
+/** Count, page size, previous, current / total, and next. */
+@OptIn(ExperimentalLayoutApi::class)
+@Composable internal fun CatalogPager(page: Int, count: Int, pageSize: Int, hasMore: Boolean = false, loading: Boolean = false,
+ go: (Int) -> Unit, onSize: (Int) -> Unit) {
+ val pages = CatalogPaging.pageCount(count, pageSize, hasMore)
+ val current = CatalogPaging.clamp(page, count, pageSize, hasMore)
+ val total = tr("{count} total").replace("{count}", "$count")
+ val canPrev = current > 0 && !loading
+ val canNext = CatalogPaging.canForward(count, current, hasMore, pageSize) && !loading
+ @Composable fun SizeLabel() {
+ DropdownMenu(items = {
+ CatalogPaging.pageSizes.map { size -> MenuItem("$size / page", selected = size == pageSize) { onSize(size) } }
+ }) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text(tr("$pageSize / page"), style = Type.footnote, color = Palette.secondary)
+ Symbol("chevron.down", size = 10.dp, tint = Palette.secondary)
+ }
+ }
+ }
+ @Composable fun SizeMenu() {
+ Text(tr("Per page"), style = Type.footnote, color = Palette.secondary)
+ DropdownMenu(items = {
+ CatalogPaging.pageSizes.map { size -> MenuItem("$size / page", selected = size == pageSize) { onSize(size) } }
+ }) {
+ Row(Modifier.clip(RoundedRectangle(8.dp)).background(Palette.bubbleAgent).padding(horizontal = 10.dp).height(28.dp),
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) {
+ Text(tr("$pageSize / page"), style = Type.footnote, color = Palette.text)
+ Symbol("chevron.down", size = 10.dp, tint = Palette.secondary)
+ }
+ }
+ }
+ BoxWithConstraints(Modifier.fillMaxWidth()) {
+ if (maxWidth < PhonePagerWidth) {
+ // Previous and next sit beside the list; the capsule keeps the page size and the page number.
+ Row(Modifier.fillMaxWidth().clip(Capsule()).background(Palette.bubbleAgent).padding(horizontal = 16.dp, vertical = 8.dp),
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween) {
+ SizeLabel()
+ Text("${current + 1} / $pages", style = Type.subheadline.semibold, color = Palette.text)
+ }
+ } else FlowRow(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp),
+ itemVerticalAlignment = Alignment.CenterVertically) {
+ Text(total, style = Type.footnote, color = Palette.secondary)
+ SizeMenu()
+ IconButton("Previous page", "chevron.left", enabled = canPrev) { go(current - 1) }
+ Text("${current + 1} / $pages", style = Type.footnote, color = Palette.text)
+ IconButton(if (loading) "Loading…" else "Next page", "chevron.right", enabled = canNext) { go(current + 1) }
+ }
+ }
+}
+
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.kt
index 3ed3f404..99210e23 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
@@ -24,6 +24,7 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
@@ -33,7 +34,6 @@ import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.contentDescription
-import androidx.compose.ui.semantics.heading
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
@@ -47,14 +47,7 @@ import com.codync.android.design.*
import com.kyant.shapes.Capsule
import com.kyant.shapes.RoundedRectangle
-// The Extensions page's building blocks (iOS `MarketRows`): sections, rows, agent cards and logos.
-
-@Composable internal fun MarketSection(title: String, content: @Composable () -> Unit) {
- Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
- Text(tr(title), Modifier.padding(start = 4.dp).semantics { heading() }, style = Type.headline, color = Palette.text)
- content()
- }
-}
+// The Extensions page's building blocks (iOS `MarketRows`): rows, agent cards and logos.
/** One catalog item: its icon, name and line, then Add (or a check once added). */
@Composable internal fun MarketRow(title: String, subtitle: String, added: Boolean, busy: Boolean = false, addLabel: String = "Add",
@@ -79,8 +72,13 @@ import com.kyant.shapes.RoundedRectangle
}
}
+/** A catalog row's room, with nothing in it (an added row has nothing to tap). A short last page keeps a full page of rows. */
+@Composable internal fun MarketRowSpacer() {
+ Box(Modifier.alpha(0f).clearAndSetSemantics {}) { MarketRow(" ", " ", added = true, icon = {}) {} }
+}
+
/** An agent in the Agents row: its logo on a tile, its name and where it stands. */
-@Composable internal fun AgentCard(backend: AgentBackend, action: () -> Unit) {
+@Composable internal fun AgentCard(backend: AgentBackend, modifier: Modifier = Modifier.width(128.dp), action: () -> Unit) {
val status = when {
!backend.installed && backend.curated -> "Not installed"
backend.needsNode -> "Needs Node.js"
@@ -88,15 +86,25 @@ import com.kyant.shapes.RoundedRectangle
backend.signedIn == false -> "Not signed in"
else -> "Installed"
}
- Column(Modifier.width(128.dp).clip(RoundedRectangle(18.dp)).background(Palette.bubbleAgent.copy(alpha = 0.45f)).plainButton(action = action)
- .semantics(mergeDescendants = true) {}.padding(horizontal = 10.dp, vertical = 18.dp),
+ AgentCardBody(modifier.clip(RoundedRectangle(18.dp)).background(Palette.bubbleAgent.copy(alpha = 0.45f)).plainButton(action = action)
+ .semantics(mergeDescendants = true) {}, backend.registry ?: backend.id, backend.name, tr(status))
+}
+
+/** An agent tile's room, with nothing in it. A short last page keeps a full page of rows, so the bar under it stays put. */
+@Composable internal fun AgentCardSpacer(modifier: Modifier = Modifier) {
+ AgentCardBody(modifier.alpha(0f).clearAndSetSemantics {}, null, " ", " ")
+}
+
+/** An agent tile's logo, name and status line. */
+@Composable private fun AgentCardBody(modifier: Modifier, registry: String?, name: String, status: String) {
+ Column(modifier.padding(horizontal = 10.dp, vertical = 14.dp),
horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(12.dp)) {
- Box(Modifier.size(64.dp).clip(RoundedRectangle(18.dp)).background(Palette.bubbleAgent), contentAlignment = Alignment.Center) {
- AgentIcon(backend.registry ?: backend.id, 34.dp)
+ Box(Modifier.size(56.dp).clip(RoundedRectangle(16.dp)).background(Palette.bubbleAgent), contentAlignment = Alignment.Center) {
+ AgentIcon(registry, 30.dp)
}
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(2.dp)) {
- Text(backend.name, style = Type.subheadline.semibold, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)
- Text(tr(status), style = Type.caption, color = Palette.secondary, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Text(name, style = Type.subheadline.semibold, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Text(status, style = Type.caption, color = Palette.secondary, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
}
@@ -117,14 +125,18 @@ private val AGENT_TINTS = mapOf("claude-acp" to 0xFFD97857, "gemini" to 0xFF9178
/** Placeholder rows while a list loads, shaped like the real ones. */
@Composable internal fun SkeletonRows() {
val dim by rememberInfiniteTransition(label = "Skeleton").animateFloat(1f, 0.5f, infiniteRepeatable(tween(900), RepeatMode.Reverse), label = "Dim")
- Column(Modifier.graphicsLayer { alpha = dim }.clearAndSetSemantics { contentDescription = "Loading" }) {
- repeat(4) {
- Row(Modifier.padding(horizontal = 12.dp, vertical = 10.dp), verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.spacedBy(14.dp)) {
- Box(Modifier.size(46.dp).clip(RoundedRectangle(12.dp)).background(Palette.bubbleAgent))
- Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
- Box(Modifier.size(120.dp, 12.dp).clip(Capsule()).background(Palette.bubbleAgent))
- Box(Modifier.size(190.dp, 10.dp).clip(Capsule()).background(Palette.bubbleAgent))
+ val loading = tr("Loading…")
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(loading, style = Type.footnote, color = Palette.secondary)
+ Column(Modifier.graphicsLayer { alpha = dim }.clearAndSetSemantics { contentDescription = loading }) {
+ repeat(4) {
+ Row(Modifier.padding(horizontal = 12.dp, vertical = 10.dp), verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(14.dp)) {
+ Box(Modifier.size(46.dp).clip(RoundedRectangle(12.dp)).background(Palette.bubbleAgent))
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Box(Modifier.size(120.dp, 12.dp).clip(Capsule()).background(Palette.bubbleAgent))
+ Box(Modifier.size(190.dp, 10.dp).clip(Capsule()).background(Palette.bubbleAgent))
+ }
}
}
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/MarketplaceView.kt b/apps/android/app/src/main/kotlin/com/codync/android/MarketplaceView.kt
index c4d3fe80..5e76a879 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/MarketplaceView.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/MarketplaceView.kt
@@ -9,15 +9,14 @@ import androidx.compose.animation.togetherWith
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
-import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
-import androidx.compose.foundation.lazy.LazyRow
-import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.verticalScroll
@@ -33,27 +32,24 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
-import androidx.compose.ui.layout.layout
-import androidx.compose.ui.unit.Dp
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import androidx.compose.ui.text.style.TextOverflow
import com.codync.android.core.AgentBackend
-import com.codync.android.core.CatalogPage
+import com.codync.android.core.CatalogPaging
import com.codync.android.core.MarketConnector
import com.codync.android.core.MarketSkill
import com.codync.android.design.*
import com.kyant.shapes.Capsule
import com.kyant.shapes.RoundedRectangle
-import java.util.UUID
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.launch
/**
- * Extensions (iOS `MarketplaceView`): one page of agents, connectors, apps and skills for the bots on
- * this computer. Installing happens on the computer; each bot turns connectors and skills on in its settings.
+ * Extensions (iOS `MarketplaceView`): Agents, Connectors and Skills, one at a time, each paged.
+ * Installing happens on the computer; each bot turns connectors and skills on in its settings.
*/
@Composable internal fun MarketplaceView(state: AppState, store: AppStore) {
var showInstalled by remember { mutableStateOf(false) }
@@ -69,14 +65,9 @@ import kotlinx.coroutines.launch
val dismiss = LocalDismissModal.current
val scope = rememberCoroutineScope()
var search by remember { mutableStateOf("") }
- // Bumped on each submitted search, so every section searches again.
- var connectors by remember { mutableStateOf(CatalogPage<MarketConnector>()) }
- var connectorRequest by remember { mutableStateOf("") }
- var connectorQuery by remember { mutableStateOf("") }
- // The registry page after the ones shown; null at the end.
- var connectorCursor by remember { mutableStateOf<String?>(null) }
- var loadingConnectors by remember { mutableStateOf(true) }
- var loadingMore by remember { mutableStateOf(false) }
+ val connectors = remember(store) {
+ ConnectorCatalog<MarketConnector>({ it.name }) { search, cursor -> store.marketConnectors(search, cursor).let { it.items to it.nextCursor } }
+ }
var skills by remember { mutableStateOf(emptyList<MarketSkill>()) }
var loadingSkills by remember { mutableStateOf(true) }
var error by remember { mutableStateOf<String?>(null) }
@@ -88,42 +79,26 @@ import kotlinx.coroutines.launch
var agent by remember { mutableStateOf<AgentBackend?>(null) }
var addingNode by remember { mutableStateOf(false) }
var showCredentials by remember { mutableStateOf(false) }
- // Agents shown before "Load more agents".
- var agentLimit by remember { mutableIntStateOf(10) }
+ var section by remember { mutableStateOf(ExtensionSection.Agents) }
+ var agentPage by remember { mutableIntStateOf(0) }
+ var skillPage by remember { mutableIntStateOf(0) }
+ var pageSize by remember { mutableIntStateOf(CatalogPaging.phonePageSize) }
+ var pickedPageSize by remember { mutableStateOf(false) }
val query = search.trim()
- suspend fun loadConnectors() {
- val request = UUID.randomUUID().toString()
- connectorRequest = request; connectorQuery = query; loadingConnectors = true; loadingMore = false
- try {
- val page = store.marketConnectors(query, null)
- if (connectorRequest != request) return
- connectors = CatalogPage<MarketConnector>().append(page.items) { it.name }; connectorCursor = page.nextCursor?.takeIf(String::isNotBlank); error = null
- } catch (cancelled: CancellationException) { throw cancelled }
- catch (failure: Exception) {
- if (connectorRequest != request) return
- connectors = CatalogPage(); connectorCursor = null; error = failure.message ?: "Couldn't load connectors."
- } finally { if (connectorRequest == request) loadingConnectors = false }
- }
- fun loadMoreConnectors() {
- if (loadingMore || loadingConnectors) return
- if (connectors.hasHidden) { connectors = connectors.reveal(); return }
- val cursor = connectorCursor ?: return
- val request = connectorRequest
- loadingMore = true
- scope.launch {
- try {
- val page = store.marketConnectors(connectorQuery, cursor)
- if (connectorRequest != request) return@launch
- connectors = connectors.append(page.items) { it.name }.reveal()
- connectorCursor = page.nextCursor?.takeIf { it.isNotBlank() && it != cursor }; error = null
- } catch (cancelled: CancellationException) { throw cancelled }
- catch (failure: Exception) { if (connectorRequest == request) error = failure.message ?: "Couldn't load more connectors." }
- finally { if (connectorRequest == request) loadingMore = false }
- }
+ /**
+ * A size picked from the menu, or one that follows the layout, starts every list over in the same change as
+ * the size, so no pager is ever built for the new size at the old page.
+ */
+ fun resize(size: Int) { pageSize = size; agentPage = 0; skillPage = 0; connectors.show(0, size) }
+ fun changePageSize(size: Int) { pickedPageSize = true; resize(size) }
+ /** Turns the connector list to `page` at once; a page that isn't full then fills from the registry. */
+ fun showConnectorPage(page: Int) {
+ connectors.show(page, pageSize)
+ scope.launch { connectors.fill(pageSize) }
}
- fun submit() { agentLimit = 10; scope.launch { loadConnectors() } }
+ fun submit() { scope.launch { connectors.load(query) } }
LaunchedEffect(Unit) { store.refreshPlugins(); store.refreshBackends() }
- LaunchedEffect(Unit) { loadConnectors() }
+ LaunchedEffect(Unit) { connectors.load(query) }
LaunchedEffect(Unit) {
try { skills = store.marketSkills() }
catch (cancelled: CancellationException) { throw cancelled }
@@ -135,43 +110,58 @@ import kotlinx.coroutines.launch
val installedSkills = state.plugins?.skills.orEmpty()
val shownSkills = if (query.isEmpty()) skills else skills.filter { it.name.contains(query, true) || it.description.contains(query, true) }
val inset = Modifier.padding(horizontal = 44.dp)
- Box(Modifier.fillMaxSize().background(Palette.background)) {
- Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(vertical = 20.dp), verticalArrangement = Arrangement.spacedBy(28.dp)) {
- Header(state, inset, showInstalled)
- SearchBox(search, { search = it }, inset, ::submit) { search = ""; submit() }
- if (agents.isNotEmpty()) Box(inset) {
- MarketSection(if (query.isEmpty()) "Agents" else tr("Agents matching “{query}”").replace("{query}", query)) {
- if (backends.any { it.needsNode }) NodeNotice(state) { addingNode = true }
- // The row runs edge to edge, past the page's margins.
- LazyRow(Modifier.bleed(24.dp), contentPadding = PaddingValues(horizontal = 24.dp),
- horizontalArrangement = Arrangement.spacedBy(10.dp)) {
- items(agents.take(agentLimit), key = { it.id }) { backend -> AgentCard(backend) { agent = backend } }
+ fun changeSearch(next: String) { search = next; agentPage = 0; skillPage = 0 }
+ fun pagePad(count: Int, shown: Int) = if (count > pageSize) maxOf(0, pageSize - shown) else 0
+ @Composable fun Pins() {
+ if (section == ExtensionSection.Agents && backends.any { it.needsNode }) NodeNotice(state) { addingNode = true }
+ if (section == ExtensionSection.Connectors) MarketRow("Custom connector", "Any MCP server: a command or a URL", added = false, addLabel = "New",
+ icon = { TileIcon("point.3.connected.trianglepath.dotted") }) { addingConnector = true }
+ if (section == ExtensionSection.Skills) MarketRow("Your own skill", "Write instructions a bot can follow", added = false, addLabel = "New",
+ icon = { TileIcon("square.and.pencil") }) { writingSkill = true }
+ }
+ @Composable fun Lists() {
+ when (section) {
+ ExtensionSection.Agents -> if (agents.isEmpty()) Text(if (query.isEmpty()) tr("No agents yet.") else tr("No agents match “{query}”.").replace("{query}", query), style = Type.body, color = Palette.secondary)
+ else {
+ FlankedPager(agentPage, agents.size, pageSize, settle = { agentPage = it }) { index ->
+ val shown = CatalogPaging.slice(agents, index, pageSize)
+ val slots = buildList<AgentBackend?> {
+ addAll(shown)
+ repeat(pagePad(agents.size, shown.size)) { add(null) }
}
- if (agents.size > agentLimit) Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
- SecondaryButton("Load more agents") { agentLimit += 10 }
+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ for (row in slots.chunked(2)) Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ for (backend in row) if (backend != null) AgentCard(backend, Modifier.weight(1f)) { agent = backend }
+ else AgentCardSpacer(Modifier.weight(1f))
+ if (row.size == 1) Spacer(Modifier.weight(1f))
+ }
}
}
}
- Box(inset) {
- MarketSection("Connectors") {
- when {
- loadingConnectors -> SkeletonRows()
- connectors.items.isEmpty() -> Text(if (query.isEmpty()) tr("Couldn't load connectors.") else tr("No connectors match “{query}”.").replace("{query}", query), style = Type.body, color = Palette.secondary)
- else -> Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
- for (c in connectors.visible) MarketRow(c.title, c.description ?: c.name, c.installed,
+ ExtensionSection.Connectors -> when {
+ connectors.loading -> SkeletonRows()
+ connectors.items.items.isEmpty() -> Text(if (query.isEmpty()) tr("Couldn't load connectors.") else tr("No connectors match “{query}”.").replace("{query}", query), style = Type.body, color = Palette.secondary)
+ else -> {
+ val rows = connectors.items.items
+ FlankedPager(connectors.page, rows.size, pageSize, connectors.hasMore, connectors.loadingMore, ::showConnectorPage) { index ->
+ val shown = CatalogPaging.slice(rows, index, pageSize)
+ // The page past the loaded rows, while the registry fills it.
+ if (shown.isEmpty()) SkeletonRows()
+ else Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ for (c in shown) MarketRow(c.title, c.description ?: c.name, c.installed,
icon = { ServiceLogo(c.website, c.title, c.name) }) { installing = c }
- if (connectors.hasHidden || connectorCursor != null) Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
- SecondaryButton(if (loadingMore) "Loading…" else "Load more connectors", enabled = !loadingMore, action = ::loadMoreConnectors)
- }
+ repeat(pagePad(rows.size, shown.size)) { MarketRowSpacer() }
}
}
}
}
- Box(inset) {
- MarketSection("Skills") {
- if (loadingSkills) SkeletonRows()
- else Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
- for (s in shownSkills) {
+ ExtensionSection.Skills -> if (loadingSkills) SkeletonRows()
+ else if (query.isNotEmpty() && shownSkills.isEmpty()) Text(tr("No skills match “{query}”.").replace("{query}", query), style = Type.body, color = Palette.secondary)
+ else {
+ FlankedPager(skillPage, shownSkills.size, pageSize, settle = { skillPage = it }) { index ->
+ val shown = CatalogPaging.slice(shownSkills, index, pageSize)
+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ for (s in shown) {
val added = s.installed || installedSkills.any { it.id == s.source.lowercase() }
MarketRow(s.name, s.description, added, busy = busySkill == s.source,
open = { viewingSkill = SkillRef("catalog/${s.source}", s.name, s.description, s.source, added) }, icon = { SkillGlyph() }) {
@@ -184,35 +174,63 @@ import kotlinx.coroutines.launch
}
}
}
+ repeat(pagePad(shownSkills.size, shown.size)) { MarketRowSpacer() }
}
}
}
- Box(inset) {
- SecondaryButton({ showCredentials = true }) {
- Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
- Symbol("lock.shield", size = 18.dp, tint = Palette.text)
- Text(tr("Credentials"))
- }
- }
+ }
+ }
+ @Composable fun Pagers() {
+ when (section) {
+ ExtensionSection.Agents -> CatalogPager(agentPage, agents.size, pageSize, go = { agentPage = CatalogPaging.clamp(it, agents.size, pageSize) }, onSize = ::changePageSize)
+ ExtensionSection.Connectors -> if (!connectors.loading) CatalogPager(connectors.page, connectors.items.items.size, pageSize, connectors.hasMore,
+ connectors.loadingMore, ::showConnectorPage, ::changePageSize)
+ ExtensionSection.Skills -> if (!loadingSkills) CatalogPager(skillPage, shownSkills.size, pageSize, go = { skillPage = CatalogPaging.clamp(it, shownSkills.size, pageSize) }, onSize = ::changePageSize)
+ }
+ }
+ @Composable fun SourceLine() {
+ Text(tr(section.source).replace("{name}", state.hostName), style = Type.footnote, color = Palette.tertiary)
+ }
+ @Composable fun Foot() {
+ (error ?: connectors.error)?.let { Text(tr(it), style = Type.footnote, color = Palette.danger) }
+ }
+ Box(Modifier.fillMaxSize().background(Palette.background)) {
+ BoxWithConstraints(Modifier.fillMaxSize()) {
+ val wide = maxWidth >= 760.dp
+ LaunchedEffect(wide, pickedPageSize) {
+ val size = if (wide) CatalogPaging.pageSize else CatalogPaging.phonePageSize
+ if (!pickedPageSize && size != pageSize) resize(size)
}
- Box(inset) {
- MarketSection("Make your own") {
- Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
- MarketRow("Custom connector", "Any MCP server: a command or a URL", added = false, addLabel = "New",
- icon = { TileIcon("point.3.connected.trianglepath.dotted") }) { addingConnector = true }
- MarketRow("Your own skill", "Write instructions a bot can follow", added = false, addLabel = "New",
- icon = { TileIcon("square.and.pencil") }) { writingSkill = true }
+ Column(Modifier.fillMaxSize().padding(vertical = 20.dp), verticalArrangement = Arrangement.spacedBy(20.dp)) {
+ Header(state, inset, showInstalled) { showCredentials = true }
+ SearchBox(search, ::changeSearch, inset, ::submit) { changeSearch(""); submit() }
+ if (wide) Row(Modifier.weight(1f).padding(horizontal = 44.dp), horizontalArrangement = Arrangement.spacedBy(20.dp)) {
+ ExtensionRail(section) { section = it }
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ SourceLine()
+ Pins()
+ Column(Modifier.weight(1f).verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Lists()
+ Pagers()
+ }
+ Foot()
+ }
+ } else Column(Modifier.weight(1f).verticalScroll(rememberScrollState()).then(inset), verticalArrangement = Arrangement.spacedBy(16.dp)) {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ TabChoice(section, ExtensionSection.entries.map { it to it.title }, { section = it })
+ SourceLine()
}
+ Pins()
+ Lists()
+ Pagers()
+ Foot()
}
}
- error?.let { Text(tr(it), inset, style = Type.footnote, color = Palette.danger) }
- Text(tr("Connectors come from the official MCP Registry, skills from Anthropic, agents from the ACP registry. Everything installs on {name}.").replace("{name}", state.hostName),
- inset, style = Type.footnote, color = Palette.tertiary)
}
// The sheet's own close, over the page.
Box(Modifier.align(Alignment.TopEnd).padding(8.dp)) { IconButton("Close", "xmark", action = dismiss) }
}
- CodyncSheet(installing, { installing = null }) { InstallConnectorSheet(it, state, store) { scope.launch { loadConnectors() } } }
+ CodyncSheet(installing, { installing = null }) { InstallConnectorSheet(it, state, store) { submit() } }
CodyncSheet(showCredentials, { showCredentials = false }) { CredentialsView(state, store) }
CodyncSheet(addingConnector, { addingConnector = false }) { CustomConnectorSheet(state, store) }
CodyncSheet(viewingSkill, { viewingSkill = null }) { SkillSheet(it, state, store) }
@@ -221,25 +239,24 @@ import kotlinx.coroutines.launch
CodyncSheet(addingNode, { addingNode = false }) { SetupTerminal(null, "node", null, state, store) { addingNode = false } }
}
-/** Widens a child past its parent's margins by `amount` on each side. */
-private fun Modifier.bleed(amount: Dp) = layout { measurable, constraints ->
- val extra = amount.roundToPx()
- val width = constraints.maxWidth + 2 * extra
- val placeable = measurable.measure(constraints.copy(minWidth = width, maxWidth = width))
- layout(constraints.maxWidth, placeable.height) { placeable.place(-extra, 0) }
-}
-
-/** The computer it all lives on, and the way to what's installed. */
-@Composable private fun Header(state: AppState, modifier: Modifier, showInstalled: () -> Unit) {
+/** The computer it all lives on, credentials beside the title, and the way to what's installed. */
+@Composable private fun Header(state: AppState, modifier: Modifier, showInstalled: () -> Unit, showCredentials: () -> Unit) {
val connectors = state.plugins?.connectors.orEmpty()
val count = connectors.size + state.plugins?.skills.orEmpty().size
Column(modifier.padding(top = 28.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
- Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
ComputerBadge(state.hello?.text("device"), 32.dp, state.computers.firstOrNull()?.color)
- Column {
+ Column(Modifier.weight(1f)) {
Text(tr("Extensions"), style = Type.title2.semibold, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(state.hostName, style = Type.subheadline, color = Palette.secondary, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
+ // Beside the title, in the room left of Close, so the list can fill the screen.
+ SecondaryButton(showCredentials) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Symbol("lock.shield", size = 18.dp, tint = Palette.text)
+ Text(tr("Credentials"), maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+ }
}
if (count > 0) Row(Modifier.plainButton(action = showInstalled), verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)) {
diff --git a/apps/android/app/src/test/kotlin/com/codync/android/ConnectorCatalogTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/ConnectorCatalogTest.kt
new file mode 100644
index 00000000..7d05f0c8
--- /dev/null
+++ b/apps/android/app/src/test/kotlin/com/codync/android/ConnectorCatalogTest.kt
@@ -0,0 +1,40 @@
+package com.codync.android
+
+import kotlinx.coroutines.runBlocking
+import org.junit.Assert.*
+import org.junit.Test
+
+class ConnectorCatalogTest {
+ @Test fun aConnectorPageFillsUntilFullAndFallsBackWhenItCannot() = runBlocking {
+ val asked = mutableListOf<String?>()
+ var offline = false
+ val catalog = ConnectorCatalog<Int>({ it.toString() }) { _, cursor ->
+ asked += cursor
+ if (offline) error("offline")
+ when (cursor) {
+ null -> (0 until 15).toList() to "a"
+ "a" -> (15 until 18).toList() to "b"
+ else -> (18 until 25).toList() to "c"
+ }
+ }
+ catalog.load("")
+ assertEquals(15, catalog.items.items.size)
+
+ // Page 2 needs rows 10-19: two registry pages fill it.
+ catalog.show(1, 10)
+ catalog.fill(10)
+ assertEquals(listOf(null, "a", "b"), asked)
+ assertEquals(1, catalog.page)
+ assertEquals(25, catalog.items.items.size)
+ assertEquals("c", catalog.cursor)
+
+ // The page past the loaded rows fails: back to the last page with rows.
+ offline = true
+ catalog.show(3, 10)
+ assertEquals(3, catalog.page)
+ catalog.fill(10)
+ assertEquals(2, catalog.page)
+ assertEquals("offline", catalog.error)
+ assertFalse(catalog.loadingMore)
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Market.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Market.kt
index 4eadf394..9ed64f5b 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Market.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Market.kt
@@ -20,13 +20,42 @@ data class PluginListing(val connectors: List<InstalledConnector>, val skills: L
@Serializable data class MarketConnectors(val items: List<MarketConnector>, val nextCursor: String? = null)
@Serializable data class MarketSkill(val source: String, val name: String, val description: String = "", val installed: Boolean = false)
-/** Registry metadata stays in memory; rows are revealed by explicit user actions. */
-data class CatalogPage<T>(val items: List<T> = emptyList(), val visibleCount: Int = 12) {
- val visible: List<T> get() = items.take(visibleCount)
- val hasHidden: Boolean get() = items.size > visibleCount
+/** Registry metadata stays in memory. The Extensions tabs page through it. */
+data class CatalogPage<T>(val items: List<T> = emptyList()) {
fun append(page: List<T>, id: (T) -> String): CatalogPage<T> {
val known = items.mapTo(mutableSetOf(), id)
return copy(items = items + page.filter { known.add(id(it)) })
}
- fun reveal(): CatalogPage<T> = copy(visibleCount = minOf(items.size, visibleCount + 12))
+}
+
+/** How many catalog rows one Extensions page shows, and which page a click lands on. */
+object CatalogPaging {
+ const val pageSize = 10
+ /** Two agent tiles across, three rows: a page has no leftover card. */
+ const val phonePageSize = 6
+ val pageSizes = listOf(6, 10, 20, 50)
+
+ /** Loaded rows split into pages. While the registry still has a cursor, one more page is offered so the bar is never 1 / 1 for a list that continues. */
+ fun pageCount(count: Int, size: Int = pageSize, hasMore: Boolean = false): Int {
+ val loaded = if (count <= 0) 1 else (count + size - 1) / size
+ return if (hasMore) loaded + 1 else loaded
+ }
+
+ fun clamp(page: Int, count: Int, size: Int = pageSize, hasMore: Boolean = false): Int =
+ page.coerceIn(0, pageCount(count, size, hasMore) - 1)
+
+ fun <T> slice(items: List<T>, page: Int, size: Int = pageSize): List<T> {
+ val start = page.coerceAtLeast(0) * size
+ return items.drop(start).take(size)
+ }
+
+ /** Next stays available through the last shown page, including the page that still has to be fetched. */
+ fun canForward(count: Int, page: Int, hasMore: Boolean, size: Int = pageSize): Boolean =
+ page < pageCount(count, size, hasMore) - 1
+
+ /** A later page that isn't full yet, so the registry has to be asked. The first page is whatever the first answer held. */
+ fun needsFetch(count: Int, page: Int, size: Int = pageSize): Boolean {
+ val start = page.coerceAtLeast(0) * size
+ return start > 0 && start + size > count
+ }
}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/MarketTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/MarketTest.kt
index a02d5c50..3781f8e6 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/MarketTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/MarketTest.kt
@@ -4,17 +4,40 @@ import org.junit.Assert.*
import org.junit.Test
class MarketTest {
- @Test fun catalogPagesDeduplicateAndRevealOnlyOnRequest() {
+ @Test fun catalogPagesDeduplicate() {
val page = CatalogPage<String>().append((1..25).map(Int::toString)) { it }
- assertEquals(12, page.visible.size)
- assertTrue(page.hasHidden)
+ assertEquals(25, page.items.size)
val next = page.append(listOf("2", "26", "26")) { it }
assertEquals(26, next.items.size)
- assertEquals(12, next.visible.size)
- assertEquals(24, next.reveal().visible.size)
- assertEquals(26, next.reveal().reveal().visible.size)
- assertFalse(next.reveal().reveal().hasHidden)
}
+
+ @Test fun catalogPagingClampsAndFetchesOnlyPastLoadedRows() {
+ val items = (0..46).toList()
+ assertEquals(5, CatalogPaging.pageCount(47))
+ assertEquals(2, CatalogPaging.pageCount(19))
+ assertEquals(1, CatalogPaging.pageCount(0))
+ assertEquals(9, CatalogPaging.pageCount(72, hasMore = true))
+ assertEquals((0..9).toList(), CatalogPaging.slice(items, 0))
+ assertEquals((40..46).toList(), CatalogPaging.slice(items, 4))
+ assertEquals(emptyList<Int>(), CatalogPaging.slice(items, 9))
+ assertEquals(4, CatalogPaging.clamp(9, 47))
+ assertEquals(8, CatalogPaging.clamp(9, 72, hasMore = true))
+ assertEquals(0, CatalogPaging.clamp(-1, 20))
+ assertEquals(0, CatalogPaging.clamp(4, 0))
+ assertTrue(CatalogPaging.canForward(10, 0, true))
+ assertTrue(CatalogPaging.needsFetch(10, 1))
+ assertTrue(CatalogPaging.canForward(20, 0, false))
+ assertFalse(CatalogPaging.needsFetch(20, 1))
+ assertFalse(CatalogPaging.canForward(8, 0, false))
+ assertFalse(CatalogPaging.needsFetch(60, 5))
+ assertTrue(CatalogPaging.needsFetch(60, 6))
+ assertTrue(CatalogPaging.needsFetch(72, 7))
+ assertFalse(CatalogPaging.needsFetch(80, 7))
+ assertFalse(CatalogPaging.needsFetch(0, 0))
+ assertFalse(CatalogPaging.needsFetch(3, 0))
+ assertTrue(CatalogPaging.needsFetch(0, 1))
+ }
+
@Test fun connectorInputsRetainHostDefaultsAndUnknownAuthorizationDoesNotClaimSignIn() {
val input = WireJson.decodeFromString<MarketInput>("""{"name":"REGION","required":true,"default":"provided-by-host","future":true}""")
val option = InstallOption("local", "npm", "On computer", listOf(input))
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 0507a2a4..4b70e45b 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -16,7 +16,7 @@
"build": "electron-vite build",
"build:demo": "vite build --config vite.demo.config.ts && mv ../../web/public/demo/desktop/index.html ../../web/public/demo/desktop.html",
"typecheck": "tsc --noEmit -p tsconfig.json",
- "test": "node --test --experimental-strip-types src/shared/*.test.ts src/renderer/lib/*.test.ts src/renderer/views/thread/*.test.ts src/renderer/views/routines/*.test.ts src/renderer/views/call/*.test.ts",
+ "test": "node --test --experimental-strip-types src/shared/*.test.ts src/renderer/lib/*.test.ts src/renderer/views/thread/*.test.ts src/renderer/views/routines/*.test.ts src/renderer/views/call/*.test.ts src/renderer/views/marketplace/*.test.ts",
"icons": "swift tools/export-symbols.swift",
"dist:mac:dev": "node tools/account-config.mjs dev && node tools/native-host.mjs dev && node tools/native-screen.mjs dev && electron-vite build && CSC_NAME=\"Pokai Lee (6KFK5J2LB4)\" electron-builder --mac --config tools/dev-builder.cjs",
"dist:mac:main": "node tools/account-config.mjs main && node tools/native-host.mjs main && node tools/native-screen.mjs main && electron-vite build && electron-builder --mac",
diff --git a/apps/desktop/src/renderer/lib/l10n.test.ts b/apps/desktop/src/renderer/lib/l10n.test.ts
index 374973ec..f4ab9bec 100644
--- a/apps/desktop/src/renderer/lib/l10n.test.ts
+++ b/apps/desktop/src/renderer/lib/l10n.test.ts
@@ -65,7 +65,7 @@ test('known chrome becomes Chinese and everything else stays', () => {
assert.equal(translate('Check for updates', 'zh', false), '检查更新')
assert.equal(translate('Computer access is ready.', 'zh', false), '电脑访问已就绪。')
assert.equal(translate('Storage', 'zh', false), '存储')
- assert.equal(translate('Load more agents', 'zh', false), '加载更多智能体')
+ assert.equal(translate('Next page', 'zh', false), '下一页')
assert.equal(
translate('listing skills on GitHub: https://api.github.com/repos/anthropics/skills answered 403 Forbidden', 'zh', false),
'无法列出 GitHub 上的技能:https://api.github.com/repos/anthropics/skills 返回了 403 Forbidden',
diff --git a/apps/desktop/src/renderer/views/marketplace/MarketplacePanel.tsx b/apps/desktop/src/renderer/views/marketplace/MarketplacePanel.tsx
new file mode 100644
index 00000000..93cbf8d0
--- /dev/null
+++ b/apps/desktop/src/renderer/views/marketplace/MarketplacePanel.tsx
@@ -0,0 +1,206 @@
+import type { ReactNode } from 'react'
+import type { Backend } from '@shared/models'
+import { VStack } from '../../components/Stack'
+import { Text } from '../../components/Text'
+import { useTr } from '../../lib/use-language'
+import { AgentTile, NodeNotice } from './AgentSheet'
+import type { ConnectorCatalog } from './connector-catalog'
+import { clampPage, EXTENSION_SECTIONS, pageItems, type ExtensionSection, type MarketConnector, type MarketSkill } from './market-models'
+import { ItemGrid, MarketRow, PageBar, ServiceLogo, SkeletonGrid, SkillGlyph, TileIcon } from './pieces'
+
+/** One tab of Extensions: the line saying where its items come from, the tab, and an error under it. */
+export function MarketPanel({ section, hostName, error, children }: { section: ExtensionSection; hostName: string; error: string | null; children: ReactNode }) {
+ const tr = useTr()
+ const source = EXTENSION_SECTIONS.find((s) => s.id === section)?.source ?? ''
+ return (
+ <div className="market-panel">
+ <Text size="footnote" tone="tertiary">{tr(source).replaceAll('{name}', hostName)}</Text>
+ {children}
+ {error ? <Text size="footnote" tone="danger">{tr(error)}</Text> : null}
+ </div>
+ )
+}
+
+interface Paging {
+ page: number
+ pageSize: number
+ onPage: (page: number) => void
+ onPageSize: (size: number) => void
+}
+
+export function AgentsPanel({ agents, query, needsNode, page, pageSize, onPage, onPageSize, onAddNode, onAgent }: Paging & {
+ agents: Backend[]
+ query: string
+ needsNode: boolean
+ onAddNode: () => void
+ onAgent: (backend: Backend) => void
+}) {
+ const tr = useTr()
+ const rows = pageItems(agents, page, pageSize)
+ return (
+ <>
+ {needsNode ? <NodeNotice onAdd={onAddNode} /> : null}
+ <div className="market-panel-scroll fade-in">
+ {agents.length === 0 ? (
+ <Text tone="secondary">{query ? tr('No agents match “{query}”.').replaceAll('{query}', query) : tr('No agents yet.')}</Text>
+ ) : (
+ <div className="agent-grid">
+ {rows.map((b) => <AgentCard key={b.id} backend={b} onClick={() => onAgent(b)} />)}
+ <PageSpacers count={pagePad(agents.length, rows.length, pageSize)} kind="agent" />
+ </div>
+ )}
+ <PageBar page={page} count={agents.length} pageSize={pageSize} onPage={(next) => onPage(clampPage(next, agents.length, pageSize))} onPageSize={onPageSize} />
+ </div>
+ </>
+ )
+}
+
+export function ConnectorsPanel({ catalog, query, pageSize, onPage, onPageSize, onAddConnector, onInstall }: Omit<Paging, 'page'> & {
+ catalog: ConnectorCatalog<MarketConnector>
+ query: string
+ onAddConnector: () => void
+ onInstall: (connector: MarketConnector) => void
+}) {
+ const tr = useTr()
+ const all = catalog.items.items
+ const rows = pageItems(all, catalog.page, pageSize)
+ return (
+ <>
+ <MarketRow
+ title={tr('Custom connector')}
+ subtitle={tr('Any MCP server: a command or a URL')}
+ added={false}
+ addLabel="New"
+ icon={<TileIcon name="point.3.connected.trianglepath.dotted" />}
+ onAdd={onAddConnector}
+ />
+ <div className="market-panel-scroll fade-in">
+ {catalog.loading ? (
+ <SkeletonGrid />
+ ) : all.length === 0 ? (
+ <Text tone="secondary">{query ? tr('No connectors match “{query}”.').replaceAll('{query}', query) : tr(`Couldn't load connectors.`)}</Text>
+ ) : rows.length === 0 ? (
+ // The page past the loaded rows, while the registry fills it.
+ <SkeletonGrid />
+ ) : (
+ <ItemGrid>
+ {rows.map((c) => (
+ <MarketRow
+ key={c.name}
+ title={c.title}
+ subtitle={c.description ?? c.name}
+ added={c.installed}
+ icon={<ServiceLogo website={c.website} name={c.title} registryName={c.name} />}
+ onAdd={() => onInstall(c)}
+ />
+ ))}
+ <PageSpacers count={pagePad(all.length, rows.length, pageSize)} kind="row" />
+ </ItemGrid>
+ )}
+ {catalog.loading ? null : (
+ <PageBar page={catalog.page} count={all.length} pageSize={pageSize} hasMore={catalog.hasMore} loading={catalog.loadingMore} onPage={onPage} onPageSize={onPageSize} />
+ )}
+ </div>
+ </>
+ )
+}
+
+export function SkillsPanel({ skills, loading, query, installedSkillIds, busySkill, page, pageSize, onPage, onPageSize, onWriteSkill, onInstallSkill, onViewSkill }: Paging & {
+ skills: MarketSkill[]
+ loading: boolean
+ query: string
+ installedSkillIds: string[]
+ busySkill: string | null
+ onWriteSkill: () => void
+ onInstallSkill: (skill: MarketSkill) => void
+ onViewSkill: (skill: MarketSkill) => void
+}) {
+ const tr = useTr()
+ const rows = pageItems(skills, page, pageSize)
+ return (
+ <>
+ <MarketRow
+ title={tr('Your own skill')}
+ subtitle={tr('Write instructions a bot can follow')}
+ added={false}
+ addLabel="New"
+ icon={<TileIcon name="square.and.pencil" />}
+ onAdd={onWriteSkill}
+ />
+ <div className="market-panel-scroll fade-in">
+ {loading ? (
+ <SkeletonGrid />
+ ) : skills.length === 0 ? (
+ query ? <Text tone="secondary">{tr('No skills match “{query}”.').replaceAll('{query}', query)}</Text> : null
+ ) : (
+ <ItemGrid>
+ {rows.map((s) => (
+ <MarketRow
+ key={s.source}
+ title={s.name}
+ subtitle={s.description}
+ added={s.installed || installedSkillIds.includes(s.source.toLowerCase())}
+ busy={busySkill === s.source}
+ icon={<SkillGlyph />}
+ onAdd={() => onInstallSkill(s)}
+ onOpen={() => onViewSkill(s)}
+ />
+ ))}
+ <PageSpacers count={pagePad(skills.length, rows.length, pageSize)} kind="row" />
+ </ItemGrid>
+ )}
+ {loading ? null : (
+ <PageBar page={page} count={skills.length} pageSize={pageSize} onPage={(next) => onPage(clampPage(next, skills.length, pageSize))} onPageSize={onPageSize} />
+ )}
+ </div>
+ </>
+ )
+}
+
+function pagePad(count: number, shown: number, size: number) {
+ return count > size ? Math.max(0, size - shown) : 0
+}
+
+/** Rooms the size of a row, with nothing in them: a short last page keeps a full page's height, so the bar stays put. */
+function PageSpacers({ count, kind }: { count: number; kind: 'agent' | 'row' }) {
+ const cells: ReactNode[] = []
+ for (let i = 0; i < count; i++) {
+ cells.push(kind === 'agent' ? (
+ <div key={i} className="agent-card page-spacer" aria-hidden="true">
+ <AgentCardBody registry={null} name={'\u00a0'} status={'\u00a0'} />
+ </div>
+ ) : (
+ <div key={i} className="page-spacer" aria-hidden="true">
+ <MarketRow title={'\u00a0'} subtitle={'\u00a0'} added icon={null} onAdd={() => {}} />
+ </div>
+ ))
+ }
+ return <>{cells}</>
+}
+
+function AgentCard({ backend, onClick }: { backend: Backend; onClick: () => void }) {
+ const tr = useTr()
+ const status = backend.installed !== true && backend.curated === true ? 'Not installed'
+ : backend.node === 'missing' ? 'Needs Node.js'
+ : backend.installed !== true ? 'Sets up on first use'
+ : backend.signedIn === false ? 'Not signed in'
+ : 'Installed'
+ return (
+ <button className="agent-card" title={backend.name} onClick={onClick}>
+ <AgentCardBody registry={backend.registry ?? backend.id} name={backend.name} status={tr(status)} />
+ </button>
+ )
+}
+
+/** An agent tile's logo, name and status line. */
+function AgentCardBody({ registry, name, status }: { registry: string | null; name: string; status: string }) {
+ return (
+ <>
+ <AgentTile registry={registry} icon={24} tile={40} radius={11} />
+ <VStack as="span" align="flex-start" gap={3} shrink>
+ <Text size="subheadline" weight="semibold" tone="text" truncate className="agent-card-line">{name}</Text>
+ <Text size="caption" tone="secondary" truncate className="agent-card-line">{status}</Text>
+ </VStack>
+ </>
+ )
+}
diff --git a/apps/desktop/src/renderer/views/marketplace/MarketplaceView.tsx b/apps/desktop/src/renderer/views/marketplace/MarketplaceView.tsx
index e9a2ba9f..6f4c20c1 100644
--- a/apps/desktop/src/renderer/views/marketplace/MarketplaceView.tsx
+++ b/apps/desktop/src/renderer/views/marketplace/MarketplaceView.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState, type ReactNode } from 'react'
+import { useEffect, useState } from 'react'
import type { Backend } from '@shared/models'
import { Button, IconButton, Spinner } from '../../components/Controls'
import { Icon } from '../../components/Icon'
@@ -8,26 +8,25 @@ import { Text } from '../../components/Text'
import { useStore } from '../../store/context'
import { useScreenViewed } from '../../store/analytics'
import { ComputerBadge } from '../ComputerBadge'
-import { AgentSheet, AgentTile, NodeNotice } from './AgentSheet'
+import { AgentSheet } from './AgentSheet'
import { CredentialsView } from './CredentialsView'
import { CustomConnectorSheet, InstallConnectorSheet, NewSkillSheet } from './ConnectorSheets'
import { SetupTerminalView } from './SetupTerminal'
import { SkillSheet, type SkillRef } from './SkillSheet'
-import {
- appendPage, emptyPage, errorText, hasHiddenItems, market, needsSignIn, replacePage, revealMore, visible,
- type MarketConnector, type MarketSkill,
-} from './market-models'
-import { AppLogo, FormSheet, ItemGrid, ItemRow, MarketRow, MarketSection, ScreenHeader, ServiceLogo, SkeletonGrid, SkillGlyph, SlideStack, TileIcon } from './pieces'
+import { useModel } from '../../lib/observable'
+import { ConnectorCatalog } from './connector-catalog'
+import { errorText, market, MARKET_PAGE_SIZE, needsSignIn, type ExtensionSection, type MarketConnector, type MarketSkill } from './market-models'
+import { AgentsPanel, ConnectorsPanel, MarketPanel, SkillsPanel } from './MarketplacePanel'
+import { AppLogo, ExtensionRail, FormSheet, ItemGrid, ItemRow, MarketSection, ScreenHeader, ServiceLogo, SkillGlyph, SlideStack } from './pieces'
import { usePlugins } from './plugins'
import { useTr } from '../../lib/use-language'
-const connectorId = (c: MarketConnector) => c.name
-
/**
- * The Marketplace (Grok Bot's layout): one page of agents, connectors and
- * skills for the bots on one computer (the store in context). Installing happens on that
- * computer; each bot turns connectors and skills on in its settings. Each computer has its own,
- * opened from its heading in the sidebar.
+ * Extensions for the bots on one computer (the store in context): Agents, Connectors
+ * and Skills, one at a time. Each list turns a page; a connector page that isn't full fetches
+ * more from the registry (`ConnectorCatalog`). Installing happens on that computer; each bot
+ * turns connectors and skills on in its settings. Each computer has its own, opened
+ * from its heading in the sidebar.
*/
export function MarketplaceView() {
const store = useStore()
@@ -36,12 +35,12 @@ export function MarketplaceView() {
const dismiss = useDismiss()
useScreenViewed('marketplace')
const [search, setSearch] = useState('')
- const [connectors, setConnectors] = useState(emptyPage<MarketConnector>)
- /** The registry page after the ones shown; null at the end. */
- const [connectorCursor, setConnectorCursor] = useState<string | null>(null)
- const [loadingMore, setLoadingMore] = useState(false)
+ const [catalog] = useState(() => new ConnectorCatalog<MarketConnector>(
+ (c) => c.name,
+ async (q, cursor) => market.marketConnectors(await store.ready(), q, cursor),
+ ))
+ const connectors = useModel(catalog)
const [skills, setSkills] = useState<MarketSkill[]>([])
- const [loadingConnectors, setLoadingConnectors] = useState(true)
const [loadingSkills, setLoadingSkills] = useState(true)
const [error, setError] = useState<string | null>(null)
const [installing, setInstalling] = useState<MarketConnector | null>(null)
@@ -51,12 +50,12 @@ export function MarketplaceView() {
const [viewingSkill, setViewingSkill] = useState<SkillRef | null>(null)
const [agent, setAgent] = useState<Backend | null>(null)
const [addingNode, setAddingNode] = useState(false)
- /** Agents shown before "Load more agents" (two rows of the grid). */
- const [agentLimit, setAgentLimit] = useState(10)
+ const [section, setSection] = useState<ExtensionSection>('agents')
+ const [agentPage, setAgentPage] = useState(0)
+ const [skillPage, setSkillPage] = useState(0)
+ const [pageSize, setPageSize] = useState(MARKET_PAGE_SIZE)
const [showInstalled, setShowInstalled] = useState(false)
const [showCredentials, setShowCredentials] = useState(false)
- const request = useRef(0)
- const connectorQuery = useRef('')
const query = search.trim()
const matches = (text: string | null | undefined) => (text ?? '').toLowerCase().includes(query.toLowerCase())
@@ -65,54 +64,24 @@ export function MarketplaceView() {
const shownSkills = query ? skills.filter((s) => matches(s.name) || matches(s.description)) : skills
const installedCount = plugins.installedConnectors.length + plugins.installedSkills.length
- const loadConnectors = async (q = query) => {
- const id = ++request.current
- connectorQuery.current = q
- setLoadingConnectors(true)
- setLoadingMore(false)
- try {
- const page = await market.marketConnectors(await store.ready(), q)
- if (request.current !== id) return
- setConnectors(replacePage(page.items, connectorId))
- setConnectorCursor(page.next)
- setError(null)
- } catch (e) {
- if (request.current !== id) return
- setConnectors(emptyPage())
- setConnectorCursor(null)
- setError(errorText(e))
- } finally {
- if (request.current === id) setLoadingConnectors(false)
- }
+ const changePageSize = (size: number) => {
+ setPageSize(size)
+ setAgentPage(0)
+ setSkillPage(0)
+ connectors.show(0, size)
}
- const loadMoreConnectors = async () => {
- if (loadingMore || loadingConnectors) return
- if (hasHiddenItems(connectors)) {
- setConnectors(revealMore)
- return
- }
- if (!connectorCursor) return
- const id = request.current
- setLoadingMore(true)
- try {
- const page = await market.marketConnectors(await store.ready(), connectorQuery.current, connectorCursor)
- if (request.current !== id) return
- setConnectors((old) => revealMore(appendPage(old, page.items, connectorId)))
- setConnectorCursor(page.next)
- setError(null)
- } catch (e) {
- if (request.current === id) setError(errorText(e))
- } finally {
- if (request.current === id) setLoadingMore(false)
- }
+ /** Turns the connector list to `page` at once; a page that isn't full then fills from the registry. */
+ const showConnectorPage = (page: number) => {
+ connectors.show(page, pageSize)
+ void connectors.fill(pageSize)
}
useEffect(() => {
void plugins.refresh()
// Picks up CLIs installed or signed in outside Codync.
void store.refreshBackends()
- void loadConnectors('')
+ void connectors.load('')
void (async () => {
try {
setSkills(await market.marketSkills(await store.ready()))
@@ -121,12 +90,12 @@ export function MarketplaceView() {
}
setLoadingSkills(false)
})()
- return () => void request.current++
+ return () => connectors.cancel()
// Mount only, like the view's `.task`s.
}, [])
const submit = (q: string) => {
- void loadConnectors(q)
+ void connectors.load(q)
}
const installSkill = async (s: MarketSkill) => {
@@ -180,7 +149,8 @@ export function MarketplaceView() {
spellCheck={false}
onChange={(e) => {
setSearch(e.target.value)
- setAgentLimit(10)
+ setAgentPage(0)
+ setSkillPage(0)
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.nativeEvent.isComposing) submit(search.trim())
@@ -193,7 +163,8 @@ export function MarketplaceView() {
className="market-search-clear"
onClick={() => {
setSearch('')
- setAgentLimit(10)
+ setAgentPage(0)
+ setSkillPage(0)
submit('')
}}
>
@@ -203,96 +174,53 @@ export function MarketplaceView() {
</div>
)
- const centered = (node: ReactNode) => <HStack align="stretch" justify="center">{node}</HStack>
-
const page = (
<div className="market-page">
- <div className="market-scroll">
- <div className="market-page-content">
- {header}
- {searchField}
- {agents.length > 0 ? (
- <MarketSection title={query ? tr('Agents matching “{query}”').replaceAll('{query}', query) : 'Agents'}>
- {allAgents.some((b) => b.node === 'missing') ? <NodeNotice onAdd={() => setAddingNode(true)} /> : null}
- <div className="agent-grid">
- {agents.slice(0, agentLimit).map((b) => <AgentCard key={b.id} backend={b} onClick={() => setAgent(b)} />)}
- </div>
- {agents.length > agentLimit ? centered(<Button kind="secondary" onClick={() => setAgentLimit((n) => n + 10)}>Load more agents</Button>) : null}
- </MarketSection>
- ) : null}
- <MarketSection title="Connectors">
- {loadingConnectors ? (
- <SkeletonGrid />
- ) : connectors.items.length === 0 ? (
- <Text tone="secondary">{query ? tr('No connectors match “{query}”.').replaceAll('{query}', query) : tr(`Couldn't load connectors.`)}</Text>
- ) : (
- <>
- <ItemGrid>
- {visible(connectors).map((c) => (
- <MarketRow
- key={c.name}
- title={c.title}
- subtitle={c.description ?? c.name}
- added={c.installed}
- icon={<ServiceLogo website={c.website} name={c.title} registryName={c.name} />}
- onAdd={() => setInstalling(c)}
- />
- ))}
- </ItemGrid>
- {hasHiddenItems(connectors) || connectorCursor
- ? centered(
- <Button kind="secondary" disabled={loadingMore} onClick={() => void loadMoreConnectors()}>
- {loadingMore ? 'Loading…' : 'Load more connectors'}
- </Button>,
- )
- : null}
- </>
- )}
- </MarketSection>
- <MarketSection title="Skills">
- {loadingSkills ? (
- <SkeletonGrid />
- ) : (
- <ItemGrid>
- {shownSkills.map((s) => (
- <MarketRow
- key={s.source}
- title={s.name}
- subtitle={s.description}
- added={s.installed || plugins.installedSkills.some((i) => i.id === s.source.toLowerCase())}
- busy={busySkill === s.source}
- icon={<SkillGlyph />}
- onAdd={() => void installSkill(s)}
- onOpen={() => setViewingSkill(s)}
- />
- ))}
- </ItemGrid>
- )}
- </MarketSection>
- <MarketSection title="Make your own">
- <ItemGrid>
- <MarketRow
- title="Custom connector"
- subtitle="Any MCP server: a command or a URL"
- added={false}
- addLabel="New"
- icon={<TileIcon name="point.3.connected.trianglepath.dotted" />}
- onAdd={() => setAddingConnector(true)}
+ <div className="market-frame">
+ {header}
+ {searchField}
+ <div className="market-split">
+ <ExtensionRail selection={section} onChange={setSection} />
+ <MarketPanel section={section} hostName={store.hostName} error={error ?? connectors.error}>
+ {section === 'agents' ? (
+ <AgentsPanel
+ agents={agents}
+ query={query}
+ needsNode={allAgents.some((b) => b.node === 'missing')}
+ page={agentPage}
+ pageSize={pageSize}
+ onPage={setAgentPage}
+ onPageSize={changePageSize}
+ onAddNode={() => setAddingNode(true)}
+ onAgent={setAgent}
+ />
+ ) : section === 'connectors' ? (
+ <ConnectorsPanel
+ catalog={connectors}
+ query={query}
+ pageSize={pageSize}
+ onPage={showConnectorPage}
+ onPageSize={changePageSize}
+ onAddConnector={() => setAddingConnector(true)}
+ onInstall={setInstalling}
/>
- <MarketRow
- title="Your own skill"
- subtitle="Write instructions a bot can follow"
- added={false}
- addLabel="New"
- icon={<TileIcon name="square.and.pencil" />}
- onAdd={() => setWritingSkill(true)}
+ ) : (
+ <SkillsPanel
+ skills={shownSkills}
+ loading={loadingSkills}
+ query={query}
+ installedSkillIds={plugins.installedSkills.map((s) => s.id)}
+ busySkill={busySkill}
+ page={skillPage}
+ pageSize={pageSize}
+ onPage={setSkillPage}
+ onPageSize={changePageSize}
+ onWriteSkill={() => setWritingSkill(true)}
+ onInstallSkill={(s) => void installSkill(s)}
+ onViewSkill={setViewingSkill}
/>
- </ItemGrid>
- </MarketSection>
- {error ? <Text size="footnote" tone="danger">{error}</Text> : null}
- <Text size="footnote" tone="tertiary">
- {tr('Connectors come from the official MCP Registry, skills from Anthropic, agents from the ACP registry. Everything installs on {name}.').replaceAll('{name}', store.hostName)}
- </Text>
+ )}
+ </MarketPanel>
</div>
</div>
{/* Dismissing slides the sheet away; clearing the caller's state would cut it off. */}
@@ -306,7 +234,7 @@ export function MarketplaceView() {
<>
<SlideStack base={page} top={showCredentials ? <CredentialsView onBack={() => setShowCredentials(false)} /> : showInstalled ? <InstalledView back={() => setShowInstalled(false)} /> : null} />
<FormSheet open={installing !== null} onClose={() => setInstalling(null)}>
- {installing ? <InstallConnectorSheet key={installing.name} item={installing} done={() => void loadConnectors(connectorQuery.current)} /> : null}
+ {installing ? <InstallConnectorSheet key={installing.name} item={installing} done={() => void connectors.reload()} /> : null}
</FormSheet>
<FormSheet open={addingConnector} onClose={() => setAddingConnector(false)}>
<CustomConnectorSheet />
@@ -327,23 +255,6 @@ export function MarketplaceView() {
)
}
-function AgentCard({ backend, onClick }: { backend: Backend; onClick: () => void }) {
- const status = backend.installed !== true && backend.curated === true ? 'Not installed'
- : backend.node === 'missing' ? 'Needs Node.js'
- : backend.installed !== true ? 'Sets up on first use'
- : backend.signedIn === false ? 'Not signed in'
- : 'Installed'
- return (
- <button className="agent-card" title={backend.name} onClick={onClick}>
- <AgentTile registry={backend.registry ?? backend.id} icon={24} tile={40} radius={11} />
- <VStack as="span" align="flex-start" gap={3} shrink>
- <Text size="subheadline" weight="semibold" tone="text" truncate className="agent-card-line">{backend.name}</Text>
- <Text size="caption" tone="secondary" truncate className="agent-card-line">{status}</Text>
- </VStack>
- </button>
- )
-}
-
// MARK: - Installed
function InstalledView({ back }: { back: () => void }) {
diff --git a/apps/desktop/src/renderer/views/marketplace/connector-catalog.test.ts b/apps/desktop/src/renderer/views/marketplace/connector-catalog.test.ts
new file mode 100644
index 00000000..c430e368
--- /dev/null
+++ b/apps/desktop/src/renderer/views/marketplace/connector-catalog.test.ts
@@ -0,0 +1,44 @@
+import assert from 'node:assert/strict'
+import { existsSync } from 'node:fs'
+import { registerHooks } from 'node:module'
+import { test } from 'node:test'
+
+registerHooks({ resolve(specifier, context, nextResolve) {
+ if (specifier.startsWith('.') && context.parentURL && !/\.[a-z]+$/.test(specifier)) {
+ const url = new URL(`${specifier}.ts`, context.parentURL)
+ if (existsSync(url)) return nextResolve(url.href, context)
+ }
+ return nextResolve(specifier, context)
+} })
+
+const rows = (from: number, to: number) => Array.from({ length: to - from }, (_, i) => from + i)
+
+test('a connector page fills until it is full, and falls back when the registry fails', async () => {
+ const { ConnectorCatalog } = await import('./connector-catalog.ts')
+ const asked: (string | null)[] = []
+ let answer = async (cursor: string | null) => {
+ asked.push(cursor)
+ if (cursor === null) return { items: rows(0, 15), next: 'a' }
+ return cursor === 'a' ? { items: rows(15, 18), next: 'b' } : { items: rows(18, 25), next: 'c' }
+ }
+ const catalog = new ConnectorCatalog<number>(String, (_search, cursor) => answer(cursor))
+ await catalog.load('')
+ assert.equal(catalog.items.items.length, 15)
+
+ // Page 2 needs rows 10-19: two registry pages fill it.
+ catalog.show(1, 10)
+ await catalog.fill(10)
+ assert.deepEqual(asked, [null, 'a', 'b'])
+ assert.equal(catalog.page, 1)
+ assert.equal(catalog.items.items.length, 25)
+ assert.equal(catalog.cursor, 'c')
+
+ // The page past the loaded rows fails: back to the last page with rows.
+ answer = async () => { throw new Error('offline') }
+ catalog.show(3, 10)
+ assert.equal(catalog.page, 3)
+ await catalog.fill(10)
+ assert.equal(catalog.page, 2)
+ assert.equal(catalog.error, 'offline')
+ assert.equal(catalog.loadingMore, false)
+})
diff --git a/apps/desktop/src/renderer/views/marketplace/connector-catalog.ts b/apps/desktop/src/renderer/views/marketplace/connector-catalog.ts
new file mode 100644
index 00000000..3e9dd298
--- /dev/null
+++ b/apps/desktop/src/renderer/views/marketplace/connector-catalog.ts
@@ -0,0 +1,109 @@
+import { Observable } from '../../lib/observable'
+import { appendPage, clampPage, emptyPage, errorText, needsFetch, replacePage, type MarketplacePage } from './market-models'
+
+type Fetch<T> = (search: string, cursor: string | null) => Promise<{ items: T[]; next: string | null }>
+
+/**
+ * The connector list Extensions pages through (kit `ConnectorCatalog`): the rows loaded so far, the
+ * registry cursor and the page on screen. A page that isn't full asks the registry until it is, or
+ * until the cursor ends.
+ */
+export class ConnectorCatalog<T> extends Observable {
+ items: MarketplacePage<T> = emptyPage()
+ /** The registry page after the ones loaded; null at the end. */
+ cursor: string | null = null
+ /** The page on screen. While the registry fills it, it can be the page past the loaded rows. */
+ page = 0
+ loading = true
+ loadingMore = false
+ error: string | null = null
+ #request = 0
+ #query = ''
+ readonly #id: (item: T) => string
+ readonly #fetch: Fetch<T>
+
+ constructor(id: (item: T) => string, fetch: Fetch<T>) {
+ super()
+ this.#id = id
+ this.#fetch = fetch
+ }
+
+ get hasMore() {
+ return this.cursor !== null
+ }
+
+ /** The first registry page for `search`; answers to an older search are dropped. */
+ async load(search: string) {
+ const request = ++this.#request
+ this.#query = search
+ this.loading = true
+ this.loadingMore = false
+ this.changed()
+ try {
+ const first = await this.#fetch(search, null)
+ if (request !== this.#request) return
+ this.items = replacePage(first.items, this.#id)
+ this.cursor = first.next
+ this.page = 0
+ this.error = null
+ } catch (e) {
+ if (request !== this.#request) return
+ this.items = emptyPage()
+ this.cursor = null
+ this.error = errorText(e)
+ } finally {
+ if (request === this.#request) {
+ this.loading = false
+ this.changed()
+ }
+ }
+ }
+
+ /** The last search again, after an install changed what it lists. */
+ reload() {
+ return this.load(this.#query)
+ }
+
+ /** Turns to `next` at once; `fill` then loads its rows. */
+ show(next: number, size: number) {
+ if (this.loading) return
+ this.page = clampPage(next, this.items.items.length, size, this.hasMore)
+ this.changed()
+ }
+
+ /**
+ * Asks the registry until the page on screen is full or the cursor ends. A page turned meanwhile
+ * is filled by the same loop. If a page fails, the list goes back to the last page with rows.
+ */
+ async fill(size: number) {
+ if (this.loading || this.loadingMore || !this.hasMore || !needsFetch(this.items.items.length, this.page, size)) return
+ const request = this.#request
+ this.loadingMore = true
+ this.changed()
+ try {
+ while (this.cursor && needsFetch(this.items.items.length, this.page, size)) {
+ const more = await this.#fetch(this.#query, this.cursor)
+ if (request !== this.#request) return
+ this.items = appendPage(this.items, more.items, this.#id)
+ this.cursor = more.next
+ this.changed()
+ }
+ this.page = clampPage(this.page, this.items.items.length, size, this.hasMore)
+ this.error = null
+ } catch (e) {
+ if (request !== this.#request) return
+ this.error = errorText(e)
+ this.page = clampPage(this.page, this.items.items.length, size)
+ } finally {
+ if (request === this.#request) {
+ this.loadingMore = false
+ this.changed()
+ }
+ }
+ }
+
+ /** Drops the answers still on their way (the view went away). */
+ cancel() {
+ this.#request++
+ }
+}
diff --git a/apps/desktop/src/renderer/views/marketplace/extensions-layout.css b/apps/desktop/src/renderer/views/marketplace/extensions-layout.css
new file mode 100644
index 00000000..96a36acd
--- /dev/null
+++ b/apps/desktop/src/renderer/views/marketplace/extensions-layout.css
@@ -0,0 +1,102 @@
+/* The Extensions sheet's layout: the section rail, one paged section, and the pager under its list. */
+/* Header and search stay put, one section fills the rest. */
+.market-frame {
+ height: 100%;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 20px;
+ padding: 30px 36px 20px;
+ max-width: 980px;
+ margin: 0 auto;
+}
+.market-split {
+ flex: 1;
+ min-height: 0;
+ display: flex;
+ gap: 20px;
+}
+.market-rail {
+ width: 176px;
+ flex: none;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+}
+.market-rail-item {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ width: 100%;
+ text-align: left;
+ padding: 8px 12px;
+ border-radius: var(--radius-m);
+ color: var(--secondary);
+ transition: background-color var(--hover), color var(--hover), transform var(--press);
+}
+.market-rail-item:hover {
+ color: var(--text);
+}
+.market-rail-item:active {
+ transform: scale(0.98);
+}
+.market-rail-item.on {
+ background: var(--bubble-agent);
+ color: var(--text);
+ font-weight: 600;
+}
+.market-panel {
+ flex: 1;
+ min-width: 0;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+.market-panel-scroll {
+ flex: 1;
+ min-height: 0;
+ overflow-y: auto;
+}
+.market-pager {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 8px 14px;
+ margin-top: 8px;
+ color: var(--secondary);
+ font-size: var(--text-footnote);
+}
+.market-pager-size {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+}
+.market-pager-size-button {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ height: 28px;
+ padding: 0 10px;
+ border: 0;
+ border-radius: 8px;
+ background: var(--bubble-agent);
+ color: var(--text);
+ font: inherit;
+}
+.market-pager-fraction {
+ min-width: 3.2em;
+ color: var(--text);
+ font-variant-numeric: tabular-nums;
+ text-align: center;
+}
+/* Fills a short last page to a full page's height, so the pager stays put. */
+.page-spacer {
+ visibility: hidden;
+}
+@media (max-width: 640px) {
+ .market-frame { padding: 28px 18px 16px; }
+ .market-split { flex-direction: column; gap: 12px; }
+ .market-rail { width: auto; flex-direction: row; flex-wrap: wrap; }
+ .market-rail-item { width: auto; }
+}
diff --git a/apps/desktop/src/renderer/views/marketplace/market-models.test.ts b/apps/desktop/src/renderer/views/marketplace/market-models.test.ts
new file mode 100644
index 00000000..9b5b11c7
--- /dev/null
+++ b/apps/desktop/src/renderer/views/marketplace/market-models.test.ts
@@ -0,0 +1,41 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { appendPage, canPageForward, clampPage, emptyPage, needsFetch, pageCount, pageItems, replacePage } from './market-models.ts'
+
+test('catalog pages keep every fetched row and drop duplicates', () => {
+ const first = replacePage([0, 1, 2], (n) => String(n))
+ const next = appendPage(first, [2, 3, 3], (n) => String(n))
+ assert.deepEqual(next.items, [0, 1, 2, 3])
+ assert.deepEqual(replacePage([], (n: number) => String(n)).items, emptyPage().items)
+})
+
+test('a catalog of 47 is five pages of 10, and the bar is never a single page while more rows exist', () => {
+ const items = Array.from({ length: 47 }, (_, i) => i)
+ assert.equal(pageCount(47), 5)
+ assert.equal(pageCount(19), 2)
+ assert.equal(pageCount(0), 1)
+ assert.equal(pageCount(72, 10, true), 9)
+ assert.deepEqual(pageItems(items, 0), items.slice(0, 10))
+ assert.deepEqual(pageItems(items, 4), items.slice(40, 47))
+ assert.deepEqual(pageItems(items, 9), [])
+ assert.equal(clampPage(9, 47), 4)
+ assert.equal(clampPage(9, 72, 10, true), 8)
+ assert.equal(clampPage(-1, 20), 0)
+ assert.equal(clampPage(4, 0), 0)
+})
+
+test('next stays available while the registry has another page', () => {
+ assert.equal(canPageForward(10, 0, true), true)
+ assert.equal(needsFetch(10, 1), true)
+ assert.equal(canPageForward(20, 0, false), true)
+ assert.equal(needsFetch(20, 1), false)
+ assert.equal(canPageForward(8, 0, false), false)
+ assert.equal(canPageForward(60, 5, true), true)
+ assert.equal(needsFetch(60, 5), false)
+ assert.equal(needsFetch(60, 6), true)
+ assert.equal(needsFetch(72, 7), true)
+ assert.equal(needsFetch(80, 7), false)
+ assert.equal(needsFetch(0, 0), false)
+ assert.equal(needsFetch(3, 0), false)
+ assert.equal(needsFetch(0, 1), true)
+})
diff --git a/apps/desktop/src/renderer/views/marketplace/market-models.ts b/apps/desktop/src/renderer/views/marketplace/market-models.ts
index 77a32032..03717ac0 100644
--- a/apps/desktop/src/renderer/views/marketplace/market-models.ts
+++ b/apps/desktop/src/renderer/views/marketplace/market-models.ts
@@ -236,13 +236,12 @@ export const market = {
termClose: (c: HostClient, term: string) => c.call('termClose', { term }),
}
-/** Keep fetched catalog metadata in memory, but create rows only as the user requests them. */
+/** Keep fetched catalog metadata in memory. The Extensions tabs page through it. */
export interface MarketplacePage<T> {
items: T[]
- visibleCount: number
}
-export const emptyPage = <T>(): MarketplacePage<T> => ({ items: [], visibleCount: 12 })
+export const emptyPage = <T>(): MarketplacePage<T> => ({ items: [] })
export function appendPage<T>(page: MarketplacePage<T>, more: T[], id: (t: T) => string): MarketplacePage<T> {
const known = new Set(page.items.map(id))
@@ -250,9 +249,46 @@ export function appendPage<T>(page: MarketplacePage<T>, more: T[], id: (t: T) =>
}
export const replacePage = <T>(items: T[], id: (t: T) => string) => appendPage(emptyPage<T>(), items, id)
-export const revealMore = <T>(page: MarketplacePage<T>): MarketplacePage<T> => ({ ...page, visibleCount: Math.min(page.items.length, page.visibleCount + 12) })
-export const visible = <T>(page: MarketplacePage<T>) => page.items.slice(0, page.visibleCount)
-export const hasHiddenItems = <T>(page: MarketplacePage<T>) => page.items.length > page.visibleCount
+
+/** How many catalog rows one Extensions page shows, and the sizes the pager offers. */
+export const MARKET_PAGE_SIZE = 10
+export const PAGE_SIZES = [6, 10, 20, 50] as const
+
+export type ExtensionSection = 'agents' | 'connectors' | 'skills'
+
+/** Each section with its icon and the line saying where its items come from. */
+export const EXTENSION_SECTIONS: { id: ExtensionSection; label: string; icon: string; source: string }[] = [
+ { id: 'agents', label: 'Agents', icon: 'terminal', source: 'Agents come from the ACP registry and install on {name}.' },
+ { id: 'connectors', label: 'Connectors', icon: 'point.3.connected.trianglepath.dotted', source: 'Connectors come from the official MCP Registry and install on {name}.' },
+ { id: 'skills', label: 'Skills', icon: 'book.pages', source: 'Skills come from Anthropic and install on {name}.' },
+]
+
+/** Loaded rows split into pages. While the registry still has a cursor, one more page is offered so the bar is never 1 / 1 for a list that continues. */
+export function pageCount(count: number, size = MARKET_PAGE_SIZE, hasMore = false): number {
+ const loaded = count <= 0 ? 1 : Math.ceil(count / size)
+ return hasMore ? loaded + 1 : loaded
+}
+
+/** The page index that still lands on a page, or 0 when the list is empty. */
+export function clampPage(page: number, count: number, size = MARKET_PAGE_SIZE, hasMore = false): number {
+ return Math.min(Math.max(0, page), pageCount(count, size, hasMore) - 1)
+}
+
+export function pageItems<T>(items: readonly T[], page: number, size = MARKET_PAGE_SIZE): T[] {
+ const start = Math.max(0, page) * size
+ return items.slice(start, start + size)
+}
+
+/** Next stays available through the last shown page, including the page that still has to be fetched. */
+export function canPageForward(count: number, page: number, hasMore: boolean, size = MARKET_PAGE_SIZE): boolean {
+ return page < pageCount(count, size, hasMore) - 1
+}
+
+/** A later page that isn't full yet, so the registry has to be asked. The first page is whatever the first answer held. */
+export function needsFetch(count: number, page: number, size = MARKET_PAGE_SIZE): boolean {
+ const start = Math.max(0, page) * size
+ return start > 0 && start + size > count
+}
export const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e))
export const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
diff --git a/apps/desktop/src/renderer/views/marketplace/pieces.tsx b/apps/desktop/src/renderer/views/marketplace/pieces.tsx
index 712835ee..f77f28a5 100644
--- a/apps/desktop/src/renderer/views/marketplace/pieces.tsx
+++ b/apps/desktop/src/renderer/views/marketplace/pieces.tsx
@@ -1,12 +1,14 @@
import { useEffect, useRef, useState, type CSSProperties, type ReactNode } from 'react'
-import { IconButton } from '../../components/Controls'
+import { DropdownMenu, IconButton } from '../../components/Controls'
import { Sheet, usePresence } from '../../components/Overlay'
import { Icon } from '../../components/Icon'
import { HStack, Spacer, VStack } from '../../components/Stack'
import { Text } from '../../components/Text'
import { useTr } from '../../lib/use-language'
+import { EXTENSION_SECTIONS, PAGE_SIZES, canPageForward, clampPage, pageCount, type ExtensionSection } from './market-models'
import { ThinkingOrb } from '../../components/ThinkingOrb'
import './marketplace.css'
+import './extensions-layout.css'
// Building blocks the Marketplace's screens share (kit MarketplaceView.swift "Pieces").
@@ -100,18 +102,22 @@ export function ItemRow({ title, subtitle, icon, trailing, onOpen }: {
/** Placeholder rows while a list loads, shaped like the real ones. */
export function SkeletonGrid() {
+ const tr = useTr()
return (
- <div className="item-grid skeleton">
- {[0, 1, 2, 3].map((i) => (
- <HStack key={i} gap={14} className="skeleton-row">
- <div className="skeleton-icon" />
- <VStack gap={8}>
- <div className="skeleton-title" />
- <div className="skeleton-subtitle" />
- </VStack>
- </HStack>
- ))}
- </div>
+ <VStack gap={8} aria-busy="true" aria-label={tr('Loading…')}>
+ <Text size="footnote" tone="secondary">{tr('Loading…')}</Text>
+ <div className="item-grid skeleton">
+ {[0, 1, 2, 3].map((i) => (
+ <HStack key={i} gap={14} className="skeleton-row">
+ <div className="skeleton-icon" />
+ <VStack gap={8}>
+ <div className="skeleton-title" />
+ <div className="skeleton-subtitle" />
+ </VStack>
+ </HStack>
+ ))}
+ </div>
+ </VStack>
)
}
@@ -290,6 +296,60 @@ export function useWindowHeight() {
return height
}
+/** Agents, Connectors, Skills: the chosen row is filled, like a side tab. */
+export function ExtensionRail({ selection, onChange }: { selection: ExtensionSection; onChange: (id: ExtensionSection) => void }) {
+ const tr = useTr()
+ return (
+ <nav className="market-rail" role="tablist" aria-label={tr('Extensions sections')}>
+ {EXTENSION_SECTIONS.map((section) => {
+ const on = section.id === selection
+ return (
+ <button key={section.id} type="button" role="tab" aria-selected={on} className={`market-rail-item${on ? ' on' : ''}`} onClick={() => onChange(section.id)}>
+ <Icon name={section.icon} size={15} />
+ <span>{tr(section.label)}</span>
+ </button>
+ )
+ })}
+ </nav>
+ )
+}
+
+/** Count, page size, previous, current / total, and next. */
+export function PageBar({ page, count, pageSize, hasMore = false, loading = false, onPage, onPageSize }: {
+ page: number
+ count: number
+ pageSize: number
+ hasMore?: boolean
+ loading?: boolean
+ onPage: (page: number) => void
+ onPageSize: (size: number) => void
+}) {
+ const tr = useTr()
+ const pages = pageCount(count, pageSize, hasMore)
+ const current = clampPage(page, count, pageSize, hasMore)
+ const canPrev = current > 0 && !loading
+ const canNext = canPageForward(count, current, hasMore, pageSize) && !loading
+ return (
+ <div className="market-pager">
+ <span>{tr('{count} total').replaceAll('{count}', String(count))}</span>
+ <span className="market-pager-size">
+ <span>{tr('Per page')}</span>
+ <DropdownMenu
+ className="market-pager-size-button"
+ title={tr(`${pageSize} / page`)}
+ items={() => PAGE_SIZES.map((size) => ({ title: `${size} / page`, selected: size === pageSize, action: () => onPageSize(size) }))}
+ >
+ <span>{tr(`${pageSize} / page`)}</span>
+ <Icon name="chevron.down" size={10} weight="semibold" />
+ </DropdownMenu>
+ </span>
+ <IconButton title="Previous page" icon="chevron.left" disabled={!canPrev} onClick={() => onPage(current - 1)} />
+ <span className="market-pager-fraction" aria-current="page">{current + 1} / {pages}</span>
+ <IconButton title={loading ? 'Loading…' : 'Next page'} icon="chevron.right" disabled={!canNext} onClick={() => onPage(current + 1)} />
+ </div>
+ )
+}
+
/**
* A Marketplace form in its own modal card (`.codyncSheet`), as tall as its content up to
* `height`; `fixed` keeps it at `height` for content that fills the card (a terminal).
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
index b9e4947c..dc3361d8 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
@@ -594,7 +594,6 @@
"Remove saved keys": "Gespeicherte Schlüssel entfernen",
"Added": "Hinzugefügt",
"No instructions.": "Keine Anleitung.",
- "Load more agents": "Weitere Agenten laden",
"Credentials": "Zugangsdaten",
"Connectors & skills": "Konnektoren und Skills",
"Search agents, connectors and skills": "Agenten, Konnektoren und Skills suchen",
@@ -606,20 +605,31 @@
"Not installed": "Nicht installiert",
"Needs Node.js": "Benötigt Node.js",
"Sets up on first use": "Einrichtung bei erster Verwendung",
- "Agents matching “{query}”": "Agenten passend zu „{query}“",
"Couldn't load connectors.": "Konnektoren konnten nicht geladen werden.",
"No connectors match “{query}”.": "Keine Konnektoren passen zu „{query}“.",
"Couldn't load apps.": "Apps konnten nicht geladen werden.",
"No apps match “{query}”.": "Keine Apps passen zu „{query}“.",
- "Load more connectors": "Weitere Konnektoren laden",
- "Make your own": "Selbst erstellen",
+ "Previous page": "Vorherige Seite",
+ "Next page": "Nächste Seite",
+ "{count} total": "{count} insgesamt",
+ "Per page": "Pro Seite",
+ "6 / page": "6 / Seite",
+ "10 / page": "10 / Seite",
+ "20 / page": "20 / Seite",
+ "50 / page": "50 / Seite",
+ "Extensions sections": "Erweiterungsbereiche",
+ "No agents match “{query}”.": "Keine Agenten passen zu „{query}“.",
+ "No skills match “{query}”.": "Keine Skills passen zu „{query}“.",
+ "No agents yet.": "Noch keine Agenten.",
"Custom connector": "Eigener Konnektor",
"Any MCP server: a command or a URL": "Beliebiger MCP-Server: Befehl oder URL",
"Your own skill": "Dein eigener Skill",
"Write instructions a bot can follow": "Schreibe Anweisungen, denen ein Bot folgen kann",
"{count} installed": "{count} installiert",
"Connectors come from the official MCP Registry, apps through Composio, skills from Anthropic, agents from the ACP registry. Everything installs on {name}.": "Konnektoren stammen aus der offiziellen MCP Registry, Apps von Composio, Skills von Anthropic und Agenten aus der ACP-Registry. Alles wird auf {name} installiert.",
- "Connectors come from the official MCP Registry, skills from Anthropic, agents from the ACP registry. Everything installs on {name}.": "Konnektoren stammen aus der offiziellen MCP Registry, Skills von Anthropic und Agenten aus der ACP-Registry. Alles wird auf {name} installiert.",
+ "Agents come from the ACP registry and install on {name}.": "Agenten stammen aus der ACP-Registry und werden auf {name} installiert.",
+ "Connectors come from the official MCP Registry and install on {name}.": "Konnektoren stammen aus der offiziellen MCP Registry und werden auf {name} installiert.",
+ "Skills come from Anthropic and install on {name}.": "Skills stammen von Anthropic und werden auf {name} installiert.",
"Node.js isn't on {name}": "Node.js ist nicht auf {name}",
"Couldn't load more connectors.": "Weitere Konnektoren konnten nicht geladen werden.",
"Couldn't load skills.": "Skills konnten nicht geladen werden.",
@@ -636,9 +646,9 @@
"Some agents need it to run. Codync adds a copy just for them.": "Einige Agenten benötigen es. Codync installiert eine eigene Kopie für sie.",
"Paste any MCP server's config": "Konfiguration eines beliebigen MCP-Servers einfügen",
"Loading the registry…": "Registry wird geladen…",
- "tab switch · ↵ install / sign in · ^r refresh · esc close": "tab wechseln · ↵ installieren / anmelden · ^r aktualisieren · esc schließen",
- "tab switch · ↵ add / sign in · ^x remove · ^r refresh · esc": "tab wechseln · ↵ hinzufügen / anmelden · ^x entfernen · ^r aktualisieren · esc",
- "tab switch · ↵ details · ^x remove · esc close": "tab wechseln · ↵ Details · ^x entfernen · esc schließen",
+ "pgup/pgdn · alt-s · tab · ↵ install / sign in · ^r · esc": "PgUp/PgDn Seite · Alt-S Größe · Tab wechseln · ↵ installieren / anmelden · ^R · Esc",
+ "pgup/pgdn · alt-s · tab · ↵ add / sign in · ^x remove · esc": "PgUp/PgDn Seite · Alt-S Größe · Tab wechseln · ↵ hinzufügen / anmelden · ^X entfernen · Esc",
+ "pgup/pgdn · alt-s · tab · ↵ details · ^x remove · esc": "PgUp/PgDn Seite · Alt-S Größe · Tab wechseln · ↵ Details · ^X entfernen · Esc",
"Sign in": "Anmelden",
"No matching time zones": "Keine passenden Zeitzonen",
"e.g. Morning summary": "z. B. Morgenzusammenfassung",
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
index bc984822..699ed4d7 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
@@ -594,7 +594,6 @@
"Remove saved keys": "Eliminar claves guardadas",
"Added": "Añadido",
"No instructions.": "Sin instrucciones.",
- "Load more agents": "Cargar más agentes",
"Credentials": "Credenciales",
"Connectors & skills": "Conectores y habilidades",
"Search agents, connectors and skills": "Buscar agentes, conectores y habilidades",
@@ -606,20 +605,31 @@
"Not installed": "No instalado",
"Needs Node.js": "Necesita Node.js",
"Sets up on first use": "Se configura en el primer uso",
- "Agents matching “{query}”": "Agentes que coinciden con «{query}»",
"Couldn't load connectors.": "No se pudieron cargar los conectores.",
"No connectors match “{query}”.": "Ningún conector coincide con «{query}».",
"Couldn't load apps.": "No se pudieron cargar las apps.",
"No apps match “{query}”.": "Ninguna app coincide con «{query}».",
- "Load more connectors": "Cargar más conectores",
- "Make your own": "Crea el tuyo",
+ "Previous page": "Página anterior",
+ "Next page": "Página siguiente",
+ "{count} total": "{count} en total",
+ "Per page": "Por página",
+ "6 / page": "6 / página",
+ "10 / page": "10 / página",
+ "20 / page": "20 / página",
+ "50 / page": "50 / página",
+ "Extensions sections": "Secciones de extensiones",
+ "No agents match “{query}”.": "Ningún agente coincide con «{query}».",
+ "No skills match “{query}”.": "Ninguna habilidad coincide con «{query}».",
+ "No agents yet.": "Aún no hay agentes.",
"Custom connector": "Conector personalizado",
"Any MCP server: a command or a URL": "Cualquier servidor MCP: un comando o una URL",
"Your own skill": "Tu propia habilidad",
"Write instructions a bot can follow": "Escribe instrucciones que un bot pueda seguir",
"{count} installed": "{count} instalados",
"Connectors come from the official MCP Registry, apps through Composio, skills from Anthropic, agents from the ACP registry. Everything installs on {name}.": "Los conectores provienen del MCP Registry oficial, las apps de Composio, las habilidades de Anthropic y los agentes del registro ACP. Todo se instala en {name}.",
- "Connectors come from the official MCP Registry, skills from Anthropic, agents from the ACP registry. Everything installs on {name}.": "Los conectores provienen del MCP Registry oficial, las habilidades de Anthropic y los agentes del registro ACP. Todo se instala en {name}.",
+ "Agents come from the ACP registry and install on {name}.": "Los agentes provienen del registro ACP y se instalan en {name}.",
+ "Connectors come from the official MCP Registry and install on {name}.": "Los conectores provienen del MCP Registry oficial y se instalan en {name}.",
+ "Skills come from Anthropic and install on {name}.": "Las habilidades provienen de Anthropic y se instalan en {name}.",
"Node.js isn't on {name}": "Node.js no está en {name}",
"Couldn't load more connectors.": "No se pudieron cargar más conectores.",
"Couldn't load skills.": "No se pudieron cargar las habilidades.",
@@ -636,9 +646,9 @@
"Some agents need it to run. Codync adds a copy just for them.": "Algunos agentes lo necesitan para funcionar. Codync instala una copia dedicada para ellos.",
"Paste any MCP server's config": "Pega la configuración de cualquier servidor MCP",
"Loading the registry…": "Cargando el registro…",
- "tab switch · ↵ install / sign in · ^r refresh · esc close": "tab cambiar · ↵ instalar / iniciar sesión · ^r actualizar · esc cerrar",
- "tab switch · ↵ add / sign in · ^x remove · ^r refresh · esc": "tab cambiar · ↵ añadir / iniciar sesión · ^x eliminar · ^r actualizar · esc",
- "tab switch · ↵ details · ^x remove · esc close": "tab cambiar · ↵ detalles · ^x eliminar · esc cerrar",
+ "pgup/pgdn · alt-s · tab · ↵ install / sign in · ^r · esc": "PgUp/PgDn página · Alt-S tamaño · Tab pestaña · ↵ instalar / iniciar sesión · ^R · Esc",
+ "pgup/pgdn · alt-s · tab · ↵ add / sign in · ^x remove · esc": "PgUp/PgDn página · Alt-S tamaño · Tab pestaña · ↵ añadir / iniciar sesión · ^X quitar · Esc",
+ "pgup/pgdn · alt-s · tab · ↵ details · ^x remove · esc": "PgUp/PgDn página · Alt-S tamaño · Tab pestaña · ↵ detalles · ^X quitar · Esc",
"Sign in": "Iniciar sesión",
"No matching time zones": "No hay zonas horarias coincidentes",
"e.g. Morning summary": "Ej.: resumen de la mañana",
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
index 8993d4fa..06a42a9f 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
@@ -594,7 +594,6 @@
"Remove saved keys": "Supprimer les clés enregistrées",
"Added": "Ajouté",
"No instructions.": "Aucune instruction.",
- "Load more agents": "Charger plus d’agents",
"Credentials": "Identifiants",
"Connectors & skills": "Connecteurs et compétences",
"Search agents, connectors and skills": "Rechercher des agents, connecteurs et compétences",
@@ -606,20 +605,31 @@
"Not installed": "Non installé",
"Needs Node.js": "Nécessite Node.js",
"Sets up on first use": "Configuration à la première utilisation",
- "Agents matching “{query}”": "Agents correspondant à « {query} »",
"Couldn't load connectors.": "Impossible de charger les connecteurs.",
"No connectors match “{query}”.": "Aucun connecteur ne correspond à « {query} ».",
"Couldn't load apps.": "Impossible de charger les apps.",
"No apps match “{query}”.": "Aucune app ne correspond à « {query} ».",
- "Load more connectors": "Charger plus de connecteurs",
- "Make your own": "Créer le vôtre",
+ "Previous page": "Page précédente",
+ "Next page": "Page suivante",
+ "{count} total": "{count} au total",
+ "Per page": "Par page",
+ "6 / page": "6 / page",
+ "10 / page": "10 / page",
+ "20 / page": "20 / page",
+ "50 / page": "50 / page",
+ "Extensions sections": "Sections des extensions",
+ "No agents match “{query}”.": "Aucun agent ne correspond à « {query} ».",
+ "No skills match “{query}”.": "Aucune compétence ne correspond à « {query} ».",
+ "No agents yet.": "Pas encore d’agent.",
"Custom connector": "Connecteur personnalisé",
"Any MCP server: a command or a URL": "Tout serveur MCP : une commande ou une URL",
"Your own skill": "Votre propre compétence",
"Write instructions a bot can follow": "Écrivez des instructions qu’un bot peut suivre",
"{count} installed": "{count} installés",
"Connectors come from the official MCP Registry, apps through Composio, skills from Anthropic, agents from the ACP registry. Everything installs on {name}.": "Les connecteurs proviennent du MCP Registry officiel, les apps de Composio, les compétences d’Anthropic et les agents du registre ACP. Tout s’installe sur {name}.",
- "Connectors come from the official MCP Registry, skills from Anthropic, agents from the ACP registry. Everything installs on {name}.": "Les connecteurs proviennent du MCP Registry officiel, les compétences d’Anthropic et les agents du registre ACP. Tout s’installe sur {name}.",
+ "Agents come from the ACP registry and install on {name}.": "Les agents proviennent du registre ACP et s’installent sur {name}.",
+ "Connectors come from the official MCP Registry and install on {name}.": "Les connecteurs proviennent du MCP Registry officiel et s’installent sur {name}.",
+ "Skills come from Anthropic and install on {name}.": "Les compétences proviennent d’Anthropic et s’installent sur {name}.",
"Node.js isn't on {name}": "Node.js n’est pas sur {name}",
"Couldn't load more connectors.": "Impossible de charger davantage de connecteurs.",
"Couldn't load skills.": "Impossible de charger les compétences.",
@@ -636,9 +646,9 @@
"Some agents need it to run. Codync adds a copy just for them.": "Certains agents en ont besoin pour fonctionner. Codync en installe une copie dédiée.",
"Paste any MCP server's config": "Collez la configuration d’un serveur MCP",
"Loading the registry…": "Chargement du registre…",
- "tab switch · ↵ install / sign in · ^r refresh · esc close": "tab changer · ↵ installer / se connecter · ^r actualiser · esc fermer",
- "tab switch · ↵ add / sign in · ^x remove · ^r refresh · esc": "tab changer · ↵ ajouter / se connecter · ^x supprimer · ^r actualiser · esc",
- "tab switch · ↵ details · ^x remove · esc close": "tab changer · ↵ détails · ^x supprimer · esc fermer",
+ "pgup/pgdn · alt-s · tab · ↵ install / sign in · ^r · esc": "PgUp/PgDn page · Alt-S taille · Tab onglet · ↵ installer / connexion · ^R · Esc",
+ "pgup/pgdn · alt-s · tab · ↵ add / sign in · ^x remove · esc": "PgUp/PgDn page · Alt-S taille · Tab onglet · ↵ ajouter / connexion · ^X retirer · Esc",
+ "pgup/pgdn · alt-s · tab · ↵ details · ^x remove · esc": "PgUp/PgDn page · Alt-S taille · Tab onglet · ↵ détails · ^X retirer · Esc",
"Sign in": "Se connecter",
"No matching time zones": "Aucun fuseau horaire correspondant",
"e.g. Morning summary": "Ex. : résumé du matin",
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
index ce989780..4d451ab2 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
@@ -594,7 +594,6 @@
"Remove saved keys": "保存されたキーを削除する",
"Added": "追加した",
"No instructions.": "指示はありません。",
- "Load more agents": "さらにエージェントをロードする",
"Credentials": "認証情報",
"Connectors & skills": "コネクターとスキル",
"Search agents, connectors and skills": "エージェント、コネクタ、スキルを検索する",
@@ -606,20 +605,31 @@
"Not installed": "インストールされていません",
"Needs Node.js": "Node.jsが必要",
"Sets up on first use": "初めて使用するときにセットアップする",
- "Agents matching “{query}”": "「{query}」に一致するエージェント",
"Couldn't load connectors.": "コネクタをロードできませんでした。",
"No connectors match “{query}”.": "「{query}」に一致するコネクタはありません。",
"Couldn't load apps.": "アプリを読み込めませんでした。",
"No apps match “{query}”.": "「{query}」に一致するアプリはありません。",
- "Load more connectors": "さらにコネクタをロードする",
- "Make your own": "自分で作ってください",
+ "Previous page": "前のページ",
+ "Next page": "次のページ",
+ "{count} total": "全 {count} 件",
+ "Per page": "ページあたり",
+ "6 / page": "6 件/ページ",
+ "10 / page": "10 件/ページ",
+ "20 / page": "20 件/ページ",
+ "50 / page": "50 件/ページ",
+ "Extensions sections": "拡張機能の区分",
+ "No agents match “{query}”.": "「{query}」に一致するエージェントはありません。",
+ "No skills match “{query}”.": "「{query}」に一致するスキルはありません。",
+ "No agents yet.": "エージェントはまだありません。",
"Custom connector": "カスタムコネクタ",
"Any MCP server: a command or a URL": "任意の MCP サーバー: コマンドまたは URL",
"Your own skill": "あなた自身のスキル",
"Write instructions a bot can follow": "ボットが従うことができる指示を書く",
"{count} installed": "{count}がインストールされました",
"Connectors come from the official MCP Registry, apps through Composio, skills from Anthropic, agents from the ACP registry. Everything installs on {name}.": "コネクタは公式 MCP レジストリから、アプリは Composio から、スキルは Anthropic から、エージェントは ACP レジストリから取得されます。すべては{name}にインストールされます。",
- "Connectors come from the official MCP Registry, skills from Anthropic, agents from the ACP registry. Everything installs on {name}.": "コネクタは公式 MCP レジストリから、スキルは Anthropic から、エージェントは ACP レジストリから取得されます。すべては{name}にインストールされます。",
+ "Agents come from the ACP registry and install on {name}.": "エージェントは ACP レジストリから取得され、{name} にインストールされます。",
+ "Connectors come from the official MCP Registry and install on {name}.": "コネクタは公式 MCP レジストリから取得され、{name} にインストールされます。",
+ "Skills come from Anthropic and install on {name}.": "スキルは Anthropic から取得され、{name} にインストールされます。",
"Node.js isn't on {name}": "Node.js は {name} にありません",
"Couldn't load more connectors.": "これ以上コネクタをロードできませんでした。",
"Couldn't load skills.": "スキルをロードできませんでした。",
@@ -636,9 +646,9 @@
"Some agents need it to run. Codync adds a copy just for them.": "一部のエージェントは実行するためにこれを必要とします。 Codync は彼ら専用のコピーを追加します。",
"Paste any MCP server's config": "MCP サーバーの設定を貼り付けます",
"Loading the registry…": "レジストリをロード中…",
- "tab switch · ↵ install / sign in · ^r refresh · esc close": "タブスイッチ · ↵ インストール/サインイン · ^r 更新 · Esc 閉じる",
- "tab switch · ↵ add / sign in · ^x remove · ^r refresh · esc": "タブ切り替え · ↵ 追加/サインイン · ^x 削除 · ^r 更新 · Esc",
- "tab switch · ↵ details · ^x remove · esc close": "タブスイッチ · ↵ 詳細 · ^x 削除 · Esc 閉じる",
+ "pgup/pgdn · alt-s · tab · ↵ install / sign in · ^r · esc": "PgUp/PgDn ページ · Alt-S 件数 · Tab 切替 · ↵ インストール / サインイン · ^R 更新 · Esc",
+ "pgup/pgdn · alt-s · tab · ↵ add / sign in · ^x remove · esc": "PgUp/PgDn ページ · Alt-S 件数 · Tab 切替 · ↵ 追加 / サインイン · ^X 削除 · Esc",
+ "pgup/pgdn · alt-s · tab · ↵ details · ^x remove · esc": "PgUp/PgDn ページ · Alt-S 件数 · Tab 切替 · ↵ 詳細 · ^X 削除 · Esc",
"Sign in": "サインイン",
"No matching time zones": "一致するタイムゾーンがありません",
"e.g. Morning summary": "例えば朝のまとめ",
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
index c6992d46..f5eb3265 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
@@ -594,7 +594,6 @@
"Remove saved keys": "저장된 키 제거",
"Added": "추가됨",
"No instructions.": "지침이 없습니다.",
- "Load more agents": "에이전트 더 불러오기",
"Credentials": "자격 증명",
"Connectors & skills": "커넥터 및 스킬",
"Search agents, connectors and skills": "에이전트, 커넥터, 스킬 검색",
@@ -606,20 +605,31 @@
"Not installed": "설치되지 않음",
"Needs Node.js": "Node.js 필요",
"Sets up on first use": "처음 사용할 때 설정됨",
- "Agents matching “{query}”": "“{query}”와 일치하는 에이전트",
"Couldn't load connectors.": "커넥터를 불러오지 못했습니다.",
"No connectors match “{query}”.": "“{query}”와 일치하는 커넥터가 없습니다.",
"Couldn't load apps.": "앱을 불러오지 못했습니다.",
"No apps match “{query}”.": "“{query}”와 일치하는 앱이 없습니다.",
- "Load more connectors": "커넥터 더 불러오기",
- "Make your own": "직접 만들기",
+ "Previous page": "이전 페이지",
+ "Next page": "다음 페이지",
+ "{count} total": "총 {count}개",
+ "Per page": "페이지당",
+ "6 / page": "6개/페이지",
+ "10 / page": "10개/페이지",
+ "20 / page": "20개/페이지",
+ "50 / page": "50개/페이지",
+ "Extensions sections": "확장 구분",
+ "No agents match “{query}”.": "“{query}”와 일치하는 에이전트가 없습니다.",
+ "No skills match “{query}”.": "“{query}”와 일치하는 기술이 없습니다.",
+ "No agents yet.": "에이전트가 아직 없습니다.",
"Custom connector": "사용자 지정 커넥터",
"Any MCP server: a command or a URL": "모든 MCP 서버: 명령 또는 URL",
"Your own skill": "나만의 스킬",
"Write instructions a bot can follow": "봇이 따를 지침 작성",
"{count} installed": "{count}개 설치됨",
"Connectors come from the official MCP Registry, apps through Composio, skills from Anthropic, agents from the ACP registry. Everything installs on {name}.": "커넥터는 공식 MCP Registry, 앱은 Composio, 스킬은 Anthropic, 에이전트는 ACP 레지스트리에서 제공됩니다. 모두 {name}에 설치됩니다.",
- "Connectors come from the official MCP Registry, skills from Anthropic, agents from the ACP registry. Everything installs on {name}.": "커넥터는 공식 MCP Registry, 스킬은 Anthropic, 에이전트는 ACP 레지스트리에서 제공됩니다. 모두 {name}에 설치됩니다.",
+ "Agents come from the ACP registry and install on {name}.": "에이전트는 ACP 레지스트리에서 제공되며 {name}에 설치됩니다.",
+ "Connectors come from the official MCP Registry and install on {name}.": "커넥터는 공식 MCP Registry에서 제공되며 {name}에 설치됩니다.",
+ "Skills come from Anthropic and install on {name}.": "스킬은 Anthropic에서 제공되며 {name}에 설치됩니다.",
"Node.js isn't on {name}": "{name}에 Node.js가 없습니다",
"Couldn't load more connectors.": "커넥터를 더 불러오지 못했습니다.",
"Couldn't load skills.": "스킬을 불러오지 못했습니다.",
@@ -636,9 +646,9 @@
"Some agents need it to run. Codync adds a copy just for them.": "일부 에이전트를 실행하려면 필요합니다. Codync가 해당 에이전트 전용으로 설치합니다.",
"Paste any MCP server's config": "MCP 서버 구성 붙여넣기",
"Loading the registry…": "레지스트리를 불러오는 중…",
- "tab switch · ↵ install / sign in · ^r refresh · esc close": "tab 전환 · ↵ 설치 / 로그인 · ^r 새로고침 · esc 닫기",
- "tab switch · ↵ add / sign in · ^x remove · ^r refresh · esc": "tab 전환 · ↵ 추가 / 로그인 · ^x 제거 · ^r 새로고침 · esc",
- "tab switch · ↵ details · ^x remove · esc close": "tab 전환 · ↵ 상세 정보 · ^x 제거 · esc 닫기",
+ "pgup/pgdn · alt-s · tab · ↵ install / sign in · ^r · esc": "PgUp/PgDn 페이지 · Alt-S 개수 · Tab 전환 · ↵ 설치 / 로그인 · ^R 새로고침 · Esc",
+ "pgup/pgdn · alt-s · tab · ↵ add / sign in · ^x remove · esc": "PgUp/PgDn 페이지 · Alt-S 개수 · Tab 전환 · ↵ 추가 / 로그인 · ^X 제거 · Esc",
+ "pgup/pgdn · alt-s · tab · ↵ details · ^x remove · esc": "PgUp/PgDn 페이지 · Alt-S 개수 · Tab 전환 · ↵ 자세히 · ^X 제거 · Esc",
"Sign in": "로그인",
"No matching time zones": "일치하는 시간대가 없습니다",
"e.g. Morning summary": "예: 아침 요약",
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
index 693d9f65..6bbb62b1 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
@@ -594,7 +594,6 @@
"Remove saved keys": "移除已保存的密钥",
"Added": "已添加",
"No instructions.": "没有说明。",
- "Load more agents": "加载更多智能体",
"Credentials": "凭证",
"Connectors & skills": "连接器和技能",
"Search agents, connectors and skills": "搜索智能体、连接器和技能",
@@ -606,20 +605,31 @@
"Not installed": "未安装",
"Needs Node.js": "需要 Node.js",
"Sets up on first use": "首次使用时设置",
- "Agents matching “{query}”": "匹配“{query}”的智能体",
"Couldn't load connectors.": "无法加载连接器。",
"No connectors match “{query}”.": "没有匹配“{query}”的连接器。",
"Couldn't load apps.": "无法加载应用。",
"No apps match “{query}”.": "没有匹配“{query}”的应用。",
- "Load more connectors": "加载更多连接器",
- "Make your own": "自己添加",
+ "Previous page": "上一页",
+ "Next page": "下一页",
+ "{count} total": "共 {count} 条",
+ "Per page": "每页",
+ "6 / page": "6 条/页",
+ "10 / page": "10 条/页",
+ "20 / page": "20 条/页",
+ "50 / page": "50 条/页",
+ "Extensions sections": "扩展分类",
+ "No agents match “{query}”.": "没有匹配“{query}”的智能体。",
+ "No skills match “{query}”.": "没有匹配“{query}”的技能。",
+ "No agents yet.": "还没有智能体。",
"Custom connector": "自定义连接器",
"Any MCP server: a command or a URL": "任意 MCP 服务器:一条命令或一个网址",
"Your own skill": "自己的技能",
"Write instructions a bot can follow": "写一段 Bot 可以遵循的指令",
"{count} installed": "已安装 {count} 个",
"Connectors come from the official MCP Registry, apps through Composio, skills from Anthropic, agents from the ACP registry. Everything installs on {name}.": "连接器来自官方 MCP Registry,应用通过 Composio,技能来自 Anthropic,智能体来自 ACP registry。全部安装在 {name} 上。",
- "Connectors come from the official MCP Registry, skills from Anthropic, agents from the ACP registry. Everything installs on {name}.": "连接器来自官方 MCP Registry,技能来自 Anthropic,智能体来自 ACP registry。全部安装在 {name} 上。",
+ "Agents come from the ACP registry and install on {name}.": "智能体来自 ACP registry,安装在 {name} 上。",
+ "Connectors come from the official MCP Registry and install on {name}.": "连接器来自官方 MCP Registry,安装在 {name} 上。",
+ "Skills come from Anthropic and install on {name}.": "技能来自 Anthropic,安装在 {name} 上。",
"Node.js isn't on {name}": "{name} 上没有 Node.js",
"Couldn't load more connectors.": "无法加载更多连接器。",
"Couldn't load skills.": "无法加载技能。",
@@ -636,9 +646,9 @@
"Some agents need it to run. Codync adds a copy just for them.": "有些智能体需要它才能运行。Codync 会只为它们添加一份。",
"Paste any MCP server's config": "粘贴任意 MCP 服务器的配置",
"Loading the registry…": "正在加载注册表…",
- "tab switch · ↵ install / sign in · ^r refresh · esc close": "Tab 切换 · ↵ 安装 / 登录 · ^r 刷新 · Esc 关闭",
- "tab switch · ↵ add / sign in · ^x remove · ^r refresh · esc": "Tab 切换 · ↵ 添加 / 登录 · ^x 移除 · ^r 刷新 · Esc",
- "tab switch · ↵ details · ^x remove · esc close": "Tab 切换 · ↵ 详情 · ^x 移除 · Esc 关闭",
+ "pgup/pgdn · alt-s · tab · ↵ install / sign in · ^r · esc": "PgUp/PgDn 翻页 · Alt-S 条数 · Tab 切换 · ↵ 安装 / 登录 · ^R 刷新 · Esc",
+ "pgup/pgdn · alt-s · tab · ↵ add / sign in · ^x remove · esc": "PgUp/PgDn 翻页 · Alt-S 条数 · Tab 切换 · ↵ 添加 / 登录 · ^X 移除 · Esc",
+ "pgup/pgdn · alt-s · tab · ↵ details · ^x remove · esc": "PgUp/PgDn 翻页 · Alt-S 条数 · Tab 切换 · ↵ 详情 · ^X 移除 · Esc",
"Sign in": "登录",
"No matching time zones": "没有匹配的时区",
"e.g. Morning summary": "例如:早晨摘要",
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
index a790b98a..50716047 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
@@ -594,7 +594,6 @@
"Remove saved keys": "移除已儲存的金鑰",
"Added": "已新增",
"No instructions.": "沒有說明。",
- "Load more agents": "載入更多智慧體",
"Credentials": "憑證",
"Connectors & skills": "聯結器和技能",
"Search agents, connectors and skills": "搜尋智慧體、聯結器和技能",
@@ -606,20 +605,31 @@
"Not installed": "未安裝",
"Needs Node.js": "需要 Node.js",
"Sets up on first use": "首次使用時設定",
- "Agents matching “{query}”": "匹配“{query}”的智慧體",
"Couldn't load connectors.": "無法載入聯結器。",
"No connectors match “{query}”.": "沒有匹配“{query}”的聯結器。",
"Couldn't load apps.": "無法載入應用。",
"No apps match “{query}”.": "沒有匹配“{query}”的應用。",
- "Load more connectors": "載入更多聯結器",
- "Make your own": "自己新增",
+ "Previous page": "上一頁",
+ "Next page": "下一頁",
+ "{count} total": "共 {count} 條",
+ "Per page": "每頁",
+ "6 / page": "6 條/頁",
+ "10 / page": "10 條/頁",
+ "20 / page": "20 條/頁",
+ "50 / page": "50 條/頁",
+ "Extensions sections": "擴充分類",
+ "No agents match “{query}”.": "沒有匹配“{query}”的智慧體。",
+ "No skills match “{query}”.": "沒有匹配“{query}”的技能。",
+ "No agents yet.": "還沒有智慧體。",
"Custom connector": "自定義聯結器",
"Any MCP server: a command or a URL": "任意 MCP 伺服器:一條命令或一個網址",
"Your own skill": "自己的技能",
"Write instructions a bot can follow": "寫一段 Bot 可以遵循的指令",
"{count} installed": "已安裝 {count} 個",
"Connectors come from the official MCP Registry, apps through Composio, skills from Anthropic, agents from the ACP registry. Everything installs on {name}.": "聯結器來自官方 MCP Registry,應用透過 Composio,技能來自 Anthropic,智慧體來自 ACP registry。全部安裝在 {name} 上。",
- "Connectors come from the official MCP Registry, skills from Anthropic, agents from the ACP registry. Everything installs on {name}.": "聯結器來自官方 MCP Registry,技能來自 Anthropic,智慧體來自 ACP registry。全部安裝在 {name} 上。",
+ "Agents come from the ACP registry and install on {name}.": "智慧體來自 ACP registry,安裝在 {name} 上。",
+ "Connectors come from the official MCP Registry and install on {name}.": "聯結器來自官方 MCP Registry,安裝在 {name} 上。",
+ "Skills come from Anthropic and install on {name}.": "技能來自 Anthropic,安裝在 {name} 上。",
"Node.js isn't on {name}": "{name} 上沒有 Node.js",
"Couldn't load more connectors.": "無法載入更多聯結器。",
"Couldn't load skills.": "無法載入技能。",
@@ -636,9 +646,9 @@
"Some agents need it to run. Codync adds a copy just for them.": "有些智慧體需要它才能執行。Codync 會只為它們新增一份。",
"Paste any MCP server's config": "貼上任意 MCP 伺服器的配置",
"Loading the registry…": "正在載入登錄檔…",
- "tab switch · ↵ install / sign in · ^r refresh · esc close": "Tab 切換 · ↵ 安裝 / 登入 · ^r 重新整理 · Esc 關閉",
- "tab switch · ↵ add / sign in · ^x remove · ^r refresh · esc": "Tab 切換 · ↵ 新增 / 登入 · ^x 移除 · ^r 重新整理 · Esc",
- "tab switch · ↵ details · ^x remove · esc close": "Tab 切換 · ↵ 詳情 · ^x 移除 · Esc 關閉",
+ "pgup/pgdn · alt-s · tab · ↵ install / sign in · ^r · esc": "PgUp/PgDn 翻頁 · Alt-S 條數 · Tab 切換 · ↵ 安裝 / 登入 · ^R 重新整理 · Esc",
+ "pgup/pgdn · alt-s · tab · ↵ add / sign in · ^x remove · esc": "PgUp/PgDn 翻頁 · Alt-S 條數 · Tab 切換 · ↵ 新增 / 登入 · ^X 移除 · Esc",
+ "pgup/pgdn · alt-s · tab · ↵ details · ^x remove · esc": "PgUp/PgDn 翻頁 · Alt-S 條數 · Tab 切換 · ↵ 詳情 · ^X 移除 · Esc",
"Sign in": "登入",
"No matching time zones": "沒有匹配的時區",
"e.g. Morning summary": "例如:早晨摘要",
diff --git a/apps/ios/Kit/Sources/CodyncUI/Marketplace/MarketRows.swift b/apps/ios/Kit/Sources/CodyncUI/Marketplace/MarketRows.swift
index d8036a5a..04d19a9c 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Marketplace/MarketRows.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Marketplace/MarketRows.swift
@@ -1,18 +1,6 @@
import CodyncKit
import SwiftUI
-struct MarketSection<Content: View>: View {
- let title: String
- @ViewBuilder let content: Content
-
- var body: some View {
- VStack(alignment: .leading, spacing: 12) {
- Text(L10n.tr(title)).font(.headline).foregroundStyle(Palette.text).padding(.leading, 4)
- content
- }
- }
-}
-
/// Two columns on wide screens, one on a phone.
struct ItemGrid<Content: View>: View {
@ViewBuilder let content: Content
@@ -36,23 +24,9 @@ struct AgentCard: View {
var body: some View {
Button(action: action) {
- VStack(spacing: 12) {
- AgentIcon(registry: backend.registry ?? backend.id, size: 34)
- .frame(width: 64, height: 64)
- .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 18, style: .continuous))
- VStack(spacing: 2) {
- Text(backend.name).font(.subheadline.weight(.semibold)).foregroundStyle(Palette.text).lineLimit(1)
- Text(L10n.tr(status))
- .font(.caption)
- .foregroundStyle(Palette.secondary)
- .lineLimit(1)
- }
- }
- .frame(maxWidth: .infinity)
- .padding(.vertical, 18)
- .padding(.horizontal, 10)
- .background(Palette.bubbleAgent.opacity(hovering ? 0.8 : 0.45), in: RoundedRectangle(cornerRadius: 18, style: .continuous))
- .contentShape(RoundedRectangle(cornerRadius: 18, style: .continuous))
+ AgentCardLabel(registry: backend.registry ?? backend.id, name: backend.name, status: L10n.tr(status))
+ .background(Palette.bubbleAgent.opacity(hovering ? 0.8 : 0.45), in: RoundedRectangle(cornerRadius: 18, style: .continuous))
+ .contentShape(RoundedRectangle(cornerRadius: 18, style: .continuous))
}
.buttonStyle(PressScale())
.onHover { h in withAnimation(Motion.hover) { hovering = h } }
@@ -60,6 +34,38 @@ struct AgentCard: View {
}
}
+/// An agent tile's logo, name and status line.
+private struct AgentCardLabel: View {
+ let registry: String?
+ let name: String
+ let status: String
+
+ var body: some View {
+ VStack(spacing: 10) {
+ AgentIcon(registry: registry, size: 30)
+ .frame(width: 56, height: 56)
+ .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 16, style: .continuous))
+ VStack(spacing: 2) {
+ Text(name).font(.subheadline.weight(.semibold)).foregroundStyle(Palette.text).lineLimit(1)
+ Text(status)
+ .font(.caption)
+ .foregroundStyle(Palette.secondary)
+ .lineLimit(1)
+ }
+ }
+ .frame(maxWidth: .infinity)
+ .padding(.vertical, 14)
+ .padding(.horizontal, 10)
+ }
+}
+
+/// An agent tile's room, with nothing in it. A short last page keeps a full page of rows, so the bar under it stays put.
+struct AgentCardSpacer: View {
+ var body: some View {
+ AgentCardLabel(registry: nil, name: " ", status: " ").hidden().accessibilityHidden(true)
+ }
+}
+
struct MarketRow<Icon: View>: View {
let title: String
let subtitle: String
@@ -111,11 +117,52 @@ struct MarketRow<Icon: View>: View {
}
}
+/// A catalog row's room, with nothing in it. A short last page keeps a full page of rows.
+struct MarketRowSpacer: View {
+ var body: some View {
+ MarketRow(title: " ", subtitle: " ", added: true) { Color.clear } add: {}
+ .hidden()
+ .accessibilityHidden(true)
+ }
+}
+
+/// Previous or next, beside the list on a phone: a dark filled circle (the text color, so white in dark mode)
+/// with the chevron in the page's background, faint when there is no page that way.
+struct PageEdgeButton: View {
+ let title: String
+ let systemImage: String
+ let enabled: Bool
+ let action: () -> Void
+
+ var body: some View {
+ Button(action: action) {
+ Image(systemName: systemImage)
+ .font(.subheadline.weight(.bold))
+ .frame(width: 36, height: 36)
+ .foregroundStyle(Palette.background)
+ .background(Palette.text, in: Circle())
+ .opacity(enabled ? 1 : 0.25)
+ }
+ .buttonStyle(PressScale())
+ .disabled(!enabled)
+ .accessibilityLabel(L10n.tr(title))
+ }
+}
+
/// Placeholder rows while a list loads, shaped like the real ones.
struct SkeletonGrid: View {
@State private var dim = false
var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ Text(L10n.tr("Loading…")).font(.footnote).foregroundStyle(Palette.secondary)
+ rows
+ }
+ .accessibilityElement(children: .ignore)
+ .accessibilityLabel(L10n.tr("Loading…"))
+ }
+
+ private var rows: some View {
ItemGrid {
ForEach(0..<4, id: \.self) { _ in
HStack(spacing: 14) {
@@ -223,3 +270,107 @@ struct WebLink: View {
.help(url.absoluteString)
}
}
+
+/// The bar under a list. A phone: the page size and the page number (previous and next sit beside the list).
+/// A wide layout: the count, the page size, previous, current / total, and next.
+struct CatalogPager: View {
+ let page: Int
+ let count: Int
+ let pageSize: Int
+ var hasMore = false
+ var loading = false
+ let go: (Int) -> Void
+ let onSize: (Int) -> Void
+ @Environment(\.horizontalSizeClass) private var sizeClass
+
+ private var pages: Int { CatalogPaging.pageCount(count, size: pageSize, hasMore: hasMore) }
+ private var current: Int { CatalogPaging.clamp(page: page, count: count, size: pageSize, hasMore: hasMore) }
+
+ var body: some View {
+ Group {
+ if sizeClass == .compact {
+ HStack(spacing: 12) {
+ sizeLabel
+ Spacer(minLength: 12)
+ fraction
+ }
+ .padding(.horizontal, 16)
+ .padding(.vertical, 8)
+ .background(Palette.bubbleAgent, in: Capsule())
+ } else {
+ controls
+ }
+ }
+ .font(.footnote)
+ }
+
+ private var controls: some View {
+ HStack(spacing: 12) {
+ total
+ sizePicker
+ navigation
+ }
+ }
+
+ private var total: some View {
+ Text(L10n.tr("{count} total").replacingOccurrences(of: "{count}", with: String(count)))
+ .foregroundStyle(Palette.secondary)
+ }
+
+ private var fraction: some View {
+ Text("\(current + 1) / \(pages)")
+ .font(.subheadline.weight(.semibold))
+ .foregroundStyle(Palette.text)
+ .monospacedDigit()
+ .accessibilityAddTraits(.isSelected)
+ }
+
+ /// The size menu, sitting on the capsule with no chip of its own.
+ private var sizeLabel: some View {
+ DropdownMenu {
+ CatalogPaging.pageSizes.map { size in
+ MenuItem("\(size) / page", selected: size == pageSize) { onSize(size) }
+ }
+ } label: {
+ HStack(spacing: 2) {
+ Text(L10n.tr("\(pageSize) / page"))
+ Image(systemName: "chevron.down").font(.caption2.weight(.semibold))
+ }
+ .foregroundStyle(Palette.secondary)
+ }
+ }
+
+ private var sizePicker: some View {
+ HStack(spacing: 6) {
+ Text(L10n.tr("Per page")).foregroundStyle(Palette.secondary)
+ DropdownMenu {
+ CatalogPaging.pageSizes.map { size in
+ MenuItem("\(size) / page", selected: size == pageSize) { onSize(size) }
+ }
+ } label: {
+ HStack(spacing: 4) {
+ Text(L10n.tr("\(pageSize) / page"))
+ Image(systemName: "chevron.down").font(.caption2.weight(.semibold))
+ }
+ .foregroundStyle(Palette.text)
+ .padding(.horizontal, 10)
+ .frame(height: 28)
+ .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 8, style: .continuous))
+ }
+ }
+ }
+
+ private var navigation: some View {
+ HStack(spacing: 4) {
+ IconButton("Previous page", systemImage: "chevron.left") { go(current - 1) }
+ .disabled(current == 0 || loading)
+ Text("\(current + 1) / \(pages)")
+ .foregroundStyle(Palette.text)
+ .monospacedDigit()
+ .frame(minWidth: 44)
+ .accessibilityAddTraits(.isSelected)
+ IconButton(loading ? "Loading…" : "Next page", systemImage: "chevron.right") { go(current + 1) }
+ .disabled(!CatalogPaging.canForward(count: count, page: current, hasMore: hasMore, size: pageSize) || loading)
+ }
+ }
+}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Marketplace/MarketplacePage.swift b/apps/ios/Kit/Sources/CodyncUI/Marketplace/MarketplacePage.swift
index 8f688a99..838b3b36 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Marketplace/MarketplacePage.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Marketplace/MarketplacePage.swift
@@ -1,15 +1,13 @@
-/// Keep fetched catalog metadata in memory, but create rows only as the user requests them.
+import SwiftUI
+
+/// Keep fetched catalog metadata in memory. The Extensions tabs page through it.
struct MarketplacePage<Item: Identifiable> {
private(set) var items: [Item] = []
- private(set) var visibleCount = 12
- var visible: ArraySlice<Item> { items.prefix(visibleCount) }
- var hasHiddenItems: Bool { items.count > visibleCount }
var isEmpty: Bool { items.isEmpty }
mutating func replace(with items: [Item]) {
self.items = []
- visibleCount = 12
append(items)
}
@@ -17,8 +15,110 @@ struct MarketplacePage<Item: Identifiable> {
var known = Set(items.map(\.id))
items += page.filter { known.insert($0.id).inserted }
}
+}
+
+/// How many catalog rows one Extensions page shows, and which page a click lands on.
+enum CatalogPaging {
+ static let pageSize = 10
+ /// Two agent tiles across, three rows: a page has no leftover card.
+ static let phonePageSize = 6
+ static let pageSizes = [6, 10, 20, 50]
+
+ /// Loaded rows split into pages. While the registry still has a cursor, one more page is offered so the bar is never 1 / 1 for a list that continues.
+ static func pageCount(_ count: Int, size: Int = pageSize, hasMore: Bool = false) -> Int {
+ let loaded = count <= 0 ? 1 : (count + size - 1) / size
+ return hasMore ? loaded + 1 : loaded
+ }
+
+ static func clamp(page: Int, count: Int, size: Int = pageSize, hasMore: Bool = false) -> Int {
+ min(max(0, page), pageCount(count, size: size, hasMore: hasMore) - 1)
+ }
+
+ static func slice<T>(_ items: [T], page: Int, size: Int = pageSize) -> ArraySlice<T> {
+ let start = max(0, page) * size
+ return items.dropFirst(start).prefix(size)
+ }
+
+ /// Next stays available through the last shown page, including the page that still has to be fetched.
+ static func canForward(count: Int, page: Int, hasMore: Bool, size: Int = pageSize) -> Bool {
+ page < pageCount(count, size: size, hasMore: hasMore) - 1
+ }
+
+ /// A later page that isn't full yet, so the registry has to be asked. The first page is whatever the first answer held.
+ static func needsFetch(count: Int, page: Int, size: Int = pageSize) -> Bool {
+ let start = max(0, page) * size
+ return start > 0 && start + size > count
+ }
+}
+
+/// The connector list Extensions pages through: the rows loaded so far, the registry cursor and the
+/// page on screen. A page that isn't full asks the registry until it is, or until the cursor ends.
+@MainActor @Observable
+final class ConnectorCatalog<Item: Identifiable> {
+ typealias Fetch = @MainActor (_ search: String, _ cursor: String?) async throws -> (items: [Item], next: String?)
+
+ private(set) var items = MarketplacePage<Item>()
+ /// The registry page after the ones loaded; nil at the end.
+ private(set) var cursor: String?
+ /// The page on screen. While the registry fills it, it can be the page past the loaded rows.
+ private(set) var page = 0
+ private(set) var loading = true
+ private(set) var loadingMore = false
+ private(set) var error: String?
+ private var request = UUID()
+ private var query = ""
+
+ var hasMore: Bool { cursor != nil }
+
+ /// The first registry page for `search`; answers to an older search are dropped.
+ func load(search: String, fetch: Fetch) async {
+ let request = UUID()
+ self.request = request
+ query = search
+ loading = true
+ loadingMore = false
+ defer { if self.request == request { loading = false } }
+ do {
+ let first = try await fetch(search, nil)
+ guard !Task.isCancelled, self.request == request else { return }
+ items.replace(with: first.items)
+ cursor = first.next
+ page = 0
+ error = nil
+ } catch {
+ guard self.request == request, !(error is CancellationError), !Task.isCancelled else { return }
+ items.replace(with: [])
+ cursor = nil
+ self.error = error.localizedDescription
+ }
+ }
+
+ /// Turns to `next` at once, so a swipe stays where it landed; `fill` then loads its rows.
+ func show(_ next: Int, size: Int) {
+ guard !loading else { return }
+ page = CatalogPaging.clamp(page: next, count: items.items.count, size: size, hasMore: hasMore)
+ }
- mutating func revealMore() {
- visibleCount = min(items.count, visibleCount + 12)
+ /// Asks the registry until the page on screen is full or the cursor ends. A page turned meanwhile is
+ /// filled by the same loop. If a page fails, the list goes back to the last page with rows.
+ func fill(size: Int, animation: Animation? = nil, fetch: Fetch) async {
+ guard !loading, !loadingMore, hasMore, CatalogPaging.needsFetch(count: items.items.count, page: page, size: size) else { return }
+ let request = self.request
+ loadingMore = true
+ defer { if self.request == request { loadingMore = false } }
+ do {
+ while let cursor, CatalogPaging.needsFetch(count: items.items.count, page: page, size: size) {
+ let more = try await fetch(query, cursor)
+ guard !Task.isCancelled, self.request == request else { return }
+ items.append(more.items)
+ self.cursor = more.next
+ }
+ page = CatalogPaging.clamp(page: page, count: items.items.count, size: size, hasMore: hasMore)
+ error = nil
+ } catch {
+ guard self.request == request, !(error is CancellationError), !Task.isCancelled else { return }
+ self.error = error.localizedDescription
+ withAnimation(animation) { page = CatalogPaging.clamp(page: page, count: items.items.count, size: size) }
+ }
}
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Marketplace/MarketplaceTabs.swift b/apps/ios/Kit/Sources/CodyncUI/Marketplace/MarketplaceTabs.swift
new file mode 100644
index 00000000..2a30eeec
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncUI/Marketplace/MarketplaceTabs.swift
@@ -0,0 +1,189 @@
+import CodyncKit
+import SwiftUI
+
+extension MarketplaceView {
+ var extensionRail: some View {
+ VStack(alignment: .leading, spacing: 4) {
+ ForEach(ExtensionSection.allCases) { item in
+ let on = section == item
+ Button {
+ withAnimation(Motion.morph) { section = item }
+ } label: {
+ HStack(spacing: 10) {
+ Image(systemName: item.icon)
+ Text(L10n.tr(item.title))
+ }
+ .font(.subheadline.weight(on ? .semibold : .regular))
+ .foregroundStyle(on ? Palette.text : Palette.secondary)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, 12)
+ .padding(.vertical, 8)
+ .background(on ? Palette.bubbleAgent : Color.clear, in: RoundedRectangle(cornerRadius: 12, style: .continuous))
+ .contentShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
+ }
+ .buttonStyle(PressScale())
+ .accessibilityAddTraits(on ? .isSelected : [])
+ }
+ }
+ .frame(width: 168)
+ .accessibilityElement(children: .contain)
+ .accessibilityLabel(L10n.tr("Extensions sections"))
+ }
+
+ @ViewBuilder var tabBody: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ switch section {
+ case .agents: agentsTab
+ case .connectors: connectorsTab
+ case .skills: skillsTab
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ // On a phone the section gives up a little width so the page buttons beside the list have room.
+ .padding(.horizontal, sizeClass == .compact ? 8 : 0)
+ .id(section)
+ .transition(.opacity)
+ }
+
+ @ViewBuilder private var agentsTab: some View {
+ if model.hello?.backends.contains(where: \.needsNode) == true {
+ NodeNotice { addingNode = true }
+ }
+ if agents.isEmpty {
+ Text(query.isEmpty ? L10n.tr("No agents yet.") : L10n.tr("No agents match “{query}”.").replacingOccurrences(of: "{query}", with: query))
+ .foregroundStyle(Palette.secondary)
+ } else {
+ flanked(count: agents.count, page: agentPage) { index in
+ let shown = Array(CatalogPaging.slice(agents, page: index, size: pageSize))
+ LazyVGrid(columns: agentColumns, spacing: 10) {
+ ForEach(shown) { b in agentCard(b) }
+ ForEach(0..<pagePad(count: agents.count, shown: shown.count), id: \.self) { _ in AgentCardSpacer() }
+ }
+ }
+ }
+ CatalogPager(page: agentPage, count: agents.count, pageSize: pageSize, go: { agentPage = CatalogPaging.clamp(page: $0, count: agents.count, size: pageSize) }, onSize: changePageSize)
+ }
+
+ @ViewBuilder private var connectorsTab: some View {
+ MarketRow(title: "Custom connector", subtitle: "Any MCP server: a command or a URL", added: false, addLabel: "New") {
+ TileIcon(systemName: "point.3.connected.trianglepath.dotted")
+ } add: {
+ addingConnector = true
+ }
+ if connectors.loading {
+ SkeletonGrid()
+ } else if connectors.items.isEmpty {
+ Text(query.isEmpty ? L10n.tr("Couldn't load connectors.") : L10n.tr("No connectors match “{query}”.").replacingOccurrences(of: "{query}", with: query))
+ .foregroundStyle(Palette.secondary)
+ } else {
+ let rows = connectors.items.items
+ flanked(count: rows.count, page: connectors.page, hasMore: connectors.hasMore, loading: connectors.loadingMore) { index in
+ let shown = Array(CatalogPaging.slice(rows, page: index, size: pageSize))
+ // The page past the loaded rows, while the registry fills it.
+ if shown.isEmpty {
+ SkeletonGrid()
+ } else {
+ ItemGrid {
+ ForEach(shown) { c in
+ MarketRow(title: c.title, subtitle: c.description ?? c.name, added: c.installed) {
+ ServiceLogo(website: c.website, name: c.title, registryName: c.name)
+ } add: {
+ installing = c
+ }
+ }
+ ForEach(0..<pagePad(count: rows.count, shown: shown.count), id: \.self) { _ in MarketRowSpacer() }
+ }
+ }
+ }
+ }
+ if !connectors.loading {
+ CatalogPager(page: connectors.page, count: connectors.items.items.count, pageSize: pageSize, hasMore: connectors.hasMore,
+ loading: connectors.loadingMore, go: { showConnectorPage($0, animated: true) }, onSize: changePageSize)
+ }
+ }
+
+ @ViewBuilder private var skillsTab: some View {
+ MarketRow(title: "Your own skill", subtitle: "Write instructions a bot can follow", added: false, addLabel: "New") {
+ TileIcon(systemName: "square.and.pencil")
+ } add: {
+ writingSkill = true
+ }
+ if loadingSkills {
+ SkeletonGrid()
+ } else if shownSkills.isEmpty {
+ if !query.isEmpty {
+ Text(L10n.tr("No skills match “{query}”.").replacingOccurrences(of: "{query}", with: query))
+ .foregroundStyle(Palette.secondary)
+ }
+ } else {
+ flanked(count: shownSkills.count, page: skillPage) { index in
+ let shown = Array(CatalogPaging.slice(shownSkills, page: index, size: pageSize))
+ ItemGrid {
+ ForEach(shown) { s in
+ let added = s.installed || model.installedSkills.contains { $0.id == s.source.lowercased() }
+ MarketRow(title: s.name, subtitle: s.description, added: added, busy: busySkill == s.source,
+ open: { viewingSkill = SkillRef(s, installed: added) }) {
+ SkillGlyph()
+ } add: {
+ busySkill = s.source
+ Task {
+ do { try await model.installSkill(source: s.source) } catch { report(error) }
+ busySkill = nil
+ }
+ }
+ }
+ ForEach(0..<pagePad(count: shownSkills.count, shown: shown.count), id: \.self) { _ in MarketRowSpacer() }
+ }
+ }
+ }
+ if !loadingSkills {
+ CatalogPager(page: skillPage, count: shownSkills.count, pageSize: pageSize, go: { skillPage = CatalogPaging.clamp(page: $0, count: shownSkills.count, size: pageSize) }, onSize: changePageSize)
+ }
+ }
+
+ /// How many invisible rows a short last page needs so the bar under the list does not jump.
+ private func pagePad(count: Int, shown: Int) -> Int {
+ count > pageSize ? max(0, pageSize - shown) : 0
+ }
+
+ /// On a phone the pages sit side by side in a paging scroll view, so a swipe turns the page,
+ /// with previous and next on either side. A wide layout shows the one page.
+ @ViewBuilder private func flanked<Content: View>(count: Int, page: Int, hasMore: Bool = false, loading: Bool = false, @ViewBuilder content: @escaping (Int) -> Content) -> some View {
+ let pages = CatalogPaging.pageCount(count, size: pageSize, hasMore: hasMore)
+ let current = CatalogPaging.clamp(page: page, count: count, size: pageSize, hasMore: hasMore)
+ if sizeClass == .compact {
+ ScrollView(.horizontal) {
+ LazyHStack(alignment: .top, spacing: 0) {
+ ForEach(0..<pages, id: \.self) { index in
+ content(index).containerRelativeFrame(.horizontal)
+ }
+ }
+ .scrollTargetLayout()
+ }
+ .scrollTargetBehavior(.paging)
+ .scrollIndicators(.hidden)
+ .scrollPosition(id: Binding(get: { current }, set: { if let index = $0, index != current { swiped(to: index) } }))
+ .overlay {
+ if pages > 1 {
+ HStack(spacing: 0) {
+ PageEdgeButton(title: "Previous page", systemImage: "chevron.left", enabled: current > 0 && !loading) { slide(forward: false) }
+ Color.clear.frame(maxWidth: .infinity).allowsHitTesting(false)
+ PageEdgeButton(title: loading ? "Loading…" : "Next page", systemImage: "chevron.right",
+ enabled: CatalogPaging.canForward(count: count, page: current, hasMore: hasMore, size: pageSize) && !loading) { slide(forward: true) }
+ }
+ .padding(.horizontal, -44)
+ }
+ }
+ } else {
+ content(current)
+ }
+ }
+
+ /// Two tiles across on a phone. One flexible column stretches each icon into a full-width card.
+ private var agentColumns: [GridItem] {
+ sizeClass == .compact
+ ? [GridItem(.flexible(), spacing: 10), GridItem(.flexible(), spacing: 10)]
+ : [GridItem(.adaptive(minimum: 160), spacing: 10)]
+ }
+
+}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Marketplace/MarketplaceView.swift b/apps/ios/Kit/Sources/CodyncUI/Marketplace/MarketplaceView.swift
index fec2e354..fe53872a 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Marketplace/MarketplaceView.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Marketplace/MarketplaceView.swift
@@ -1,46 +1,46 @@
import CodyncKit
import SwiftUI
-/// The Marketplace (Grok Bot's layout): one page of agents, connectors and
-/// skills for the bots on one computer (the store in the environment). Installing happens on that
+/// Extensions for the bots on one computer (the store in the environment): Agents,
+/// Connectors and Skills, one at a time. Each list turns a page; a connector page that
+/// isn't full fetches more from the registry (`ConnectorCatalog`). Installing happens on that
/// computer; each bot turns connectors and skills on in its settings.
public struct MarketplaceView: View {
- @Environment(BotStore.self) private var model
- @State private var search = ""
- @State private var connectors = MarketplacePage<MarketConnector>()
- @State private var connectorRequest = UUID()
- @State private var connectorQuery = ""
- /// The registry page after the ones shown; nil at the end.
- @State private var connectorCursor: String?
- @State private var loadingMore = false
- @State private var skills: [MarketSkill] = []
- @State private var loadingConnectors = true
- @State private var loadingSkills = true
- @State private var error: String?
- @State private var installing: MarketConnector?
- @State private var busySkill: String?
- @State private var addingConnector = false
- @State private var writingSkill = false
- @State private var viewingSkill: SkillRef?
- @State private var agent: Backend?
- @State private var addingNode = false
- /// Agents shown before "Load more agents".
- @State private var agentLimit = 10
- @State private var showInstalled = false
- @State private var showCredentials = false
+ @Environment(BotStore.self) var model
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
+ @State var search = ""
+ @State var connectors = ConnectorCatalog<MarketConnector>()
+ @State var skills: [MarketSkill] = []
+ @State var loadingSkills = true
+ @State var error: String?
+ @State var installing: MarketConnector?
+ @State var busySkill: String?
+ @State var addingConnector = false
+ @State var writingSkill = false
+ @State var viewingSkill: SkillRef?
+ @State var agent: Backend?
+ @State var addingNode = false
+ @State var section = ExtensionSection.agents
+ @State var agentPage = 0
+ @State var skillPage = 0
+ /// Nil until the menu is used, so a phone stays at 6 and a wide layout stays at 10.
+ @State var chosenPageSize: Int?
+ @State var showInstalled = false
+ @State var showCredentials = false
@Environment(\.dismissModal) private var dismiss
+ @Environment(\.horizontalSizeClass) var sizeClass
/// Each computer has its own marketplace (the `BotStore` in the environment).
public init() {}
- private var query: String { search.trimmingCharacters(in: .whitespaces) }
+ var query: String { search.trimmingCharacters(in: .whitespaces) }
- private var agents: [Backend] {
+ var agents: [Backend] {
let all = (model.hello?.backends ?? []).filter { $0.available || $0.installed == true || $0.curated == true }
return query.isEmpty ? all : all.filter { $0.name.localizedCaseInsensitiveContains(query) }
}
- private var shownSkills: [MarketSkill] {
+ var shownSkills: [MarketSkill] {
query.isEmpty ? skills : skills.filter { $0.name.localizedCaseInsensitiveContains(query) || $0.description.localizedCaseInsensitiveContains(query) }
}
@@ -64,9 +64,12 @@ public struct MarketplaceView: View {
.task { await model.refreshBackends() }
.task { await loadConnectors() }
.task {
- do { skills = try await model.marketSkills() } catch { self.error = error.localizedDescription }
- loadingSkills = false
+ loadingSkills = true
+ do { skills = try await model.marketSkills() } catch { report(error) }
+ if !Task.isCancelled { loadingSkills = false }
}
+ // A size picked from the menu, or one that follows the layout, starts every list over.
+ .onChange(of: pageSize) { _, _ in resetPages() }
.codyncSheet(item: $installing) { item in
InstallConnectorSheet(item: item) { Task { await loadConnectors() } }
}
@@ -83,96 +86,24 @@ public struct MarketplaceView: View {
VStack(alignment: .leading, spacing: 28) {
header
searchField
- if !agents.isEmpty {
- MarketSection(title: query.isEmpty ? "Agents" : L10n.tr("Agents matching “{query}”").replacingOccurrences(of: "{query}", with: query)) {
- if model.hello?.backends.contains(where: \.needsNode) == true {
- NodeNotice { addingNode = true }
- }
- ScrollView(.horizontal, showsIndicators: false) {
- LazyHStack(spacing: 10) {
- ForEach(agents.prefix(agentLimit)) { b in agentCard(b).frame(width: 128) }
- }
- .padding(.horizontal, 24)
- }
- .padding(.horizontal, -24)
- if agents.count > agentLimit {
- Button(L10n.tr("Load more agents")) {
- withAnimation(Motion.fade) { agentLimit += 10 }
- }
- .buttonStyle(SecondaryButtonStyle())
- .frame(maxWidth: .infinity)
- }
- }
- }
- MarketSection(title: query.isEmpty ? "Connectors" : "Connectors") {
- if loadingConnectors {
- SkeletonGrid()
- } else if connectors.isEmpty {
- Text(query.isEmpty ? L10n.tr("Couldn't load connectors.") : L10n.tr("No connectors match “{query}”.").replacingOccurrences(of: "{query}", with: query))
- .foregroundStyle(Palette.secondary)
- } else {
- ItemGrid {
- ForEach(connectors.visible) { c in
- MarketRow(title: c.title, subtitle: c.description ?? c.name, added: c.installed) {
- ServiceLogo(website: c.website, name: c.title, registryName: c.name)
- } add: {
- installing = c
- }
- }
- }
- if connectors.hasHiddenItems || connectorCursor != nil {
- Button(L10n.tr(loadingMore ? "Loading…" : "Load more connectors")) { Task { await loadMoreConnectors() } }
- .buttonStyle(SecondaryButtonStyle())
- .disabled(loadingMore)
- .frame(maxWidth: .infinity)
- }
- }
- }
- MarketSection(title: "Skills") {
- if loadingSkills {
- SkeletonGrid()
- } else {
- ItemGrid {
- ForEach(shownSkills) { s in
- let added = s.installed || model.installedSkills.contains { $0.id == s.source.lowercased() }
- MarketRow(title: s.name, subtitle: s.description, added: added, busy: busySkill == s.source,
- open: { viewingSkill = SkillRef(s, installed: added) }) {
- SkillGlyph()
- } add: {
- busySkill = s.source
- Task {
- do { try await model.installSkill(source: s.source) } catch { self.error = error.localizedDescription }
- busySkill = nil
- }
- }
- }
- }
+ if sizeClass == .compact {
+ VStack(alignment: .leading, spacing: 8) {
+ TabChoice(selection: $section, options: ExtensionSection.allCases.map { (id: $0, label: $0.title) })
+ sourceLine
}
- }
- Button { withAnimation(Motion.layout) { showCredentials = true } } label: {
- Label(L10n.tr("Credentials"), systemImage: "lock.shield")
- }
- .buttonStyle(SecondaryButtonStyle())
- MarketSection(title: "Make your own") {
- ItemGrid {
- MarketRow(title: "Custom connector", subtitle: "Any MCP server: a command or a URL", added: false, addLabel: "New") {
- TileIcon(systemName: "point.3.connected.trianglepath.dotted")
- } add: {
- addingConnector = true
- }
- MarketRow(title: "Your own skill", subtitle: "Write instructions a bot can follow", added: false, addLabel: "New") {
- TileIcon(systemName: "square.and.pencil")
- } add: {
- writingSkill = true
+ tabBody
+ } else {
+ HStack(alignment: .top, spacing: 20) {
+ extensionRail
+ VStack(alignment: .leading, spacing: 12) {
+ sourceLine
+ tabBody.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
- if let error {
+ if let error = error ?? connectors.error {
Text(L10n.tr(error)).font(.footnote).foregroundStyle(Palette.danger)
}
- Text(L10n.tr("Connectors come from the official MCP Registry, skills from Anthropic, agents from the ACP registry. Everything installs on {name}.").replacingOccurrences(of: "{name}", with: model.hostName))
- .font(.footnote)
- .foregroundStyle(Palette.tertiary)
}
.padding(.horizontal, 44)
.padding(.vertical, 20)
@@ -203,8 +134,16 @@ public struct MarketplaceView: View {
}
.lineLimit(1)
.minimumScaleFactor(0.7)
+ Spacer(minLength: 8)
+ // Beside the title, in the room left of Close, so the list can fill the screen.
+ Button { withAnimation(Motion.layout) { showCredentials = true } } label: {
+ Label(L10n.tr("Credentials"), systemImage: "lock.shield")
+ }
+ .buttonStyle(SecondaryButtonStyle())
+ .fixedSize()
+ .layoutPriority(1)
}
- .layoutPriority(1)
+ .frame(maxWidth: .infinity)
if installedCount > 0 {
Button { withAnimation(Motion.layout) { showInstalled = true } } label: {
HStack(spacing: 8) {
@@ -228,6 +167,14 @@ public struct MarketplaceView: View {
.padding(.top, 28)
}
+ /// One sentence for the open section, tucked under its tab.
+ private var sourceLine: some View {
+ Text(L10n.tr(section.source).replacingOccurrences(of: "{name}", with: model.hostName))
+ .font(.footnote)
+ .foregroundStyle(Palette.tertiary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+
private var searchField: some View {
HStack(spacing: 10) {
Image(systemName: "magnifyingglass").foregroundStyle(Palette.secondary)
@@ -235,7 +182,7 @@ public struct MarketplaceView: View {
.textFieldStyle(.plain)
.plainTextInput()
.onSubmit { Task { await loadConnectors() } }
- .onChange(of: search) { agentLimit = 10 }
+ .onChange(of: search) { _, _ in resetPages() }
if !search.isEmpty {
Button { search = ""; Task { await loadConnectors() } } label: {
Image(systemName: "xmark.circle.fill").foregroundStyle(Palette.tertiary)
@@ -249,54 +196,102 @@ public struct MarketplaceView: View {
.background(Palette.bubbleAgent, in: Capsule())
}
- private func agentCard(_ b: Backend) -> some View {
+ func agentCard(_ b: Backend) -> some View {
AgentCard(backend: b) { agent = b }
}
private func loadConnectors() async {
- let request = UUID()
- connectorRequest = request
- connectorQuery = query
- loadingConnectors = true
- loadingMore = false
- defer { if connectorRequest == request { loadingConnectors = false } }
- do {
- let page = try await model.marketConnectors(search: connectorQuery)
- guard !Task.isCancelled, connectorRequest == request else { return }
- connectors.replace(with: page.items)
- connectorCursor = page.next
- error = nil
- } catch {
- guard !Task.isCancelled, connectorRequest == request else { return }
- connectors.replace(with: [])
- connectorCursor = nil
- self.error = error.localizedDescription
+ await connectors.load(search: query, fetch: fetchConnectors)
+ }
+
+ private func fetchConnectors(search: String, cursor: String?) async throws -> (items: [MarketConnector], next: String?) {
+ try await model.marketConnectors(search: search, cursor: cursor)
+ }
+
+ /// A load that SwiftUI cancelled is the next load starting, not a failure to show.
+ func report(_ error: Error) {
+ if error is CancellationError || Task.isCancelled { return }
+ self.error = error.localizedDescription
+ }
+
+ var pageSize: Int {
+ chosenPageSize ?? (sizeClass == .compact ? CatalogPaging.phonePageSize : CatalogPaging.pageSize)
+ }
+
+ private func canTurn(_ forward: Bool) -> Bool {
+ let (page, count, hasMore) = switch section {
+ case .agents: (agentPage, agents.count, false)
+ case .skills: (skillPage, shownSkills.count, false)
+ case .connectors: (connectors.page, connectors.items.items.count, connectors.hasMore)
}
+ if section == .connectors, connectors.loading || connectors.loadingMore { return false }
+ let next = page + (forward ? 1 : -1)
+ return CatalogPaging.clamp(page: next, count: count, size: pageSize, hasMore: hasMore) == next
}
- private func loadMoreConnectors() async {
- guard !loadingMore, !loadingConnectors else { return }
- if connectors.hasHiddenItems {
- withAnimation(Motion.fade) { connectors.revealMore() }
- return
+ /// How a page turn from an arrow scrolls the pager.
+ var pageMotion: Animation? { reduceMotion ? nil : Motion.layout }
+
+ /// The arrow buttons turn the page; on a phone the pager scrolls over to it.
+ func slide(forward: Bool) {
+ guard canTurn(forward) else { return }
+ let step = forward ? 1 : -1
+ switch section {
+ case .agents: withAnimation(pageMotion) { agentPage += step }
+ case .skills: withAnimation(pageMotion) { skillPage += step }
+ case .connectors: showConnectorPage(connectors.page + step, animated: true)
}
- guard let cursor = connectorCursor else { return }
- let request = connectorRequest
- loadingMore = true
- defer { if connectorRequest == request { loadingMore = false } }
- do {
- let page = try await model.marketConnectors(search: connectorQuery, cursor: cursor)
- guard !Task.isCancelled, connectorRequest == request else { return }
- withAnimation(Motion.fade) {
- connectors.append(page.items)
- connectors.revealMore()
- }
- connectorCursor = page.next
- error = nil
- } catch {
- guard !Task.isCancelled, connectorRequest == request else { return }
- self.error = error.localizedDescription
+ }
+
+ /// A swipe landed on `page`. The page shows at once; a connector page that isn't full then fills.
+ func swiped(to page: Int) {
+ switch section {
+ case .agents: agentPage = page
+ case .skills: skillPage = page
+ case .connectors: showConnectorPage(page, animated: false)
}
}
+ /// The new size starts every list over (`onChange(of: pageSize)`).
+ func changePageSize(_ size: Int) {
+ chosenPageSize = size
+ }
+
+ private func resetPages() {
+ agentPage = 0
+ skillPage = 0
+ connectors.show(0, size: pageSize)
+ }
+
+ /// Turns the connector list to `page`; a page that isn't full then fills from the registry.
+ func showConnectorPage(_ page: Int, animated: Bool) {
+ withAnimation(animated ? pageMotion : nil) { connectors.show(page, size: pageSize) }
+ Task { await connectors.fill(size: pageSize, animation: pageMotion, fetch: fetchConnectors) }
+ }
+}
+
+enum ExtensionSection: String, CaseIterable, Identifiable {
+ case agents, connectors, skills
+ var id: String { rawValue }
+ var title: String {
+ switch self {
+ case .agents: "Agents"
+ case .connectors: "Connectors"
+ case .skills: "Skills"
+ }
+ }
+ var icon: String {
+ switch self {
+ case .agents: "terminal"
+ case .connectors: "point.3.connected.trianglepath.dotted"
+ case .skills: "book.pages"
+ }
+ }
+ var source: String {
+ switch self {
+ case .agents: "Agents come from the ACP registry and install on {name}."
+ case .connectors: "Connectors come from the official MCP Registry and install on {name}."
+ case .skills: "Skills come from Anthropic and install on {name}."
+ }
+ }
}
diff --git a/apps/ios/Kit/Tests/CodyncUITests/MarketplacePageTests.swift b/apps/ios/Kit/Tests/CodyncUITests/MarketplacePageTests.swift
index b3ff282b..1303e34d 100644
--- a/apps/ios/Kit/Tests/CodyncUITests/MarketplacePageTests.swift
+++ b/apps/ios/Kit/Tests/CodyncUITests/MarketplacePageTests.swift
@@ -3,41 +3,63 @@ import Testing
private struct CatalogItem: Identifiable { let id: Int }
-@Test func catalogStartsSmallAndExpandsOnlyWhenRequested() {
+@Test func catalogPagesDeduplicate() {
var page = MarketplacePage<CatalogItem>()
- page.replace(with: (0..<60).map { CatalogItem(id: $0) })
- #expect(page.visible.count == 12)
- #expect(page.hasHiddenItems)
- page.revealMore()
- #expect(page.visible.map(\.id) == Array(0..<24))
- #expect(page.items.count == 60)
+ page.replace(with: (0..<12).map { CatalogItem(id: $0) })
+ page.append((10..<15).map { CatalogItem(id: $0) })
+ #expect(page.items.map(\.id) == Array(0..<15))
+ page.replace(with: [])
+ #expect(page.isEmpty)
}
-@Test func catalogEndsAtItsActualCount() {
- var page = MarketplacePage<CatalogItem>()
- page.replace(with: (0..<15).map { CatalogItem(id: $0) })
- page.revealMore()
- #expect(page.visible.count == 15)
- #expect(!page.hasHiddenItems)
+@Test func catalogPagingClampsAndFetchesOnlyPastLoadedRows() {
+ let items = Array(0..<47)
+ #expect(CatalogPaging.pageCount(47) == 5)
+ #expect(CatalogPaging.pageCount(19) == 2)
+ #expect(CatalogPaging.pageCount(0) == 1)
+ #expect(CatalogPaging.pageCount(72, hasMore: true) == 9)
+ #expect(Array(CatalogPaging.slice(items, page: 0)) == Array(0..<10))
+ #expect(Array(CatalogPaging.slice(items, page: 4)) == Array(40..<47))
+ #expect(Array(CatalogPaging.slice(items, page: 9)).isEmpty)
+ #expect(CatalogPaging.clamp(page: 9, count: 47) == 4)
+ #expect(CatalogPaging.clamp(page: 9, count: 72, hasMore: true) == 8)
+ #expect(CatalogPaging.clamp(page: -1, count: 20) == 0)
+ #expect(CatalogPaging.clamp(page: 4, count: 0) == 0)
+ #expect(CatalogPaging.canForward(count: 10, page: 0, hasMore: true))
+ #expect(CatalogPaging.needsFetch(count: 10, page: 1))
+ #expect(CatalogPaging.canForward(count: 20, page: 0, hasMore: false))
+ #expect(!CatalogPaging.needsFetch(count: 20, page: 1))
+ #expect(!CatalogPaging.canForward(count: 8, page: 0, hasMore: false))
+ #expect(!CatalogPaging.needsFetch(count: 60, page: 5))
+ #expect(CatalogPaging.needsFetch(count: 60, page: 6))
+ #expect(CatalogPaging.needsFetch(count: 72, page: 7))
+ #expect(!CatalogPaging.needsFetch(count: 80, page: 7))
+ #expect(!CatalogPaging.needsFetch(count: 0, page: 0))
+ #expect(!CatalogPaging.needsFetch(count: 3, page: 0))
+ #expect(CatalogPaging.needsFetch(count: 0, page: 1))
}
-@Test func laterCatalogPagesStayBoundedAndRemoveDuplicates() {
- var page = MarketplacePage<CatalogItem>()
- page.replace(with: (0..<12).map { CatalogItem(id: $0) })
- page.append((10..<60).map { CatalogItem(id: $0) })
- #expect(page.visible.count == 12)
- page.revealMore()
- #expect(page.visible.map(\.id) == Array(0..<24))
- #expect(page.items.count == 60)
-}
+private struct Offline: Error {}
-@Test func newCatalogSearchResetsTheVisibleBatch() {
- var page = MarketplacePage<CatalogItem>()
- page.replace(with: (0..<60).map { CatalogItem(id: $0) })
- page.revealMore()
- page.replace(with: (100..<130).map { CatalogItem(id: $0) })
- #expect(page.visible.map(\.id) == Array(100..<112))
- page.replace(with: [])
- #expect(page.isEmpty)
- #expect(!page.hasHiddenItems)
+@Test @MainActor func aConnectorPageFillsUntilFullAndFallsBackWhenItCannot() async {
+ let catalog = ConnectorCatalog<CatalogItem>()
+ var asked: [String?] = []
+ let rows = { (range: Range<Int>) in range.map { CatalogItem(id: $0) } }
+ await catalog.load(search: "") { _, cursor in asked.append(cursor); return (rows(0..<15), "a") }
+ #expect(catalog.items.items.count == 15 && catalog.page == 0 && !catalog.loading)
+
+ // Page 2 needs rows 10-19: two registry pages fill it.
+ catalog.show(1, size: 10)
+ await catalog.fill(size: 10) { _, cursor in
+ asked.append(cursor)
+ return cursor == "a" ? (rows(15..<18), "b") : (rows(18..<25), "c")
+ }
+ #expect(asked == [nil, "a", "b"])
+ #expect(catalog.page == 1 && catalog.items.items.count == 25 && catalog.cursor == "c" && !catalog.loadingMore)
+
+ // The page past the loaded rows fails: back to the last page with rows.
+ catalog.show(3, size: 10)
+ #expect(catalog.page == 3)
+ await catalog.fill(size: 10) { _, _ in throw Offline() }
+ #expect(catalog.page == 2 && catalog.error != nil)
}
diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.md
index ed826ebb..b5b98c5b 100644
--- a/apps/ios/WhatsNew.md
+++ b/apps/ios/WhatsNew.md
@@ -11,10 +11,16 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o
### zh-Hant
- Bot 傳來的圖片會直接顯示在聊天裡,點一下可以放大看,不用先下載。
- 電腦上的 Codync 版本太舊時,更新提示多了「Update now」按鈕,直接從手機叫那台電腦更新。
+- 擴充套件一次顯示一個分類:智慧體、聯結器或技能,每個列表都分頁。點列表兩側的圓形按鈕或左右滑動就能翻頁,下方可選每頁 6、10、20 或 50 筆,並顯示目前在第幾頁。
+- 聯結器翻到還沒載入的頁面時,會從 MCP Registry 接著載入。
+- 「憑證」移到上方電腦名稱旁;「自定義聯結器」和「自己的技能」放在各自分類的列表上方。
### en-US
- Images a bot sends now show right in the chat; tap one to see it full size, no download needed.
- When a computer's Codync is too old for this app, Update now on the notice updates that computer from your phone.
+- Extensions shows one section at a time: Agents, Connectors or Skills, each in pages. Tap the round buttons beside the list or swipe left or right to turn the page; under it, pick 6, 10, 20 or 50 per page and see which page you're on.
+- Connectors keep loading from the MCP Registry as you page past what's loaded.
+- Credentials sits beside the computer's name at the top, and Custom connector and Your own skill sit above their lists.
## 2.26.1
diff --git a/docs/features/marketplace.md b/docs/features/marketplace.md
index ac843b68..518e7af5 100644
--- a/docs/features/marketplace.md
+++ b/docs/features/marketplace.md
@@ -2,7 +2,7 @@
The Extensions screen configures capabilities installed on one computer. Account membership does not install the same capability on every computer, so each computer has its own Extensions, opened from that computer and never switched inside: with several computers, from the Extensions button on its heading in the bot list (desktop and iPhone); on the desktop with one computer, from the sidebar footer; on the iPhone, also from its row in Computers & settings.
-The desktop and iPhone installed count is labeled **Connectors & skills**, and opens a library with that same title. It includes connected apps (stored as connectors), but excludes agents; agents show their own installation status in the Agents section. The terminal already separates these categories and does not show a combined installed count.
+Under the open section, one line says where that section comes from: agents from the ACP registry, connectors from the MCP Registry, skills from Anthropic, and that they install on this computer. Credentials sits on the title row, beside the computer name, on the iPhone, Android and desktop, so the list can use the rest of the screen. The terminal has no Credentials control on this sheet. The desktop and iPhone installed count is labeled **Connectors & skills**, and opens a library with that same title. It includes connected apps (stored as connectors), but excludes agents; agents show their own installation status in the Agents section. The terminal already separates these categories and does not show a combined installed count.
| Capability | Implementation | Behavior |
| --- | --- | --- |
@@ -26,7 +26,7 @@ has only Agents, Connectors and Skills tabs.
Install runs the CLI's own native installer where it has one, on Windows too (Claude Code, Codex, Grok, Qwen, Droid, Qoder, Cursor…, `Install` in `backends.rs`); CLIs published only on npm (Gemini, Cline, Auggie, Kilo…) install with `codync-host npm install -g <package>`, npm on the computer's own Node or else on Codync's. A CLI with its own ACP mode then runs as installed, without Node.js. Refreshing the agents re-reads the PATH a fresh login would get (the login shell's; on Windows the user's and machine's PATH from the registry), so a CLI found by an installer that just ran shows up without restarting the host. Many agents' ACP adapters run through `npx` (Claude, Codex, Gemini, Qwen…). On a computer without Node.js, the agent list marks each of them `node: "missing"` (only then is the field there; `added` once Codync's copy is in place) and they aren't available; Extensions shows one *Add Node.js* notice above the agents, each such agent reads *Needs Node.js*, and its setup sheet gets a Node.js step between Install and Sign in. Adding it (`agentSetup {step: "node"}`, a setup terminal running `codync-host node`) downloads the official Node.js of a pinned version (`VERSION` and SHA-256s in `node.rs`) once into `~/.codync/node/<version>`; npm installs with it go to `~/.codync/node/global`. Both folders come last on the agent search path, so the computer's own Node and CLIs always win, and nothing outside `~/.codync` changes. Linux builds of Node need glibc: on musl distros (Alpine) install Node.js yourself.
-The Connectors shelf opens with a short featured list, then pages through the whole MCP Registry (`marketConnectors {search, cursor}` → `{items, nextCursor}`, 60 metadata records per API page; the UI initially shows 12 and reveals another 12 only when *Load more connectors* is pressed). Searching resets the visible batch; late responses from an older search are ignored. Scrolling never triggers another catalog fetch. Listed: stdio npm/PyPI/OCI/NuGet packages (the registry's runtime and package arguments become inputs) and streamable-HTTP or SSE remotes (URL `{variables}` become inputs). Not listed: MCPB bundles and packages that serve HTTP locally; add those as a custom connector.
+Extensions shows one section at a time — Agents, Connectors, or Skills — and each list is paged. A phone starts at 6 rows, three rows of the two agent tiles, so a page has no leftover card; the desktop and the terminal start at 10. The size menu is 6, 10, 20 or 50. The bar shows the count, the page size, previous and next, and the current page over the page count (`1 / 5`). On a phone, previous and next are dark filled circles on either side of the list, and swiping the list left or right also turns the page, in Agents, Connectors and Skills alike. The agent tiles are a bit smaller there, to leave room for the buttons. The bar under the list keeps the page size and the page number. A short last page still takes the height of a full page, so the bar does not move. The Connectors section opens with the first registry page, then, when a later page isn't full, fetches registry pages until it is or the cursor ends (`marketConnectors {search, cursor}` → `{items, nextCursor}`, 60 metadata records per API page). That page shows at once, with placeholder rows while it has none; if a fetch fails, the list goes back to the last page with rows. While a cursor remains, the page count includes one more page, so a list that continues never reads `1 / 1`. A registry that answers with the cursor it was asked for ends the list there: the host drops that cursor rather than serve the same page forever. Searching starts again at the first page; late responses from an older search are ignored. The terminal pages the same lists: Page Up and Page Down move, and Alt+S changes the page size. Its rows that aren't catalog entries (Add Node.js, installed connectors and skills, Custom connector) start every page and aren't counted. Listed: stdio npm/PyPI/OCI/NuGet packages (the registry's runtime and package arguments become inputs) and streamable-HTTP or SSE remotes (URL `{variables}` become inputs). Not listed: MCPB bundles and packages that serve HTTP locally; add those as a custom connector.
Registry package installs use pinned package references: npm, PyPI and NuGet require the package’s own version; OCI uses the tag or SHA-256 digest already in its image identifier, even when the separate package version is omitted. Untagged images, `latest` tags without a digest, and invalid references are rejected; a server-level version does not pin the executable package.
@@ -40,7 +40,7 @@ Skills follow the same rule: an installed or hand-written skill is turned on for
Bots write skills too, with the `chat` server's `save_skill {name, description, instructions, id?}` (`host/src/chat/skills.rs`): when the user asks, or when the bot has worked out how to do a task the user will likely want again, never because a file, web page, tool result or another bot says so. A new skill is saved like a hand-written one (`source: "custom"`, so it shows in Extensions and bot settings and can be removed there) plus the bot that wrote it (`writtenBy`), and is turned on for that bot only: new bots don't start with it either, and the user turns it on for other bots in their settings, so a bot (a prompt-injected one included) can't put instructions in front of other bots. With `id`, the bot rewrites a skill it saved itself; skills the user wrote, other bots' and downloaded ones can't be changed. Files beside `SKILL.md` stay, so a bot can keep a skill's scripts or references in its folder. Each save posts a notice in the bot's chat ("Saved the skill …", "Updated the skill …"), and a bot that has the skill on hears a new name or description in its next profile update. Limits: name 64 characters, description 1,024, instructions 64K characters; the name and description become one line each in the front matter. Saves of the installed list go one at a time. A download takes its folder before it starts, and a written skill never takes an existing folder (it gets `-2`), so a save during a download can't land in the download's folder; adding a catalog skill whose id a written one already has is refused until that one is removed.
-Clicking a skill (an Extensions row, an installed skill, or the info button beside a skill's switch in bot settings; in the terminal, ↵ on a skill, or `i` on the bot form's Skills field) opens its details: the description and its instructions, with Add while it isn't installed. `skillDetails {id}` (installed) or `{source}` (catalog) returns `{markdown}`: the `SKILL.md` body without its front matter, at most 256 KB. The host looks names up in the installed list or the catalog cache, never as a path; the catalog fetch already downloads every `SKILL.md`, so the bodies stay in that cache. An Extensions row opens its details, or does what its button does when it has none (connectors open their install sheet).
+Clicking a skill (an Extensions row, an installed skill, or the info button beside a skill's switch in bot settings; in the terminal, ↵ on a skill, or `i` on the bot form's Skills field) opens its details: the description and its instructions, with Add while it isn't installed. `skillDetails {id}` (installed) or `{source}` (catalog) returns `{markdown}`: the `SKILL.md` body without its front matter, at most 256 KB. The host looks names up in the installed list or the catalog cache, never as a path; the catalog fetch already downloads every `SKILL.md`, so the bodies stay in that cache. The folder list comes from the public tree page (`github.com/anthropics/skills/tree/main/skills`) and each `SKILL.md` from raw.githubusercontent.com. The GitHub contents API is not used for that: its unauthenticated quota is 60 requests an hour for the whole computer, and a spent quota answers 403. An Extensions row opens its details, or does what its button does when it has none (connectors open their install sheet).
Registry-backed package connectors follow their upstream release. The host checks the Registry periodically after credentials are unlocked and checks again immediately before a package process starts. If a newer pinned npm, PyPI, OCI or NuGet reference is available, only that package/image argument is replaced; the running process is not interrupted, and the new version applies on its next launch. Network failures, missing packages and attempted downgrades leave the installed reference unchanged. Custom command connectors are never updated automatically.
diff --git a/host/src/market/registry.rs b/host/src/market/registry.rs
index f34cd35f..856b30b0 100644
--- a/host/src/market/registry.rs
+++ b/host/src/market/registry.rs
@@ -94,17 +94,62 @@ pub(super) fn listing(server: &Value, installed: &[Connector]) -> Option<Value>
/// Browse the whole MCP Registry a page at a time (featured connectors lead the first
/// page of the unfiltered list), or search it. `nextCursor` fetches the following page.
pub async fn browse_connectors(store: &crate::store::Store, search: &str, cursor: &str) -> Result<Value> {
+ let deadline = Instant::now() + BROWSE_BUDGET;
let installed = connectors(store)?;
let search = search.trim();
let (servers, next) =
if search.is_empty() && cursor.is_empty() { first_page().await? } else { later_page(search, cursor).await? };
+ let (items, next) = past_empty_pages((listings(&servers, &installed), next), cursor, deadline, |after| {
+ let installed = &installed;
+ async move {
+ let (servers, next) = later_page(search, &after).await?;
+ Ok((listings(&servers, installed), next))
+ }
+ })
+ .await?;
+ Ok(json!({"items": items, "nextCursor": next}))
+}
+
+/// The servers on a page that Codync can install, each once.
+fn listings(servers: &[Value], installed: &[Connector]) -> Vec<Value> {
let mut seen = std::collections::HashSet::new();
- let items: Vec<Value> = servers
+ servers
.iter()
.filter(|s| seen.insert(s["name"].as_str().unwrap_or_default().to_owned()))
- .filter_map(|s| listing(s, &installed))
- .collect();
- Ok(json!({"items": items, "nextCursor": next}))
+ .filter_map(|s| listing(s, installed))
+ .collect()
+}
+
+/// Registry pages read past one with nothing Codync can install. An empty answer reads as the end
+/// of the list in every app, so a few more pages are tried while the cursor goes on.
+const EMPTY_PAGE_SKIPS: usize = 3;
+/// The apps wait 60 s for `marketConnectors`, and one registry page can take 45 s: skipping stops
+/// in time to answer, handing back the cursor it didn't get to.
+const BROWSE_BUDGET: Duration = Duration::from_secs(40);
+
+async fn past_empty_pages<F, Fut>(page: Page, cursor: &str, deadline: Instant, mut fetch: F) -> Result<Page>
+where
+ F: FnMut(String) -> Fut,
+ Fut: Future<Output = Result<Page>>,
+{
+ let (mut items, mut next) = page;
+ let mut asked = cursor.to_owned();
+ for _ in 0..EMPTY_PAGE_SKIPS {
+ if !items.is_empty() {
+ break;
+ }
+ let Some(after) = following(&asked, next.take()) else { break };
+ let Some(left) = deadline.checked_duration_since(Instant::now()) else { return Ok((items, Some(after))) };
+ let Ok(page) = tokio::time::timeout(left, fetch(after.clone())).await else { return Ok((items, Some(after))) };
+ (items, next) = page?;
+ asked = after;
+ }
+ Ok((items, following(&asked, next)))
+}
+
+/// The registry handing back the cursor it was asked with would page the same rows forever: that ends the list.
+fn following(cursor: &str, next: Option<String>) -> Option<String> {
+ next.filter(|n| n != cursor)
}
type Page = (Vec<Value>, Option<String>);
@@ -180,4 +225,37 @@ mod tests {
assert_eq!(title_from_name("com.vercel/vercel-mcp"), "Vercel");
assert_eq!(title_from_name("io.github.microsoft/playwright-mcp"), "Playwright");
}
+
+ #[tokio::test]
+ async fn an_empty_page_with_a_cursor_reads_on() {
+ let pages = |cursor: String| async move {
+ Ok(match cursor.as_str() {
+ "b" => (vec![], Some("c".to_owned())),
+ "c" => (vec![json!({"name": "found"})], Some("d".to_owned())),
+ _ => (vec![], Some(cursor)),
+ })
+ };
+ let later = Instant::now() + Duration::from_secs(60);
+ let (items, next) = past_empty_pages((vec![], Some("b".into())), "", later, pages).await.unwrap();
+ assert_eq!(items.len(), 1);
+ assert_eq!(next.as_deref(), Some("d"));
+ let (items, next) = past_empty_pages((vec![], Some("x".into())), "", later, pages).await.unwrap();
+ assert!(items.is_empty() && next.is_none(), "a cursor the registry repeats still ends the list");
+ let (items, next) = past_empty_pages((vec![json!({})], Some("b".into())), "", later, pages).await.unwrap();
+ assert_eq!((items.len(), next.as_deref()), (1, Some("b")), "a page with rows is kept as it is");
+ let slow = |_: String| async {
+ tokio::time::sleep(Duration::from_secs(5)).await;
+ Ok((vec![json!({})], None))
+ };
+ let soon = Instant::now() + Duration::from_millis(20);
+ let (items, next) = past_empty_pages((vec![], Some("b".into())), "", soon, slow).await.unwrap();
+ assert!(items.is_empty() && next.as_deref() == Some("b"), "past the deadline the cursor comes back unread");
+ }
+
+ #[test]
+ fn a_repeated_cursor_ends_the_list() {
+ assert_eq!(following("a", Some("a".into())), None);
+ assert_eq!(following("a", Some("b".into())), Some("b".into()));
+ assert_eq!(following("", None), None);
+ }
}
diff --git a/host/src/market/skills.rs b/host/src/market/skills.rs
index a98c4212..a2448b39 100644
--- a/host/src/market/skills.rs
+++ b/host/src/market/skills.rs
@@ -1,6 +1,6 @@
//! Skills: the anthropics/skills catalog, downloads, hand-written skills and the profile's skills block.
-use super::{SKILLS_REPO, Skill, TIMEOUT, UA, get_json, save, skills, skills_dir, slug, unique_id};
+use super::{SKILLS_REPO, Skill, TIMEOUT, UA, save, skills, skills_dir, slug, unique_id};
use crate::LockExt;
use anyhow::{Context, Result, anyhow, bail};
use serde_json::{Value, json};
@@ -56,6 +56,70 @@ fn body(md: &str) -> &str {
""
}
+/// One entry on a public GitHub tree page.
+struct TreeEntry {
+ name: String,
+ path: String,
+ dir: bool,
+}
+
+/// Folders and files on the public tree page. The contents API shares a 60-request hour
+/// with every other unauthenticated call from this computer, and answers 403 once that
+/// quota is spent, so the catalog never uses it.
+async fn tree_entries(repo_path: &str) -> Result<Vec<TreeEntry>> {
+ let url = format!("https://github.com/{SKILLS_REPO}/tree/main/{repo_path}");
+ // github.com sometimes answers the first handshake with a non-TLS record. One try
+ // then surfaces as the red error under the list, so the catalog tries again.
+ let mut last = anyhow!("listing skills on GitHub");
+ for attempt in 0u64..3 {
+ match fetch_tree_page(&url).await {
+ Ok(html) => return parse_tree_entries(&html).context("listing skills on GitHub"),
+ Err(e) if attempt < 2 => {
+ last = e;
+ tokio::time::sleep(Duration::from_millis(300 * (attempt + 1))).await;
+ }
+ Err(e) => last = e,
+ }
+ }
+ Err(last)
+}
+
+async fn fetch_tree_page(url: &str) -> Result<String> {
+ let response = crate::http()
+ .get(url)
+ .header("user-agent", UA)
+ .timeout(TIMEOUT)
+ .send()
+ .await
+ .context("listing skills on GitHub")?;
+ response.text().await.context("listing skills on GitHub")
+}
+
+/// `items` in the tree page's embedded catalog: name, path, and whether it is a directory.
+fn parse_tree_entries(html: &str) -> Result<Vec<TreeEntry>> {
+ const MARK: &str = r#"data-target="react-app.embeddedData">"#;
+ let start = html.find(MARK).context("the skill list page has no catalog")?;
+ let json = &html[start + MARK.len()..];
+ let end = json.find("</script>").context("the skill list page has no catalog")?;
+ let value: Value = serde_json::from_str(&json[..end]).context("the skill list page")?;
+ let items = value["payload"]["codeViewTreeRoute"]["tree"]["items"]
+ .as_array()
+ .context("the skill list page has no catalog")?
+ .clone();
+ Ok(items
+ .into_iter()
+ .filter_map(|item| {
+ let name = item["name"].as_str()?.to_owned();
+ let path = item["path"].as_str()?.to_owned();
+ // Names become paths: plain file names only.
+ if name.is_empty() || name.starts_with('.') || name.contains(['/', '\\']) {
+ return None;
+ }
+ Some(TreeEntry { name, path, dir: item["contentType"] == "directory" })
+ })
+ .collect())
+}
+
/// Skills published in anthropics/skills, with their `SKILL.md` body (cached for an hour).
async fn catalog() -> Result<Value> {
let cached = SKILL_CATALOG
@@ -66,16 +130,8 @@ async fn catalog() -> Result<Value> {
let catalog = if let Some(v) = cached {
v
} else {
- let dirs = get_json(&format!("https://api.github.com/repos/{SKILLS_REPO}/contents/skills"))
- .await
- .context("listing skills on GitHub")?;
- let names: Vec<String> = dirs
- .as_array()
- .into_iter()
- .flatten()
- .filter(|d| d["type"] == "dir")
- .filter_map(|d| d["name"].as_str().map(str::to_owned))
- .collect();
+ let names: Vec<String> =
+ tree_entries("skills").await?.into_iter().filter(|entry| entry.dir).map(|entry| entry.name).collect();
let fetches = names.iter().map(|dir| async move {
let url = format!("https://raw.githubusercontent.com/{SKILLS_REPO}/main/skills/{dir}/SKILL.md");
let md = crate::http().get(&url).header("user-agent", UA).timeout(TIMEOUT).send().await.ok()?.text().await.ok()?;
@@ -134,27 +190,42 @@ pub async fn skill_details(store: &crate::store::Store, b: &Value) -> Result<Val
Ok(json!({"markdown": markdown}))
}
+const MAX_SKILL_FILE: usize = 1_000_000;
+
+/// One skill file, or nothing when it is over [`MAX_SKILL_FILE`]. Reading stops at the limit.
+async fn skill_file(url: &str) -> Result<Option<Vec<u8>>> {
+ let mut response = crate::http().get(url).header("user-agent", UA).timeout(TIMEOUT).send().await?;
+ if response.content_length().is_some_and(|size| size > MAX_SKILL_FILE as u64) {
+ return Ok(None);
+ }
+ let mut bytes = Vec::new();
+ while let Some(chunk) = response.chunk().await? {
+ if bytes.len().saturating_add(chunk.len()) > MAX_SKILL_FILE {
+ return Ok(None);
+ }
+ bytes.extend_from_slice(&chunk);
+ }
+ Ok(Some(bytes))
+}
+
/// Downloads a skill folder from anthropics/skills (files up to 1 MB, two levels deep).
async fn download_dir(repo_path: &str, dest: &std::path::Path, depth: u8) -> Result<()> {
- let listing = get_json(&format!("https://api.github.com/repos/{SKILLS_REPO}/contents/{repo_path}")).await?;
+ let listing = tree_entries(repo_path).await?;
tokio::fs::create_dir_all(dest).await?;
- for item in listing.as_array().into_iter().flatten() {
- let name = item["name"].as_str().unwrap_or_default();
- // Names become paths: plain file names only.
- if name.is_empty() || name.starts_with('.') || name.contains(['/', '\\']) {
+ for entry in listing {
+ // The page's path has to be the folder we asked for, not somewhere else.
+ if entry.path != format!("{repo_path}/{}", entry.name) {
continue;
}
- match item["type"].as_str() {
- Some("file") if item["size"].as_u64().unwrap_or(0) <= 1_000_000 => {
- let Some(url) = item["download_url"].as_str() else { continue };
- let bytes =
- crate::http().get(url).header("user-agent", UA).timeout(TIMEOUT).send().await?.bytes().await?;
- tokio::fs::write(dest.join(name), &bytes).await?;
+ if entry.dir {
+ if depth > 0 {
+ Box::pin(download_dir(&entry.path, &dest.join(&entry.name), depth - 1)).await?;
}
- Some("dir") if depth > 0 => {
- Box::pin(download_dir(&format!("{repo_path}/{name}"), &dest.join(name), depth - 1)).await?;
- }
- _ => {}
+ continue;
+ }
+ let url = format!("https://raw.githubusercontent.com/{SKILLS_REPO}/main/{}", entry.path);
+ if let Some(bytes) = skill_file(&url).await? {
+ tokio::fs::write(dest.join(entry.name), &bytes).await?;
}
}
Ok(())
@@ -355,6 +426,61 @@ pub fn skills_brief(store: &crate::store::Store, enabled: &[String]) -> Option<S
mod tests {
use super::*;
+ /// Serves `/declared` (a Content-Length over the limit), `/streamed` (chunks past the limit, no
+ /// length) and anything else as a five-byte body.
+ async fn file_server() -> String {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.expect("a local port");
+ let base = format!("http://{}", listener.local_addr().expect("a bound address"));
+ tokio::spawn(async move {
+ while let Ok((mut socket, _)) = listener.accept().await {
+ tokio::spawn(async move {
+ let mut request = [0u8; 1024];
+ let read = socket.read(&mut request).await.unwrap_or(0);
+ let head = String::from_utf8_lossy(&request[..read]).into_owned();
+ // The client hangs up as soon as it sees too much; later writes may fail.
+ if head.starts_with("GET /declared") {
+ let _ = socket.write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 2000000\r\n\r\n").await;
+ } else if head.starts_with("GET /streamed") {
+ let _ = socket.write_all(b"HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n").await;
+ let chunk = vec![b'x'; 65_536];
+ for _ in 0..17 {
+ let _ = socket.write_all(b"10000\r\n").await;
+ let _ = socket.write_all(&chunk).await;
+ let _ = socket.write_all(b"\r\n").await;
+ }
+ let _ = socket.write_all(b"0\r\n\r\n").await;
+ } else {
+ let _ = socket.write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 5\r\n\r\nhello").await;
+ }
+ });
+ }
+ });
+ base
+ }
+
+ #[tokio::test]
+ async fn a_skill_file_over_the_limit_is_skipped_without_reading_it_all() {
+ let base = file_server().await;
+ assert_eq!(skill_file(&format!("{base}/declared")).await.expect("declared"), None);
+ assert_eq!(skill_file(&format!("{base}/streamed")).await.expect("streamed"), None);
+ assert_eq!(skill_file(&format!("{base}/small")).await.expect("small").as_deref(), Some(&b"hello"[..]));
+ }
+
+ #[test]
+ fn the_public_tree_page_lists_skill_folders() {
+ let html = r#"<script type="application/json" data-target="react-app.embeddedData">{"payload":{"codeViewTreeRoute":{"tree":{"items":[
+ {"name":"pdf","path":"skills/pdf","contentType":"directory"},
+ {"name":"SKILL.md","path":"skills/pdf/SKILL.md","contentType":"file"},
+ {"name":".claude-plugin","path":"skills/.claude-plugin","contentType":"directory"},
+ {"name":"../etc","path":"skills/../etc","contentType":"file"}
+ ]}}}}</script>"#;
+ let entries = parse_tree_entries(html).expect("tree page");
+ assert_eq!(entries.len(), 2);
+ assert!(entries[0].dir && entries[0].name == "pdf" && entries[0].path == "skills/pdf");
+ assert!(!entries[1].dir && entries[1].name == "SKILL.md");
+ }
+
#[test]
fn front_matter_is_read() {
let md = "---\nname: pdf\ndescription: \"Work with PDFs\"\n---\n# PDF";
diff --git a/host/src/tui/manage/market.rs b/host/src/tui/manage/market.rs
index b44834bc..72d55a2e 100644
--- a/host/src/tui/manage/market.rs
+++ b/host/src/tui/manage/market.rs
@@ -1,11 +1,11 @@
//! The marketplace: agents, connectors and skills.
-use crossterm::event::{KeyCode, KeyEvent};
+use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde_json::{Value, json};
use super::super::app::{After, App, Confirm, ConfirmAct, Editor, Overlay, fuzzy};
use super::super::l10n::tr;
-use super::{Fields, Input, Market, Reply, Row, Submit, TABS, Tab, ctrl, s};
+use super::{Fields, Input, Market, MarketPage, Reply, Row, Submit, TABS, Tab, ctrl, s};
impl App {
pub fn open_market(&mut self) {
@@ -24,54 +24,107 @@ impl App {
loading: true,
cursor: 0,
error: None,
+ pages: [0; 3],
+ page_size: PAGE_SIZE,
})));
}
- /// The marketplace's rows on its current tab, filtered by the query.
- pub fn market_rows<'a>(&'a self, m: &'a Market) -> Vec<Row<'a>> {
+ /// The open tab's page: the rows every page starts with, then this page's catalog rows.
+ pub fn market_page<'a>(&'a self, m: &'a Market) -> MarketPage<'a> {
+ let (mut rows, catalog) = self.market_catalog(m, m.tab);
+ let more = m.tab == Tab::Connectors && m.next.is_some();
+ let count = catalog.len();
+ let page = clamp_page(m.pages[m.tab.index()], count, m.page_size, more);
+ rows.extend(catalog.into_iter().skip(page * m.page_size).take(m.page_size));
+ MarketPage { rows, count, page, pages: page_count(count, m.page_size, more) }
+ }
+
+ fn connector_count(&self, m: &Market) -> usize {
+ self.market_catalog(m, Tab::Connectors).1.len()
+ }
+
+ fn load_more_connectors(&self, m: &mut Market) {
+ if m.loading || m.next.is_none() {
+ return;
+ }
+ m.loading = true;
+ let search = m.searched.clone().unwrap_or_default();
+ self.sheet("marketConnectors", json!({"search": search, "cursor": m.next}), Reply::Registry { more: true });
+ }
+
+ /// After a connector page turns or a registry page arrives, keep fetching until that page is full or the cursor ends.
+ /// The Connectors page fills even while another tab is open.
+ pub(super) fn continue_market_page(&self, m: &mut Market) {
+ let count = self.connector_count(m);
+ let i = Tab::Connectors.index();
+ if m.next.is_some() && needs_fetch(count, m.pages[i], m.page_size) {
+ self.load_more_connectors(m);
+ } else {
+ m.pages[i] = clamp_page(m.pages[i], count, m.page_size, m.next.is_some());
+ }
+ }
+
+ /// A registry page that didn't come: back to the last Connectors page with rows.
+ pub(super) fn settle_connector_page(&self, m: &mut Market) {
+ let i = Tab::Connectors.index();
+ m.pages[i] = clamp_page(m.pages[i], self.connector_count(m), m.page_size, false);
+ }
+
+ fn turn_market_page(&self, m: &mut Market, forward: bool) {
+ let MarketPage { page, pages, .. } = self.market_page(m);
+ let next = if forward { page + 1 } else { page.saturating_sub(1) };
+ if next == page || next >= pages {
+ return;
+ }
+ m.pages[m.tab.index()] = next;
+ m.cursor = 0;
+ if m.tab == Tab::Connectors {
+ self.continue_market_page(m);
+ }
+ }
+
+ /// A tab's rows, split into the ones every page starts with and the catalog rows that are paged.
+ fn market_catalog<'a>(&'a self, m: &'a Market, tab: Tab) -> (Vec<Row<'a>>, Vec<Row<'a>>) {
let q = m.query.text.trim();
let hit = |v: &Value, keys: &[&str]| {
let fields: Vec<&str> = keys.iter().map(|k| v[*k].as_str().unwrap_or_default()).collect();
fuzzy(q, &fields)
};
- match m.tab {
+ match tab {
Tab::Agents => {
let agents = self
.backends
.iter()
.filter(|b| b["available"] == true || b["installed"] == true || b["curated"] == true);
let node = agents.clone().any(|b| b["node"] == "missing").then_some(Row::Node);
- node.into_iter().chain(agents.filter(|b| hit(b, &["name", "id"])).map(Row::Agent)).collect()
+ (node.into_iter().collect(), agents.filter(|b| hit(b, &["name", "id"])).map(Row::Agent).collect())
}
Tab::Connectors => {
let installed: Vec<&str> = self.plugins.0.iter().filter_map(|c| c["registryName"].as_str()).collect();
- let mut rows: Vec<Row> =
+ let mut pinned: Vec<Row> =
self.plugins.0.iter().filter(|c| hit(c, &["name", "description"])).map(Row::Installed).collect();
- rows.push(Row::Custom);
- rows.extend(
- m.registry
- .iter()
- .filter(|c| !installed.contains(&c["name"].as_str().unwrap_or_default()))
- .map(Row::Registry),
- );
- if m.next.is_some() {
- rows.push(Row::More);
- }
- rows
+ pinned.push(Row::Custom);
+ let registry = m
+ .registry
+ .iter()
+ .filter(|c| !installed.contains(&c["name"].as_str().unwrap_or_default()))
+ .map(Row::Registry)
+ .collect();
+ (pinned, registry)
}
Tab::Skills => {
let installed: Vec<String> = self.plugins.1.iter().map(|v| s(v, "id").to_lowercase()).collect();
- let mut rows: Vec<Row> =
+ let own =
self.plugins.1.iter().filter(|v| hit(v, &["name", "description"])).map(Row::OwnSkill).collect();
- rows.extend(
- m.skills
- .iter()
- .flatten()
- .filter(|v| !installed.contains(&s(v, "source").to_lowercase()))
- .filter(|v| hit(v, &["name", "description"]))
- .map(Row::Skill),
- );
- rows
+ let catalog = m
+ .skills
+ .iter()
+ .flatten()
+ .filter(|v| !installed.contains(&s(v, "source").to_lowercase()))
+ .filter(|v| hit(v, &["name", "description"]))
+ .map(Row::Skill)
+ .collect();
+ (own, catalog)
}
}
}
@@ -82,7 +135,8 @@ impl App {
}
pub(in crate::tui) fn market_key(&mut self, mut m: Box<Market>, k: KeyEvent) -> Option<Overlay> {
- let n = self.market_rows(&m).len();
+ let n = self.market_page(&m).rows.len();
+ let alt = k.modifiers.contains(KeyModifiers::ALT);
match k.code {
KeyCode::Esc => return None,
KeyCode::Tab | KeyCode::BackTab => {
@@ -93,6 +147,14 @@ impl App {
}
KeyCode::Down => m.cursor = (m.cursor + 1).min(n.saturating_sub(1)),
KeyCode::Up => m.cursor = m.cursor.saturating_sub(1),
+ KeyCode::PageDown => self.turn_market_page(&mut m, true),
+ KeyCode::PageUp => self.turn_market_page(&mut m, false),
+ KeyCode::Char('s') if alt => {
+ let i = PAGE_SIZES.iter().position(|s| *s == m.page_size).unwrap_or(0);
+ m.page_size = PAGE_SIZES[(i + 1) % PAGE_SIZES.len()];
+ m.pages = [0; 3];
+ m.cursor = 0;
+ }
KeyCode::Char('n' | 'j') if ctrl(k) => m.cursor = (m.cursor + 1).min(n.saturating_sub(1)),
KeyCode::Char('p') if ctrl(k) => m.cursor = m.cursor.saturating_sub(1),
KeyCode::Char('r') if ctrl(k) => {
@@ -106,12 +168,13 @@ impl App {
m.cursor = 0;
m.registry.clear();
m.next = None;
+ m.pages[Tab::Connectors.index()] = 0;
self.sheet("marketConnectors", json!({"search": search}), Reply::Registry { more: false });
m.searched = Some(search);
}
KeyCode::Enter => return self.market_enter(m),
KeyCode::Char('x') if ctrl(k) => {
- let (id, name, skill) = match self.market_rows(&m).get(m.cursor) {
+ let (id, name, skill) = match self.market_page(&m).rows.get(m.cursor) {
Some(Row::Installed(c)) => (s(c, "id"), s(c, "name"), false),
Some(Row::OwnSkill(v)) => (s(v, "id"), s(v, "name"), true),
_ => return Some(Overlay::Market(m)),
@@ -135,30 +198,29 @@ impl App {
_ => {
if m.query.key(k) {
m.cursor = 0;
+ m.pages[m.tab.index()] = 0;
}
}
}
Some(Overlay::Market(m))
}
- fn market_enter(&mut self, mut m: Box<Market>) -> Option<Overlay> {
+ fn market_enter(&mut self, m: Box<Market>) -> Option<Overlay> {
enum Act {
Node,
Agent(String),
SignIn(String),
Custom,
Install(Value),
- More,
Skill(Value, bool),
None,
}
- let act = match self.market_rows(&m).get(m.cursor) {
+ let act = match self.market_page(&m).rows.get(m.cursor) {
Some(Row::Node) => Act::Node,
Some(Row::Agent(b)) => Act::Agent(s(b, "id")),
Some(Row::Installed(c)) if c["auth"] == "signedOut" => Act::SignIn(s(c, "id")),
Some(Row::Custom) => Act::Custom,
Some(Row::Registry(c)) => Act::Install((*c).clone()),
- Some(Row::More) => Act::More,
Some(Row::Skill(v)) => Act::Skill((*v).clone(), true),
Some(Row::OwnSkill(v)) => Act::Skill((*v).clone(), false),
_ => Act::None,
@@ -239,15 +301,6 @@ impl App {
return None;
}
}
- Act::More => {
- m.loading = true;
- let search = m.searched.clone().unwrap_or_default();
- self.sheet(
- "marketConnectors",
- json!({"search": search, "cursor": m.next}),
- Reply::Registry { more: true },
- );
- }
Act::Skill(v, catalog) => {
self.overlays.push(Overlay::Market(m));
self.open_skill(&v, catalog);
@@ -259,6 +312,41 @@ impl App {
}
}
+const PAGE_SIZE: usize = 10;
+const PAGE_SIZES: [usize; 4] = [6, 10, 20, 50];
+
+impl MarketPage<'_> {
+ /// The pager, in the same order as the other clients: count, size, previous, current / total, next.
+ pub fn pager_line(&self, page_size: usize) -> String {
+ format!(
+ "{} {} {} {} {} / {} {}",
+ tr("{count} total").replace("{count}", &self.count.to_string()),
+ tr("Per page"),
+ tr(&format!("{page_size} / page")),
+ tr("Previous page"),
+ self.page + 1,
+ self.pages,
+ tr("Next page"),
+ )
+ }
+}
+
+/// Catalog rows split into pages. While the registry still has a cursor, one more page is offered.
+fn page_count(count: usize, size: usize, has_more: bool) -> usize {
+ let loaded = if count == 0 { 1 } else { count.div_ceil(size) };
+ if has_more { loaded + 1 } else { loaded }
+}
+
+fn clamp_page(page: usize, count: usize, size: usize, has_more: bool) -> usize {
+ page.min(page_count(count, size, has_more).saturating_sub(1))
+}
+
+/// A later page that isn't full yet: the registry has to be asked. The first page is whatever the first answer held.
+fn needs_fetch(count: usize, page: usize, size: usize) -> bool {
+ let start = page * size;
+ start > 0 && start + size > count
+}
+
/// The inputs of a connector's chosen way to run, defaults filled in.
pub(super) fn connector_inputs(f: &mut Fields) {
let Submit::Connector(item) = &f.submit else { return };
@@ -282,3 +370,82 @@ pub(super) fn connector_inputs(f: &mut Fields) {
.collect();
f.cursor = f.cursor.min(f.offset() + f.inputs.len().saturating_sub(1));
}
+
+#[cfg(test)]
+mod tests {
+ use super::super::super::app::{App, Overlay};
+ use super::super::super::net::Client;
+ use super::super::{Market, Reply, Tab};
+ use super::{clamp_page, needs_fetch, page_count};
+ use serde_json::{Value, json};
+
+ #[test]
+ fn forty_seven_agents_are_five_pages() {
+ assert_eq!(page_count(47, 10, false), 5);
+ assert_eq!(page_count(19, 10, false), 2);
+ assert_eq!(page_count(0, 10, false), 1);
+ assert_eq!(page_count(72, 10, true), 9);
+ assert_eq!(clamp_page(9, 47, 10, false), 4);
+ assert_eq!(clamp_page(9, 72, 10, true), 8);
+ assert!(!needs_fetch(60, 5, 10));
+ assert!(needs_fetch(60, 6, 10));
+ assert!(needs_fetch(72, 7, 10));
+ assert!(!needs_fetch(80, 7, 10));
+ assert!(!needs_fetch(0, 0, 10));
+ assert!(!needs_fetch(3, 0, 10));
+ assert!(needs_fetch(0, 1, 10));
+ }
+
+ fn registry(range: std::ops::Range<usize>, next: Option<&str>) -> Value {
+ let items: Vec<Value> = range.map(|i| json!({"name": format!("c{i}"), "title": format!("C{i}")})).collect();
+ json!({"items": items, "nextCursor": next})
+ }
+
+ fn market(app: &App) -> &Market {
+ match app.overlays.last() {
+ Some(Overlay::Market(m)) => m,
+ _ => panic!("the marketplace is open"),
+ }
+ }
+
+ fn turn_to(app: &mut App, page: usize) {
+ let Some(Overlay::Market(mut m)) = app.overlays.pop() else { panic!("the marketplace is open") };
+ m.tab = Tab::Connectors;
+ m.pages[Tab::Connectors.index()] = page;
+ app.continue_market_page(&mut m);
+ app.overlays.push(Overlay::Market(m));
+ }
+
+ #[tokio::test]
+ async fn a_connector_page_fills_from_the_registry_and_falls_back_when_it_cannot() {
+ let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
+ let mut app = App::new(Client::new("http://127.0.0.1:1", None), tx, String::new());
+ app.open_market();
+ app.on_sheet_reply(Reply::Registry { more: false }, Ok(registry(0..15, Some("a"))));
+ turn_to(&mut app, 0);
+ let page = app.market_page(market(&app));
+ assert_eq!((page.count, page.pages), (15, 3));
+
+ // Page 2 starts at row 10 but only 15 are loaded: the next registry page is asked for.
+ turn_to(&mut app, 1);
+ assert!(market(&app).loading);
+ app.on_sheet_reply(Reply::Registry { more: true }, Ok(registry(15..18, Some("b"))));
+ assert!(market(&app).loading, "18 rows still leave page 2 short");
+ app.on_sheet_reply(Reply::Registry { more: true }, Ok(registry(18..25, Some("c"))));
+ assert!(!market(&app).loading);
+ assert_eq!(market(&app).pages[Tab::Connectors.index()], 1);
+
+ // The page past the loaded rows fails: back to the last page with rows.
+ turn_to(&mut app, 3);
+ assert!(market(&app).loading);
+ app.on_sheet_reply(Reply::Registry { more: true }, Err("offline".into()));
+ let m = market(&app);
+ assert!(!m.loading);
+ assert_eq!(m.error.as_deref(), Some("offline"));
+ assert_eq!(m.pages[Tab::Connectors.index()], 2);
+
+ // The cursor ends: no page past the rows.
+ app.on_sheet_reply(Reply::Registry { more: true }, Ok(registry(25..26, None)));
+ assert_eq!(app.market_page(market(&app)).pages, 3);
+ }
+}
diff --git a/host/src/tui/manage/mod.rs b/host/src/tui/manage/mod.rs
index 2f8d7cac..cd7d86b6 100644
--- a/host/src/tui/manage/mod.rs
+++ b/host/src/tui/manage/mod.rs
@@ -130,6 +130,16 @@ pub enum Tab {
pub const TABS: [(Tab, &str); 3] = [(Tab::Agents, "Agents"), (Tab::Connectors, "Connectors"), (Tab::Skills, "Skills")];
+impl Tab {
+ pub(in crate::tui) fn index(self) -> usize {
+ match self {
+ Self::Agents => 0,
+ Self::Connectors => 1,
+ Self::Skills => 2,
+ }
+ }
+}
+
pub struct Market {
pub tab: Tab,
pub query: Editor,
@@ -141,6 +151,9 @@ pub struct Market {
pub loading: bool,
pub cursor: usize,
pub error: Option<String>,
+ /// Page index on Agents, Connectors, then Skills.
+ pub pages: [usize; 3],
+ pub page_size: usize,
}
pub enum Row<'a> {
@@ -150,11 +163,20 @@ pub enum Row<'a> {
Installed(&'a Value),
Custom,
Registry(&'a Value),
- More,
OwnSkill(&'a Value),
Skill(&'a Value),
}
+/// One page of the open marketplace tab.
+pub struct MarketPage<'a> {
+ /// The rows every page starts with (Add Node.js, what's installed, Custom connector), then this page's catalog rows.
+ pub rows: Vec<Row<'a>>,
+ /// Catalog rows on the tab, without the ones every page starts with.
+ pub count: usize,
+ pub page: usize,
+ pub pages: usize,
+}
+
pub struct AgentSetup {
pub backend: String,
pub auth: Option<Value>,
diff --git a/host/src/tui/manage/replies.rs b/host/src/tui/manage/replies.rs
index ba81caf6..e0ff332f 100644
--- a/host/src/tui/manage/replies.rs
+++ b/host/src/tui/manage/replies.rs
@@ -3,7 +3,7 @@
use serde_json::{Value, json};
use super::super::app::{After, AgentModel, App, Entry, Overlay, Toggle};
-use super::{MemoryMode, Reply, Shell, open_browser, s};
+use super::{Market, MemoryMode, Reply, Shell, open_browser, s};
impl App {
pub(in crate::tui) fn on_sheet_reply(&mut self, r: Reply, res: Result<Value, String>) {
@@ -107,22 +107,19 @@ impl App {
"Copied a curl command (the cloud is off: this computer only)"
});
}
- Reply::Registry { more } => {
- if let Some(Overlay::Market(m)) =
- self.overlays.iter_mut().rev().find(|o| matches!(o, Overlay::Market(_)))
- {
- let items = v["items"].as_array().cloned().unwrap_or_default();
- if more {
- m.registry.extend(items);
- } else {
- m.registry = items;
- }
- m.next = v["nextCursor"].as_str().filter(|c| !c.is_empty()).map(str::to_owned);
- m.searched.get_or_insert_with(String::new);
- m.loading = false;
- m.error = None;
+ Reply::Registry { more } => self.with_market(|app, m| {
+ let items = v["items"].as_array().cloned().unwrap_or_default();
+ if more {
+ m.registry.extend(items);
+ } else {
+ m.registry = items;
}
- }
+ m.next = v["nextCursor"].as_str().filter(|c| !c.is_empty()).map(str::to_owned);
+ m.searched.get_or_insert_with(String::new);
+ m.loading = false;
+ m.error = None;
+ app.continue_market_page(m);
+ }),
Reply::Skills => {
if let Some(Overlay::Market(m)) =
self.overlays.iter_mut().rev().find(|o| matches!(o, Overlay::Market(_)))
@@ -223,15 +220,20 @@ impl App {
}
}
}
- Reply::Registry { .. } | Reply::Skills => {
- if let Some(Overlay::Market(m)) =
- self.overlays.iter_mut().rev().find(|o| matches!(o, Overlay::Market(_)))
- {
+ Reply::Registry { more } => {
+ let more = *more;
+ self.with_market(|app, m| {
m.loading = false;
- m.skills.get_or_insert_with(Vec::new);
m.error = Some(e);
- }
+ if more {
+ app.settle_connector_page(m);
+ }
+ });
}
+ Reply::Skills => self.with_market(|_, m| {
+ m.skills.get_or_insert_with(Vec::new);
+ m.error = Some(e);
+ }),
Reply::CallEntries(call) => {
// The call's line folds again with nothing kept, so the next `o` asks again.
let lines: Vec<String> = self
@@ -293,6 +295,19 @@ impl App {
}
}
+ /// Runs `f` on the open marketplace, with the rest of the app readable beside it.
+ fn with_market(&mut self, f: impl FnOnce(&Self, &mut Market)) {
+ let Some(i) = self.overlays.iter().rposition(|o| matches!(o, Overlay::Market(_))) else { return };
+ let overlay = match self.overlays.remove(i) {
+ Overlay::Market(mut m) => {
+ f(self, &mut m);
+ Overlay::Market(m)
+ }
+ other => other,
+ };
+ self.overlays.insert(i, overlay);
+ }
+
/// Loads what every open sheet shows again, after a change.
pub(in crate::tui) fn refresh_sheets(&mut self) {
let mut calls: Vec<(&'static str, Value, After)> = vec![];
diff --git a/host/src/tui/sheets.rs b/host/src/tui/sheets.rs
index c924532d..38ccaa60 100644
--- a/host/src/tui/sheets.rs
+++ b/host/src/tui/sheets.rs
@@ -11,18 +11,18 @@ use crate::tui::l10n::tr;
use serde_json::Value;
mod library_view;
+mod market_view;
mod memory_view;
pub use library_view::draw as library;
+pub use market_view::draw as market;
pub use memory_view::draw as memory;
use super::app::{App, Editor};
-use super::manage::{
- AgentSetup, Fields, Market, Page, RoutineField, RoutineForm, RoutineList, Row, SetupRow, Submit, TABS, Tab,
-};
+use super::manage::{AgentSetup, Fields, Page, RoutineField, RoutineForm, RoutineList, SetupRow, Submit};
use super::md::truncate;
use super::view::{
- centered, chain_line, composer_lines, field_line, frame_box, hline, input_line, put, restyle, rput, set_cursor,
- theme, u, using_line, when_future,
+ centered, chain_line, composer_lines, frame_box, hline, input_line, put, restyle, rput, set_cursor, theme, u,
+ using_line, when_future,
};
fn s<'a>(v: &'a Value, k: &str) -> &'a str {
@@ -244,94 +244,6 @@ fn multiline(buf: &mut Buffer, r: Rect, e: &Editor, placeholder: &str, active: b
}
}
-pub fn market(buf: &mut Buffer, area: Rect, app: &App, m: &Market) {
- let t = theme();
- let r = centered(area, 96, 30);
- let title = format!("{} · {}", tr("Extensions"), app.host);
- let inner = frame_box(buf, r, t.text, t.panel, Some((&title, t.text)));
- let mut x = inner.x;
- for (tab, label) in TABS {
- let style = if tab == m.tab { t.btn_primary } else { t.secondary.patch(t.btn) };
- let tab_label = tr(label);
- x = put(buf, x, inner.y, 20, &format!(" {tab_label} "), style) + 1;
- }
- let search = Rect::new(x + 2, inner.y, inner.right().saturating_sub(x + 2), 1);
- let placeholder = match m.tab {
- Tab::Connectors => tr("search the MCP registry"),
- _ => tr("filter"),
- };
- field_line(buf, search, inner.y, &m.query, &placeholder, true);
- let rows = app.market_rows(m);
- let list_h = usize::from(inner.height.saturating_sub(5));
- let mut y = inner.y + 2;
- if App::market_stale(m) {
- put(buf, inner.x, y, inner.width, &tr("↵ searches the registry"), t.secondary.patch(t.panel));
- y += 1;
- }
- for (i, item) in rows.iter().enumerate().skip(window(m.cursor, list_h)).take(list_h) {
- let base = row(buf, inner, y, i == m.cursor);
- let (mark, name, detail, right): (&str, String, String, String) = match item {
- Row::Node => (
- "+",
- tr("Add Node.js").into_owned(),
- tr("Some agents need it to run. Codync adds a copy just for them.").into_owned(),
- String::new(),
- ),
- Row::Agent(b) => {
- let status = match (b["installed"] == true, b["signedIn"].as_bool()) {
- (false, _) if b["curated"] == true => "not installed",
- _ if b["node"] == "missing" => "needs Node.js",
- (_, Some(true)) => "signed in",
- (true, Some(false)) => "not signed in",
- (true, None) => "installed",
- (false, _) => "sets up on first use",
- };
- let status = tr(status);
- let mark = if b["signedIn"] == true || b["installed"] == true { "✓" } else { "↓" };
- (mark, s(b, "name").into(), s(b, "description").into(), status.into_owned())
- }
- Row::Installed(c) => {
- let right = match s(c, "auth") {
- "signedOut" => tr("↵ sign in"),
- _ if c["kind"] == "composio" => std::borrow::Cow::Borrowed("Composio"),
- _ => tr("installed"),
- };
- let detail = c["command"].as_str().or(c["url"].as_str()).unwrap_or(s(c, "description"));
- ("✓", s(c, "name").into(), detail.into(), right.into_owned())
- }
- Row::Custom => (
- "+",
- tr("Custom connector").into_owned(),
- tr("Paste any MCP server's config").into_owned(),
- String::new(),
- ),
- Row::Registry(c) => ("↓", s(c, "title").into(), s(c, "description").into(), String::new()),
- Row::More => ("…", tr("Load more connectors").into_owned(), String::new(), String::new()),
- Row::OwnSkill(v) => ("✓", s(v, "name").into(), s(v, "description").into(), tr("installed").into_owned()),
- Row::Skill(v) => ("↓", s(v, "name").into(), s(v, "description").into(), String::new()),
- };
- let ok = mark == "✓";
- put(buf, inner.x, y, 2, mark, if ok { t.green } else { t.dim }.patch(base));
- let nx = put(buf, inner.x + 2, y, 26, &truncate(&name, 26), t.bold.patch(base)) + 2;
- let rx = rput(buf, inner.right(), y, &right, t.dim.patch(base));
- let room = usize::from(rx.saturating_sub(nx + 1));
- put(buf, nx, y, u(room), &truncate(&detail.replace('\n', " "), room), t.secondary.patch(base));
- y += 1;
- }
- if rows.is_empty() {
- let msg = if m.loading { tr("Loading…") } else { tr("Nothing matches") };
- put(buf, inner.x, y, inner.width, &msg, t.dim.patch(t.panel));
- }
- let keys = match m.tab {
- Tab::Agents => tr("tab switch · ↵ install / sign in · ^r refresh · esc close"),
- Tab::Connectors => tr("tab switch · ↵ add / sign in · ^x remove · ^r refresh · esc"),
- Tab::Skills => tr("tab switch · ↵ details · ^x remove · esc close"),
- };
- let loading = m.loading && m.tab == Tab::Connectors && !rows.is_empty();
- let registry = tr("Loading the registry…");
- footer(buf, inner, m.error.as_deref().or(loading.then_some(registry.as_ref())), &keys);
-}
-
pub fn agent(buf: &mut Buffer, area: Rect, app: &App, a: &AgentSetup) {
let t = theme();
let b = app.backends.iter().find(|b| b["id"] == a.backend.as_str());
diff --git a/host/src/tui/sheets/market_view.rs b/host/src/tui/sheets/market_view.rs
new file mode 100644
index 00000000..ee62d96f
--- /dev/null
+++ b/host/src/tui/sheets/market_view.rs
@@ -0,0 +1,112 @@
+//! The Extensions sheet: three tabs, a search field, and a pinned pager.
+
+use super::{App, Buffer, Rect, centered, footer, frame_box, put, row, rput, s, theme, truncate, u, window};
+use crate::tui::l10n::tr;
+use crate::tui::manage::{Market, Row, TABS, Tab};
+use crate::tui::view::field_line;
+
+pub fn draw(buf: &mut Buffer, area: Rect, app: &App, m: &Market) {
+ let t = theme();
+ let r = centered(area, 96, 30);
+ let title = format!("{} · {}", tr("Extensions"), app.host);
+ let inner = frame_box(buf, r, t.text, t.panel, Some((&title, t.text)));
+ let mut x = inner.x;
+ for (tab, label) in TABS {
+ let style = if tab == m.tab { t.btn_primary } else { t.secondary.patch(t.btn) };
+ let tab_label = tr(label);
+ x = put(buf, x, inner.y, 20, &format!(" {tab_label} "), style) + 1;
+ }
+ let search = Rect::new(x + 2, inner.y, inner.right().saturating_sub(x + 2), 1);
+ let placeholder = match m.tab {
+ Tab::Connectors => tr("search the MCP registry"),
+ _ => tr("filter"),
+ };
+ field_line(buf, search, inner.y, &m.query, &placeholder, true);
+ let source = match m.tab {
+ Tab::Agents => tr("Agents come from the ACP registry and install on {name}."),
+ Tab::Connectors => tr("Connectors come from the official MCP Registry and install on {name}."),
+ Tab::Skills => tr("Skills come from Anthropic and install on {name}."),
+ };
+ let source = source.replace("{name}", &app.host);
+ put(buf, inner.x, inner.y + 1, inner.width, &truncate(&source, usize::from(inner.width)), t.dim.patch(t.panel));
+ let page = app.market_page(m);
+ let rows = &page.rows;
+ // Tabs, source line, then the list; under it the pager, the error and the keys.
+ let list_h = usize::from(inner.height.saturating_sub(6));
+ let mut y = inner.y + 2;
+ if App::market_stale(m) {
+ put(buf, inner.x, y, inner.width, &tr("↵ searches the registry"), t.secondary.patch(t.panel));
+ y += 1;
+ }
+ for (i, item) in rows.iter().enumerate().skip(window(m.cursor, list_h)).take(list_h) {
+ let base = row(buf, inner, y, i == m.cursor);
+ let (mark, name, detail, right): (&str, String, String, String) = match item {
+ Row::Node => (
+ "+",
+ tr("Add Node.js").into_owned(),
+ tr("Some agents need it to run. Codync adds a copy just for them.").into_owned(),
+ String::new(),
+ ),
+ Row::Agent(b) => {
+ let status = match (b["installed"] == true, b["signedIn"].as_bool()) {
+ (false, _) if b["curated"] == true => "not installed",
+ _ if b["node"] == "missing" => "needs Node.js",
+ (_, Some(true)) => "signed in",
+ (true, Some(false)) => "not signed in",
+ (true, None) => "installed",
+ (false, _) => "sets up on first use",
+ };
+ let status = tr(status);
+ let mark = if b["signedIn"] == true || b["installed"] == true { "✓" } else { "↓" };
+ (mark, s(b, "name").into(), s(b, "description").into(), status.into_owned())
+ }
+ Row::Installed(c) => {
+ let right = match s(c, "auth") {
+ "signedOut" => tr("↵ sign in"),
+ _ if c["kind"] == "composio" => std::borrow::Cow::Borrowed("Composio"),
+ _ => tr("installed"),
+ };
+ let detail = c["command"].as_str().or(c["url"].as_str()).unwrap_or(s(c, "description"));
+ ("✓", s(c, "name").into(), detail.into(), right.into_owned())
+ }
+ Row::Custom => (
+ "+",
+ tr("Custom connector").into_owned(),
+ tr("Paste any MCP server's config").into_owned(),
+ String::new(),
+ ),
+ Row::Registry(c) => ("↓", s(c, "title").into(), s(c, "description").into(), String::new()),
+ Row::OwnSkill(v) => ("✓", s(v, "name").into(), s(v, "description").into(), tr("installed").into_owned()),
+ Row::Skill(v) => ("↓", s(v, "name").into(), s(v, "description").into(), String::new()),
+ };
+ let ok = mark == "✓";
+ put(buf, inner.x, y, 2, mark, if ok { t.green } else { t.dim }.patch(base));
+ let nx = put(buf, inner.x + 2, y, 26, &truncate(&name, 26), t.bold.patch(base)) + 2;
+ let rx = rput(buf, inner.right(), y, &right, t.dim.patch(base));
+ let room = usize::from(rx.saturating_sub(nx + 1));
+ put(buf, nx, y, u(room), &truncate(&detail.replace('\n', " "), room), t.secondary.patch(base));
+ y += 1;
+ }
+ if rows.is_empty() {
+ let msg = if m.loading { tr("Loading…") } else { tr("Nothing matches") };
+ put(buf, inner.x, y, inner.width, &msg, t.dim.patch(t.panel));
+ }
+ let keys = match m.tab {
+ Tab::Agents => tr("pgup/pgdn · alt-s · tab · ↵ install / sign in · ^r · esc"),
+ Tab::Connectors => tr("pgup/pgdn · alt-s · tab · ↵ add / sign in · ^x remove · esc"),
+ Tab::Skills => tr("pgup/pgdn · alt-s · tab · ↵ details · ^x remove · esc"),
+ };
+ let loading = m.loading && m.tab == Tab::Connectors && !rows.is_empty();
+ let registry = tr("Loading the registry…");
+ // Like the apps, a list still loading for the first time has no pager yet.
+ let settled = match m.tab {
+ Tab::Agents => true,
+ Tab::Connectors => !(m.loading && m.registry.is_empty()),
+ Tab::Skills => m.skills.is_some(),
+ };
+ if settled {
+ let line = page.pager_line(m.page_size);
+ put(buf, inner.x, inner.bottom().saturating_sub(3), inner.width, &line, t.secondary.patch(t.panel));
+ }
+ footer(buf, inner, m.error.as_deref().or(loading.then_some(registry.as_ref())), &keys);
+}
diff --git a/web/content/docs/agents.mdx b/web/content/docs/agents.mdx
index 72c05f03..719bc7ac 100644
--- a/web/content/docs/agents.mdx
+++ b/web/content/docs/agents.mdx
@@ -65,7 +65,7 @@ Agents are set up from **Extensions**, which belongs to one computer:
- **iPhone:** tap the account button at the top left of the Bots tab, open **Computers & settings**, and tap the **Extensions** button on the computer.
- **Terminal UI:** press `A`.
-The **Agents** section shows each agent's status: **Installed**, **Not installed**, **Not signed in**, **Needs Node.js**, or **Sets up on first use** (registry agents). Select an agent to open its setup sheet. It walks through up to three steps.
+The **Agents** section shows each agent's status: **Installed**, **Not installed**, **Not signed in**, **Needs Node.js**, or **Sets up on first use** (registry agents). The list is paged: **Previous page** and **Next page** move through it (on a phone, you can also swipe the list left or right), and the bar shows the current page over the page count, such as **1 / 5**. Select an agent to open its setup sheet. It walks through up to three steps.
### Install
diff --git a/web/content/docs/connectors-and-skills.mdx b/web/content/docs/connectors-and-skills.mdx
index c59af10b..14731f1c 100644
--- a/web/content/docs/connectors-and-skills.mdx
+++ b/web/content/docs/connectors-and-skills.mdx
@@ -8,11 +8,11 @@ You add both in **Extensions**. They install on the computer, so every bot on th
- **iPhone:** tap the account button at the top left of the Bots tab, open **Computers & settings**, and tap the Extensions button on the computer's row. With several computers, the Extensions button on a computer's heading in the Bots tab opens it too.
- **Terminal UI:** press `A`, or pick "Extensions: agents, connectors, skills…" from the action list. Tab switches between Agents, Connectors and Skills.
-The header names the computer everything installs on. Once you've added something, a count under it ("3 installed", **Connectors & skills**) opens your library, where you can sign in to a connector or remove one.
+The header names the computer everything installs on. **Credentials** sits on that same row, beside the name. Under the open section, one line says where those items come from and that they install on this computer. Once you've added something, a count under it ("3 installed", **Connectors & skills**) opens your library, where you can sign in to a connector or remove one.
## Add a connector from the registry
-The **Connectors** section starts with a short featured list, then pages through the official MCP Registry. Search by service name, or press **Load more connectors** to see more.
+Extensions opens on one section at a time: **Agents**, **Connectors**, or **Skills**. On the desktop, and on a wide phone, those are a side list; on a narrow phone they are tabs along the top. Each list is paged. A phone starts at 6 at a time, three rows of the two agent tiles; elsewhere it starts at 10. The bar under the list shows how many there are, how many fit on a page (6, 10, 20 or 50), **Previous page**, the current page over the page count (such as **1 / 8**), and **Next page**. On a phone, previous and next are the dark round buttons on either side of the list, and you can also swipe the list left or right to turn the page. The bar underneath is the page size and the page number (`1 / 8` is the page, not how many fit). A short last page keeps the height of a full page, so the bar stays put. The **Connectors** list starts with the first page from the official MCP Registry; opening a page that isn't full yet fetches more. Search by service name. In the terminal, Tab still switches sections, Page Up and Page Down turn the page, and Alt+S changes the page size.
1. Pick a connector. The **Add connector** sheet opens.
2. If it can run more than one way, choose under **Runs**: hosted by the service, or on your computer as a package.
@@ -40,7 +40,7 @@ Some services don't offer this kind of sign-in (GitHub is one). For those, add t
## Add a custom connector
-Under **Make your own**, choose **Custom connector**, then one of:
+In the **Connectors** section, choose **Custom connector**, above the registry list, then one of:
- **Command:** a command line that starts an MCP server. It runs on the computer in the bot's project folder, and quotes work like in a shell. Put keys under **Environment**, one `KEY=value` per line.
- **URL:** a hosted MCP server. Add headers under **Headers**, one `Name: value` per line, or leave them empty if the service has you sign in.
@@ -89,7 +89,7 @@ The bot picks up the change on its next turn, in the same conversation.
A skill is a folder with a `SKILL.md` file: a name, a line saying when to use it, and the instructions. A bot with a skill on is told its name, its description and where its instructions are, so it can read them when a task calls for it.
- **Install one:** the **Skills** section of Extensions lists Anthropic's published skills. Press **Add**. Click any skill to read its instructions first.
-- **Write your own:** under **Make your own**, choose **Your own skill** and fill in **Name**, **When to use it** and **Instructions**.
+- **Write your own:** in the **Skills** section, choose **Your own skill**, above the list, and fill in **Name**, **When to use it** and **Instructions**.
- **Let a bot write one:** ask a bot to save how it did something as a skill. A bot may also save one on its own after working out a task you're likely to want again. The chat shows "Saved the skill …" or "Updated the skill …". A skill a bot writes is on for that bot only; turn it on for other bots in their settings. A bot can change only the skills it wrote, and you can remove any skill from your library.
### Use a skill with a slash command