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: keep a bot's dev servers running apart from its agent

leepokaib34bb62743be
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsEvent.kt b/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsEvent.kt
index e787d481..56df5399 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsEvent.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AnalyticsEvent.kt
@@ -86,6 +86,10 @@ internal sealed class AnalyticsEvent(val name: String) {
data class ScreenViewed(val screen: AnalyticsScreen) : AnalyticsEvent("screen_viewed") {
override val properties get() = mapOf("screen" to screen.json)
}
+ /** A dev server opened, or its address copied; the host reports what it does itself. */
+ data class DevServerAction(val use: DevServerUse) : AnalyticsEvent("dev_server_action") {
+ override val properties get() = mapOf("action" to use.json)
+ }
}
/** One of a property's catalog values, as sent. */
@@ -176,6 +180,8 @@ internal enum class OutboundLink(override val wire: String) : CatalogValue {
InstallLink("install_link"),
}
+internal enum class DevServerUse(override val wire: String) : CatalogValue { Open("open"), Copy("copy") }
+
internal enum class VoiceEngineKind(override val wire: String) : CatalogValue {
OnDevice("on_device"), OpenAI("openai"), Gemini("gemini"),
/** A provider's speech-to-text and text-to-speech (`CloudSpeechEngine`), not its realtime model. */
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.kt
index 430a8337..6f412cfe 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreBots.kt
@@ -115,6 +115,12 @@ fun AppStore.deleteBot(bot: Bot, onDeleted: () -> Unit) = action("delete:" + bot
onDeleted()
}
+/** A refusal shows; the bot's next update shows the rest. */
+fun AppStore.devServerAction(action: DevServerAction, botId: String, id: String) = command(action.method, body("botId" to botId, "id" to id), action.method + ":" + id)
+
+suspend fun AppStore.devServerLogs(botId: String, id: String): String =
+ hostQuery("devServerLogs", body("botId" to botId, "id" to id)).jsonObject["text"]?.jsonPrimitive?.content.orEmpty()
+
/** A host call for the screens that keep their own state (memory): waits for the connection first. */
internal suspend fun AppStore.hostCall(method: String, body: JsonObject, timeoutMillis: Long = 240_000): JsonElement = ready().call(method, body, timeoutMillis)
internal suspend fun AppStore.hostFiles(): HostFiles = HostFiles(ready())
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/BotDetailsView.kt b/apps/android/app/src/main/kotlin/com/codync/android/BotDetailsView.kt
index 8e4a9428..e1e70df5 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/BotDetailsView.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/BotDetailsView.kt
@@ -82,6 +82,7 @@ internal data class DetailsRequest(val tab: DetailsTab = DetailsTab.Details, val
Box(Modifier.fillMaxWidth().padding(top = 20.dp)) {
when (tab) {
DetailsTab.Details -> Column(verticalArrangement = Arrangement.spacedBy(28.dp)) {
+ if (bot.devServers.isNotEmpty()) DevServersSection(bot, store)
BotSettingsForm(state, store, draft, { draft = it }, FormPart.Often, error = saveError)
state.screen?.let { ComputerCard(it, draft.computer, online) { on -> draft = draft.copy(computer = on) } }
RoutinesView(bot, state, store, routineId)
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt b/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt
index 5aaf479d..c3347138 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt
@@ -161,7 +161,7 @@ import com.kyant.shapes.Capsule
BotAvatar(bot, state.bots, 22.dp)
Text(bot.name, style = Type.system(13f).semibold, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
- ConnectionSubtitle(state)
+ ConnectionSubtitle(state, devServerSummary(bot.devServers))
}
}
// The corner is the computer: it pulses while this bot is operating it (watch, then take over).
@@ -184,9 +184,17 @@ import com.kyant.shapes.Capsule
}
}
-/** The link to the computer: route icon (or a spinner) and a word. */
-@Composable private fun ConnectionSubtitle(state: AppState) {
- Row(Modifier.clearAndSetSemantics { contentDescription = "${state.hostName}, ${connectionDescription(state)}" }, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+/** The link to the computer: route icon (or a spinner) and a word, then what the bot keeps running. */
+@Composable private fun ConnectionSubtitle(state: AppState, summary: DevServerSummary) {
+ val servers = when (summary) {
+ DevServerSummary.None -> null
+ DevServerSummary.Starting -> tr("Starting")
+ DevServerSummary.Failed -> tr("Failed to start")
+ is DevServerSummary.Running -> summary.text
+ }
+ val style = Type.system(10f).medium
+ val description = listOfNotNull(state.hostName, connectionDescription(state), servers).joinToString(", ")
+ Row(Modifier.clearAndSetSemantics { contentDescription = description }, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
Box(Modifier.width(12.dp), contentAlignment = Alignment.Center) {
when (val link = state.connection) {
LinkState.Connecting -> Spinner(8.dp)
@@ -194,7 +202,14 @@ import com.kyant.shapes.Capsule
else -> Symbol("wifi.slash", size = 11.dp, tint = Palette.secondary)
}
}
- Text(connectionLabel(state), style = Type.system(10f).medium, color = Palette.secondary, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) {
+ Text(connectionLabel(state), style = style, color = Palette.secondary, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ if (servers != null) {
+ Text("·", style = style, color = Palette.secondary)
+ if (summary == DevServerSummary.Starting) Spinner(8.dp)
+ Text(servers, style = style.monospacedDigit, color = if (summary == DevServerSummary.Failed) Palette.danger else Palette.secondary, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ }
+ }
}
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/DevServersSection.kt b/apps/android/app/src/main/kotlin/com/codync/android/DevServersSection.kt
new file mode 100644
index 00000000..980d1558
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/DevServersSection.kt
@@ -0,0 +1,149 @@
+package com.codync.android
+
+import android.content.ClipData
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.offset
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.requiredSize
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.text.selection.SelectionContainer
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.ClipEntry
+import androidx.compose.ui.platform.LocalClipboard
+import androidx.compose.ui.platform.LocalUriHandler
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.Bot
+import com.codync.android.core.DevServer
+import com.codync.android.core.DevServerAction
+import com.codync.android.core.DevServerMenuRow
+import com.codync.android.core.DevServerStatus
+import com.codync.android.core.DevServerTap
+import com.codync.android.design.*
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.launch
+
+/** What a bot keeps running (iOS `DevServersSection`): a row is its name and ports, tapping it opens it, the rest is behind `⋯`. */
+@Composable internal fun DevServersSection(bot: Bot, store: AppStore) {
+ var logs by remember { mutableStateOf<DevServer?>(null) }
+ CardSection("Dev servers") {
+ for (server in bot.devServers) row { DevServerRow(bot.id, server, store) { logs = server } }
+ }
+ CodyncSheet(logs, { logs = null }) { DevServerLogsView(bot.id, it, store) }
+}
+
+@Composable private fun DevServerRow(botId: String, server: DevServer, store: AppStore, showLogs: () -> Unit) {
+ val uri = LocalUriHandler.current
+ val clipboard = LocalClipboard.current
+ val scope = rememberCoroutineScope()
+ fun open(address: String) {
+ try {
+ uri.openUri(address)
+ Analytics.capture(AnalyticsEvent.DevServerAction(DevServerUse.Open))
+ } catch (failure: Exception) { store.showError(failure) }
+ }
+ fun copy(address: String) {
+ Analytics.capture(AnalyticsEvent.DevServerAction(DevServerUse.Copy))
+ scope.launch { clipboard.setClipEntry(ClipEntry(ClipData.newPlainText("Address", address))) }
+ }
+ val tap: (() -> Unit)? = when (val action = server.tap) {
+ is DevServerTap.Open -> { { open(action.address) } }
+ DevServerTap.Logs -> showLogs
+ null -> null
+ }
+ Row(Modifier.fillMaxWidth().heightIn(min = 32.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Row(Modifier.weight(1f).then(if (tap != null) Modifier.plainButton(action = tap) else Modifier),
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(server.name, Modifier.weight(1f), style = Type.body, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ if (server.status == DevServerStatus.Starting) Spinner(11.dp)
+ Text(tr(server.rowValue), style = Type.body.monospacedDigit, maxLines = 1,
+ color = if (server.status == DevServerStatus.Failed) Palette.danger else Palette.secondary)
+ }
+ // A 44 dp target in a row of the card's height, its glyph near the card's edge.
+ DropdownMenu({ menuItems(botId, server, store, showLogs, ::open, ::copy) }, Modifier.offset(x = 12.dp).height(32.dp).requiredSize(44.dp),
+ label = tr("More actions for {name}").replace("{name}", server.name)) {
+ Symbol("ellipsis", size = 18.dp, tint = Palette.secondary)
+ }
+ }
+}
+
+private fun menuItems(botId: String, server: DevServer, store: AppStore, showLogs: () -> Unit, open: (String) -> Unit, copy: (String) -> Unit): List<MenuItem> {
+ fun act(action: DevServerAction) = store.devServerAction(action, botId, server.id)
+ return server.menuRows.mapIndexed { index, row ->
+ when (row) {
+ DevServerMenuRow.OnlyOnComputer -> MenuItem("Only reachable on the computer", enabled = false)
+ DevServerMenuRow.StartedByShell -> MenuItem("Started through the bot's shell: it stops with the bot", enabled = false)
+ DevServerMenuRow.Open -> MenuItem("Open", icon = "arrow.up.right") { server.remoteAddress?.let(open) }
+ DevServerMenuRow.CopyAddress -> MenuItem("Copy address", icon = "doc.on.doc") { server.remoteAddress?.let(copy) }
+ DevServerMenuRow.Logs -> MenuItem("Logs", icon = "doc.text", action = showLogs)
+ DevServerMenuRow.Restart -> MenuItem("Restart", icon = "arrow.clockwise") { act(DevServerAction.Restart) }
+ DevServerMenuRow.Start -> MenuItem("Start", icon = "arrow.clockwise") { act(DevServerAction.Restart) }
+ DevServerMenuRow.Stop -> MenuItem("Stop", icon = "stop.fill", destructive = true, divider = index > 0) { act(DevServerAction.Stop) }
+ DevServerMenuRow.Remove -> MenuItem("Remove", icon = "trash", destructive = true, divider = index > 0) { act(DevServerAction.Remove) }
+ }
+ }
+}
+
+private sealed interface DevServerOutput {
+ data object Loading : DevServerOutput
+ data class Shown(val text: String) : DevServerOutput
+ data class Failed(val message: String) : DevServerOutput
+}
+
+/** A server's recent output, to read. */
+@Composable private fun DevServerLogsView(botId: String, server: DevServer, store: AppStore) {
+ // Moves to read the logs again.
+ var reads by remember(server.id) { mutableIntStateOf(0) }
+ var output by remember(server.id) { mutableStateOf<DevServerOutput>(DevServerOutput.Loading) }
+ LaunchedEffect(server.id, reads) {
+ output = try { DevServerOutput.Shown(store.devServerLogs(botId, server.id)) }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (failure: Exception) { DevServerOutput.Failed(failure.message ?: failure.toString()) }
+ }
+ val exit = server.exitCode?.takeIf { server.status == DevServerStatus.Failed }?.let { " · " + tr("Exit code {code}").replace("{code}", "$it") }.orEmpty()
+ Column(Modifier.fillMaxSize()) {
+ ModalHeader({
+ Column {
+ Text(server.name, style = Type.body.semibold, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Text(server.command + exit, style = Type.system(11f).monospaced, color = Palette.secondary, maxLines = 1, overflow = TextOverflow.MiddleEllipsis)
+ }
+ }, { IconButton("Refresh", "arrow.clockwise") { reads++ } })
+ when (val shown = output) {
+ is DevServerOutput.Shown -> if (shown.text.isEmpty()) LogsState { Text(tr("No output yet"), style = Type.body, color = Palette.secondary) }
+ else SelectionContainer(Modifier.weight(1f).fillMaxWidth().verticalScroll(rememberScrollState())) {
+ Text(shown.text, Modifier.padding(start = 20.dp, end = 20.dp, bottom = 20.dp), style = Type.system(12f).monospaced, color = Palette.text)
+ }
+ is DevServerOutput.Failed -> LogsState {
+ Column(Modifier.padding(20.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ SelectionContainer { Text(tr(shown.message), style = Type.body, color = Palette.danger, textAlign = TextAlign.Center) }
+ SecondaryButton("Try again") { output = DevServerOutput.Loading; reads++ }
+ }
+ }
+ DevServerOutput.Loading -> LogsState { Spinner() }
+ }
+ }
+}
+
+/** The sheet's body when there's no output to scroll. */
+@Composable private fun LogsState(content: @Composable () -> Unit) {
+ Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { content() }
+}
diff --git a/apps/android/app/src/test/kotlin/com/codync/android/AnalyticsTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/AnalyticsTest.kt
index 6eb4ed47..d38bf642 100644
--- a/apps/android/app/src/test/kotlin/com/codync/android/AnalyticsTest.kt
+++ b/apps/android/app/src/test/kotlin/com/codync/android/AnalyticsTest.kt
@@ -25,6 +25,8 @@ class AnalyticsTest {
assertEquals("""{"setting":"live_activities","on":false}""", json(AnalyticsEvent.SettingChanged(PhoneSetting.LiveActivities, false)))
assertEquals("""{"via":"link","computer":"fbfcd4f4fe9f876c"}""", json(AnalyticsEvent.ComputerPaired(PairedVia.Link, "tZ1WMzsVltt-fj7mUDwZsg")))
assertEquals("{}", json(AnalyticsEvent.SignedOut))
+ assertEquals("dev_server_action", AnalyticsEvent.DevServerAction(DevServerUse.Copy).name)
+ assertEquals("""{"action":"copy"}""", json(AnalyticsEvent.DevServerAction(DevServerUse.Copy)))
assertEquals("""{"link":"install_link"}""", json(AnalyticsEvent.LinkOpened(OutboundLink.InstallLink)))
assertEquals("""{"step":"choose"}""", json(AnalyticsEvent.OnboardingStepViewed(OnboardingStep.Choose)))
assertEquals("""{"computers":2,"keys":"moved"}""", json(AnalyticsEvent.SignedOutPairingsMoved(2, MovedKeys.Moved)))
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/DevServer.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/DevServer.kt
new file mode 100644
index 00000000..b0918a17
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/DevServer.kt
@@ -0,0 +1,108 @@
+package com.codync.android.core
+
+import kotlinx.serialization.KSerializer
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.descriptors.PrimitiveKind
+import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
+import kotlinx.serialization.encoding.Decoder
+import kotlinx.serialization.encoding.Encoder
+
+/**
+ * A program a bot keeps running on the computer: the host runs it ([managed]), or the bot left it running through its
+ * own shell. What each state shows and offers is decided here, the same on the iPhone (`DevServer.swift`).
+ */
+@Serializable
+data class DevServer(
+ val id: String,
+ val name: String = "",
+ val command: String = "",
+ val folder: String? = null,
+ val status: DevServerStatus = DevServerStatus.Stopped,
+ val ports: List<DevServerPort> = emptyList(),
+ val startedAt: Long? = null,
+ val exitCode: Int? = null,
+ val managed: Boolean = true,
+) {
+ /** Where a phone can reach it while it runs; null when it listens only on its computer. */
+ val remoteAddress: String? get() = if (status == DevServerStatus.Running) ports.firstNotNullOfOrNull { it.remote.firstOrNull() } else null
+
+ /** Its row's value: its ports, or a phrase to look up. */
+ val rowValue: String get() = when (status) {
+ DevServerStatus.Starting -> "Starting"
+ DevServerStatus.Stopped -> "Stopped"
+ DevServerStatus.Failed -> "Failed to start"
+ DevServerStatus.Running -> if (ports.isEmpty()) "Running" else ports.joinToString(" ") { ":${it.port}" }
+ }
+
+ /** Open what can be reached, or read the log of what has no port (a watch build, or one that ended). */
+ val tap: DevServerTap? get() = remoteAddress?.let(DevServerTap::Open)
+ ?: DevServerTap.Logs.takeIf { managed && !(status == DevServerStatus.Running && ports.isNotEmpty()) }
+
+ /** Only what applies. A server the bot started through its shell can only be opened or stopped. */
+ val menuRows: List<DevServerMenuRow> get() = buildList {
+ val live = status == DevServerStatus.Running || status == DevServerStatus.Starting
+ if (status == DevServerStatus.Running && ports.isNotEmpty() && remoteAddress == null) add(DevServerMenuRow.OnlyOnComputer)
+ if (remoteAddress != null) { add(DevServerMenuRow.Open); add(DevServerMenuRow.CopyAddress) }
+ if (managed) {
+ add(DevServerMenuRow.Logs)
+ if (status != DevServerStatus.Starting) add(if (live) DevServerMenuRow.Restart else DevServerMenuRow.Start)
+ } else add(DevServerMenuRow.StartedByShell)
+ if (live) add(DevServerMenuRow.Stop) else if (managed) add(DevServerMenuRow.Remove)
+ }
+}
+
+@Serializable
+data class DevServerPort(
+ val port: Int,
+ /** Works on the computer running it. */
+ val local: String = "",
+ /** Work from other devices; empty when it listens only on that computer. */
+ val remote: List<String> = emptyList(),
+)
+
+@Serializable(with = DevServerStatusSerializer::class)
+enum class DevServerStatus(val wire: String) { Starting("starting"), Running("running"), Stopped("stopped"), Failed("failed") }
+
+/** A status a newer host adds reads as stopped, rather than losing the bot. */
+internal object DevServerStatusSerializer : KSerializer<DevServerStatus> {
+ override val descriptor = PrimitiveSerialDescriptor("DevServerStatus", PrimitiveKind.STRING)
+ override fun serialize(encoder: Encoder, value: DevServerStatus) = encoder.encodeString(value.wire)
+ override fun deserialize(decoder: Decoder): DevServerStatus {
+ val wire = decoder.decodeString()
+ return DevServerStatus.entries.firstOrNull { it.wire == wire } ?: DevServerStatus.Stopped
+ }
+}
+
+/** What the host can be asked to do with a server. Clients name it and never send a command. */
+enum class DevServerAction(val method: String) { Stop("devServerStop"), Restart("devServerRestart"), Remove("devServerRemove") }
+
+/** What tapping its row does. */
+sealed interface DevServerTap {
+ data class Open(val address: String) : DevServerTap
+ data object Logs : DevServerTap
+}
+
+/** A line of its menu. */
+enum class DevServerMenuRow { OnlyOnComputer, Open, CopyAddress, Logs, Restart, Start, StartedByShell, Stop, Remove }
+
+/** What the chat's title shows of a bot's servers: nothing until one starts, or once they've all stopped. */
+sealed interface DevServerSummary {
+ data object None : DevServerSummary
+ data object Starting : DevServerSummary
+ data object Failed : DevServerSummary
+ data class Running(val text: String) : DevServerSummary
+}
+
+fun devServerSummary(servers: List<DevServer>): DevServerSummary {
+ val running = servers.filter { it.status == DevServerStatus.Running }
+ val first = running.firstOrNull { it.ports.isNotEmpty() } ?: running.firstOrNull()
+ return when {
+ first != null -> {
+ val label = first.ports.firstOrNull()?.let { ":${it.port}" } ?: first.name
+ DevServerSummary.Running(if (running.size > 1) "$label +${running.size - 1}" else label)
+ }
+ servers.any { it.status == DevServerStatus.Starting } -> DevServerSummary.Starting
+ servers.any { it.status == DevServerStatus.Failed } -> DevServerSummary.Failed
+ else -> DevServerSummary.None
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt
index ab471923..b58e3c79 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt
@@ -79,6 +79,8 @@ data class Bot(
val agentStep: AgentStep? = null,
/** Agents of its chain resting now. */
val resting: List<Resting> = emptyList(),
+ /** What it keeps running on the computer. Empty from an older host, and for a group. */
+ val devServers: List<DevServer> = emptyList(),
val customIcon: CustomIcon? = null,
) {
/** Its band in the roster: pinned bots, then the rest. Reordering stays inside a band. */
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/DevServerTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/DevServerTest.kt
new file mode 100644
index 00000000..09128500
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/DevServerTest.kt
@@ -0,0 +1,80 @@
+package com.codync.android.core
+
+import com.codync.android.core.DevServerMenuRow.*
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Test
+
+class DevServerTest {
+ private fun server(status: DevServerStatus = DevServerStatus.Running, name: String = "web", ports: List<DevServerPort> = emptyList(), managed: Boolean = true) =
+ DevServer("a", name, "npm run dev", "/site", status, ports, startedAt = 1, managed = managed)
+ private fun port(number: Int, remote: List<String> = emptyList()) = DevServerPort(number, "http://localhost:$number", remote)
+ private val reachable = port(5173, listOf("http://192.168.1.20:5173"))
+
+ @Test fun `the title shows nothing without a live server`() {
+ assertEquals(DevServerSummary.None, devServerSummary(emptyList()))
+ assertEquals(DevServerSummary.None, devServerSummary(listOf(server(DevServerStatus.Stopped))))
+ }
+
+ @Test fun `the title shows the port and how many more run`() {
+ assertEquals(DevServerSummary.Running(":5173"), devServerSummary(listOf(server(ports = listOf(port(5173))))))
+ val three = listOf(server(name = "watch"), server(ports = listOf(port(5173))), server(ports = listOf(port(8787))))
+ assertEquals(DevServerSummary.Running(":5173 +2"), devServerSummary(three))
+ }
+
+ @Test fun `the title names a server without a port`() {
+ assertEquals(DevServerSummary.Running("watch"), devServerSummary(listOf(server(name = "watch"))))
+ }
+
+ @Test fun `running outranks starting which outranks failed`() {
+ assertEquals(DevServerSummary.Running(":1"), devServerSummary(listOf(server(DevServerStatus.Failed), server(ports = listOf(port(1))))))
+ assertEquals(DevServerSummary.Starting, devServerSummary(listOf(server(DevServerStatus.Failed), server(DevServerStatus.Starting))))
+ assertEquals(DevServerSummary.Failed, devServerSummary(listOf(server(DevServerStatus.Failed), server(DevServerStatus.Stopped))))
+ }
+
+ @Test fun `a row says its ports or its state`() {
+ assertEquals(":5173 :24678", server(ports = listOf(port(5173), port(24678))).rowValue)
+ assertEquals("Running", server().rowValue)
+ assertEquals("Starting", server(DevServerStatus.Starting).rowValue)
+ assertEquals("Stopped", server(DevServerStatus.Stopped).rowValue)
+ assertEquals("Failed to start", server(DevServerStatus.Failed).rowValue)
+ }
+
+ @Test fun `tapping opens what a phone can reach and logs what ended`() {
+ val open = DevServerTap.Open("http://192.168.1.20:5173")
+ assertEquals(open, server(ports = listOf(reachable)).tap)
+ // The first port listens only on the computer; the second doesn't.
+ assertEquals(open, server(ports = listOf(port(1), reachable)).tap)
+ assertNull(server(ports = listOf(port(5173))).tap)
+ assertEquals(DevServerTap.Logs, server().tap)
+ assertEquals(DevServerTap.Logs, server(DevServerStatus.Starting).tap)
+ assertEquals(DevServerTap.Logs, server(DevServerStatus.Stopped).tap)
+ assertEquals(DevServerTap.Logs, server(DevServerStatus.Failed).tap)
+ assertNull(server(DevServerStatus.Stopped, managed = false).tap)
+ // A stopped server's last address is no longer an address.
+ assertEquals(DevServerTap.Logs, server(DevServerStatus.Stopped, ports = listOf(reachable)).tap)
+ }
+
+ @Test fun `the menu offers only what applies`() {
+ assertEquals(listOf(Open, CopyAddress, Logs, Restart, Stop), server(ports = listOf(reachable)).menuRows)
+ assertEquals(listOf(OnlyOnComputer, Logs, Restart, Stop), server(ports = listOf(port(5173))).menuRows)
+ assertEquals(listOf(Logs, Restart, Stop), server().menuRows)
+ assertEquals(listOf(Logs, Stop), server(DevServerStatus.Starting).menuRows)
+ assertEquals(listOf(Logs, Start, Remove), server(DevServerStatus.Stopped).menuRows)
+ assertEquals(listOf(Logs, Start, Remove), server(DevServerStatus.Failed).menuRows)
+ }
+
+ @Test fun `a server left in the bot's shell can only be opened or stopped`() {
+ assertEquals(listOf(Open, CopyAddress, StartedByShell, Stop), server(ports = listOf(reachable), managed = false).menuRows)
+ assertEquals(listOf(OnlyOnComputer, StartedByShell, Stop), server(ports = listOf(port(5173)), managed = false).menuRows)
+ }
+
+ @Test fun `a bot decodes its servers and an older host's without them`() {
+ val bot = HostClient.decode(Json.parseToJsonElement("""{"id":"b","name":"Scout","devServers":[{"id":"a","name":"web","command":"npm run dev",
+ "folder":null,"status":"running","ports":[{"port":5173,"local":"http://localhost:5173","remote":["http://192.168.1.20:5173"]}],
+ "startedAt":null,"exitCode":null,"managed":true},{"id":"c","name":"w","command":"w","status":"sleeping","ports":[],"managed":false}]}""").jsonObject)
+ assertEquals("http://192.168.1.20:5173", bot.devServers.first().remoteAddress)
+ assertEquals(DevServerStatus.Stopped, bot.devServers.last().status)
+ assertTrue(HostClient.decode(Json.parseToJsonElement("""{"id":"b","name":"Scout"}""").jsonObject).devServers.isEmpty())
+ }
+}
diff --git a/apps/desktop/e2e/dev-servers.spec.ts b/apps/desktop/e2e/dev-servers.spec.ts
new file mode 100644
index 00000000..d68ef113
--- /dev/null
+++ b/apps/desktop/e2e/dev-servers.spec.ts
@@ -0,0 +1,89 @@
+import { test, expect, type Page } from '@playwright/test'
+import { api, attach } from './sandbox.ts'
+
+/** A port nothing listens on yet, below the range the system picks from. */
+const freePort = () => 20_000 + Math.floor(Math.random() * 10_000)
+
+/** A bot of its own, its chat open, whose agent never runs: the servers come through the host's API. */
+async function openBot(page: Page, name: string) {
+ await page.reload()
+ const { bot } = await api<{ bot: { id: string } }>(page, 'createBot', { name, backend: 'custom', command: 'unused', connectors: [], permission: 'auto' })
+ await page.locator('.roster-row', { hasText: name }).click()
+ return bot.id
+}
+
+const start = (page: Page, botId: string, command: string, name: string) =>
+ api(page, 'chatCall', { botId, name: 'start_dev_server', arguments: { command, name } })
+
+async function pick(page: Page, row: ReturnType<Page['locator']>, title: string) {
+ await row.hover()
+ await row.locator('.dev-server-more').click()
+ await page.locator('.menu-row', { hasText: title }).click()
+}
+
+test('a dev server shows its port in the title, and the details open, log, stop, start and remove it', async () => {
+ const { browser, page } = await attach()
+ const name = `Dev server e2e ${Date.now()}`
+ const port = freePort()
+ let botId: string | undefined
+ try {
+ botId = await openBot(page, name)
+ const pill = page.locator('.title-pill')
+ await expect(pill).toContainText(name)
+ await expect(pill).not.toContainText(`:${port}`)
+
+ await start(page, botId, `python3 -m http.server ${port} --bind 127.0.0.1`, 'web')
+ await expect(pill).toContainText(`:${port}`)
+
+ await pill.click()
+ const row = page.locator('.dev-server-row', { hasText: 'web' })
+ await expect(row).toContainText(`:${port}`)
+
+ await row.hover()
+ await row.locator('.dev-server-more').click()
+ await expect(page.getByText('Copy address')).toBeVisible()
+ await page.locator('.menu-row', { hasText: 'Logs' }).click()
+ await expect(page.locator('.modal-content')).toContainText('python3 -m http.server')
+ await page.keyboard.press('Escape')
+ await expect(page.locator('.modal-content')).toBeHidden()
+
+ await pick(page, row, 'Stop')
+ await expect(row).toContainText('Stopped')
+ await expect(pill).not.toContainText(`:${port}`)
+
+ await pick(page, row, 'Start')
+ await expect(row).toContainText(`:${port}`)
+ await expect(pill).toContainText(`:${port}`)
+
+ await pick(page, row, 'Stop')
+ await expect(row).toContainText('Stopped')
+ await pick(page, row, 'Remove')
+ await expect(page.locator('.dev-server-row')).toHaveCount(0)
+ await expect(page.getByText('Dev servers')).toBeHidden()
+ } finally {
+ if (botId) await api(page, 'deleteBot', { botId }).catch(() => {})
+ await browser.close()
+ }
+})
+
+test('a failing command shows Failed to start, and its row opens the log with how it ended', async () => {
+ const { browser, page } = await attach()
+ let botId: string | undefined
+ try {
+ botId = await openBot(page, `Dev server failure e2e ${Date.now()}`)
+ await start(page, botId, 'echo no such script; exit 3', 'docs')
+ const pill = page.locator('.title-pill')
+ await expect(pill).toContainText('Failed to start')
+
+ await pill.click()
+ const row = page.locator('.dev-server-row', { hasText: 'docs' })
+ await expect(row).toContainText('Failed to start')
+ await row.locator('.dev-server-open').click()
+ const logs = page.locator('.modal-content')
+ await expect(logs).toContainText('Exit code 3')
+ await expect(logs).toContainText('no such script')
+ } finally {
+ if (botId) await api(page, 'deleteBot', { botId }).catch(() => {})
+ await browser.close()
+ }
+})
diff --git a/apps/desktop/src/renderer/store/bot-store.ts b/apps/desktop/src/renderer/store/bot-store.ts
index 13261ffa..17c8e78a 100644
--- a/apps/desktop/src/renderer/store/bot-store.ts
+++ b/apps/desktop/src/renderer/store/bot-store.ts
@@ -19,6 +19,7 @@ import { readSharedFile } from '../../shared/files.ts'
import { prefs } from '../lib/prefs'
import { FileDownloads } from './file-downloads'
import { BotSections } from './bot-sections'
+import { DevServerCommands } from './dev-servers'
import { BotSync, sleep } from './bot-sync'
export { builtInBackendName, type Connection } from './bot-mirror'
@@ -52,6 +53,7 @@ export const QUICK_REACTIONS = ['👍', '❤️', '😂', '🎉', '👀', '✅']
export class BotStore extends BotSync {
readonly fileDownloads = new FileDownloads(() => this.changed())
readonly sections = new BotSections(() => this.bots, () => this.changed(), (op, undo) => this.perform(op, true, undo))
+ readonly devServers = new DevServerCommands((op) => this.perform(op), (op) => this.withLink(op))
override retire() { this.fileDownloads.retire(); super.retire() }
diff --git a/apps/desktop/src/renderer/store/dev-servers.ts b/apps/desktop/src/renderer/store/dev-servers.ts
new file mode 100644
index 00000000..0bb924cc
--- /dev/null
+++ b/apps/desktop/src/renderer/store/dev-servers.ts
@@ -0,0 +1,22 @@
+import type { HostClient } from '../client/host-client'
+
+type DevServerMethod = 'devServerStop' | 'devServerRestart' | 'devServerRemove'
+
+/** What this app can ask of a computer's dev servers: it names one, and never sends a command. */
+export class DevServerCommands {
+ private perform: (op: (c: HostClient) => Promise<unknown>) => Promise<boolean>
+ private withLink: <T>(op: (c: HostClient) => Promise<T>) => Promise<T>
+ constructor(perform: DevServerCommands['perform'], withLink: DevServerCommands['withLink']) {
+ this.perform = perform
+ this.withLink = withLink
+ }
+
+ act(method: DevServerMethod, botId: string, id: string) {
+ return this.perform((c) => c.call(method, { botId, id }))
+ }
+
+ async logs(botId: string, id: string): Promise<string> {
+ const { text } = await this.withLink((c) => c.call<{ text: string }>('devServerLogs', { botId, id }))
+ return text
+ }
+}
diff --git a/apps/desktop/src/renderer/views/thread/DetailsPanel.tsx b/apps/desktop/src/renderer/views/thread/DetailsPanel.tsx
index fd5af646..9ab465ec 100644
--- a/apps/desktop/src/renderer/views/thread/DetailsPanel.tsx
+++ b/apps/desktop/src/renderer/views/thread/DetailsPanel.tsx
@@ -13,6 +13,7 @@ import { BotSettingsPanel } from '../bots/BotEditorView'
import { MemoryCard } from '../bots/MemoryView'
import { RoutinesView } from '../routines/RoutinesView'
import { LibraryView } from '../library/LibraryView'
+import { DevServersSection } from './DevServersSection'
import { MacChatButton } from './MacChatButton'
import '../bots/bots.css'
import './details-panel.css'
@@ -60,6 +61,7 @@ export function DetailsPanel({ botId, routineId, tab, setTab, editGroup, openArt
<div key={tab} className="details-tab fade-in">
{tab === 'details' ? (
<>
+ {bot ? <DevServersSection bot={bot} /> : null}
<BotSettingsPanel botId={botId} part="often" />
{bot ? <ComputerUse bot={bot} /> : null}
<RoutinesView botId={botId} initialId={routineId} />
diff --git a/apps/desktop/src/renderer/views/thread/DevServersSection.tsx b/apps/desktop/src/renderer/views/thread/DevServersSection.tsx
new file mode 100644
index 00000000..4acbf51c
--- /dev/null
+++ b/apps/desktop/src/renderer/views/thread/DevServersSection.tsx
@@ -0,0 +1,154 @@
+import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'
+import { devServerAddress, devServerClick, devServerMenuRows, devServerValue, type DevServer, type DevServerMenuRow, type DevServerSummary } from '@shared/dev-servers'
+import type { Bot } from '@shared/models'
+import { Button, IconButton, Spinner } from '../../components/Controls'
+import { AnchoredMenu, ModalHeader, Sheet, SheetPage, type MenuItem } from '../../components/Overlay'
+import { HStack, VStack } from '../../components/Stack'
+import { Text } from '../../components/Text'
+import { useTr } from '../../lib/use-language'
+import { analytics } from '../../store/analytics'
+import type { BotStore } from '../../store/bot-store'
+import { useApp, useStore } from '../../store/context'
+import './dev-servers.css'
+
+/** A bot's dev servers in the title: the port in quiet text, or nothing. */
+export function DevServerTitle({ summary }: { summary: DevServerSummary }) {
+ const tr = useTr()
+ switch (summary.kind) {
+ case 'none':
+ return null
+ case 'running':
+ return <Text size="body" tone="secondary" tabular className="title-pill-port">{summary.text}</Text>
+ case 'starting':
+ return <><Spinner size={11} /><Text size="body" tone="secondary" className="title-pill-port">{tr(`Starting`)}</Text></>
+ case 'failed':
+ return <Text size="body" tone="danger" className="title-pill-port">{tr(`Failed to start`)}</Text>
+ }
+}
+
+/** What a bot keeps running: a row is its name and port, opening it is a click, the rest is behind `⋯`. */
+export function DevServersSection({ bot }: { bot: Bot }) {
+ const tr = useTr()
+ const [logs, setLogs] = useState<DevServer | null>(null)
+ if (bot.devServers.length === 0) return null
+ return (
+ <section className="details-section">
+ <Text className="details-section-title">{tr(`Dev servers`)}</Text>
+ <VStack className="outlined-card">
+ {bot.devServers.map((server) => <Row key={server.id} bot={bot} server={server} showLogs={() => setLogs(server)} />)}
+ </VStack>
+ <Sheet open={logs !== null} onClose={() => setLogs(null)} width={620} dismissOnDim>
+ {logs ? <Logs bot={bot} server={logs} /> : null}
+ </Sheet>
+ </section>
+ )
+}
+
+function Row({ bot, server, showLogs }: { bot: Bot; server: DevServer; showLogs: () => void }) {
+ const tr = useTr()
+ const store = useStore()
+ const app = useApp()
+ const [menu, setMenu] = useState(false)
+ const more = useRef<HTMLButtonElement>(null)
+ // Not `store.isLoopback`: a store attached over SSH is loopback too, through its tunnel.
+ const onThisComputer = store === app.local
+ const clicked = () => {
+ const click = devServerClick(server, onThisComputer)
+ switch (click.kind) {
+ case 'open':
+ analytics.track({ event: 'dev_server_action', action: 'open' })
+ window.codync.app.openExternal(click.address)
+ return
+ case 'logs': return showLogs()
+ case 'menu': return setMenu(true)
+ }
+ }
+ const items = () => menuItems(bot, server, devServerAddress(server, onThisComputer), store, showLogs)
+ return (
+ <HStack className="dev-server-row">
+ <button className="dev-server-open" title={tooltip(server, tr)} onClick={clicked}>
+ <Text grow truncate className="dev-server-name">{server.name}</Text>
+ {server.status === 'starting' ? <Spinner size={11} /> : null}
+ <Text tabular tone={server.status === 'failed' ? 'danger' : 'secondary'}>{tr(devServerValue(server))}</Text>
+ </button>
+ <IconButton
+ className="dev-server-more"
+ title={tr('More actions for {name}').replaceAll('{name}', () => server.name)}
+ icon="ellipsis"
+ size={24}
+ buttonRef={more}
+ menuOpen={menu}
+ onClick={() => setMenu(true)}
+ />
+ <AnchoredMenu open={menu} onClose={() => setMenu(false)} anchor={more} items={items} />
+ </HStack>
+ )
+}
+
+function tooltip(server: DevServer, tr: (text: string) => string): string {
+ const code = server.exitCode !== null && server.status === 'failed' ? ` · ${tr('Exit code {code}').replaceAll('{code}', String(server.exitCode))}` : ''
+ return `${server.command}${code}`
+}
+
+function menuItems(bot: Bot, server: DevServer, address: string | null, store: BotStore, showLogs: () => void): MenuItem[] {
+ const copyAddress = (local: string) => {
+ analytics.track({ event: 'dev_server_action', action: 'copy' })
+ window.codync.app.copy(address ?? local)
+ }
+ const item = (row: DevServerMenuRow, divider: boolean): MenuItem => {
+ switch (row) {
+ case 'copyAddress':
+ // Elsewhere, a server that listens on its computer only can't be opened from here.
+ return { title: 'Copy address', icon: 'doc.on.doc', detail: address ? undefined : 'Only reachable on the computer', action: () => copyAddress(server.ports[0].local) }
+ case 'logs':
+ return { title: 'Logs', icon: 'doc.text', action: showLogs }
+ case 'restart':
+ return { title: 'Restart', icon: 'arrow.clockwise', action: () => store.devServers.act('devServerRestart', bot.id, server.id) }
+ case 'start':
+ return { title: 'Start', icon: 'arrow.clockwise', action: () => store.devServers.act('devServerRestart', bot.id, server.id) }
+ case 'stop':
+ return {
+ title: 'Stop',
+ icon: 'stop.fill',
+ destructive: true,
+ divider,
+ detail: server.managed ? undefined : "Started through the bot's shell: it stops with the bot",
+ action: () => store.devServers.act('devServerStop', bot.id, server.id),
+ }
+ case 'remove':
+ return { title: 'Remove', icon: 'trash', destructive: true, divider, action: () => store.devServers.act('devServerRemove', bot.id, server.id) }
+ }
+ }
+ return devServerMenuRows(server).map((row, index) => item(row, index > 0))
+}
+
+function Logs({ bot, server }: { bot: Bot; server: DevServer }) {
+ const tr = useTr()
+ const store = useStore()
+ const [text, setText] = useState<string | null>(null)
+ const [failed, setFailed] = useState<string | null>(null)
+ const load = useCallback(() => {
+ setFailed(null)
+ store.devServers.logs(bot.id, server.id).then(setText, (error: unknown) => setFailed(error instanceof Error ? error.message : String(error)))
+ }, [store, bot.id, server.id])
+ useEffect(load, [load])
+ const state = (content: ReactNode) => <VStack gap={12} align="center" justify="center" className="dev-server-logs-state">{content}</VStack>
+ return (
+ <SheetPage>
+ <ModalHeader
+ title={server.name}
+ subtitle={<Text mono size="caption" tone="secondary">{tooltip(server, tr)}</Text>}
+ trailing={<IconButton title="Refresh" icon="arrow.clockwise" onClick={load} />}
+ />
+ {failed ? (
+ state(<><Text tone="danger">{failed}</Text><Button kind="secondary" onClick={load}>Try again</Button></>)
+ ) : text === null ? (
+ state(<Spinner />)
+ ) : text === '' ? (
+ state(<Text tone="secondary">{tr(`No output yet`)}</Text>)
+ ) : (
+ <pre className="dev-server-logs selectable">{text}</pre>
+ )}
+ </SheetPage>
+ )
+}
diff --git a/apps/desktop/src/renderer/views/thread/ThreadView.tsx b/apps/desktop/src/renderer/views/thread/ThreadView.tsx
index b6eaea76..bb19e485 100644
--- a/apps/desktop/src/renderer/views/thread/ThreadView.tsx
+++ b/apps/desktop/src/renderer/views/thread/ThreadView.tsx
@@ -16,7 +16,9 @@ import { buildChat, rowIn, useArrivals, type ChatItem } from './chat-items'
import { BotConversationView, BotMessageRow } from './BotConversation'
import { CallConversationView, CallLineRow } from '../call/CallRows'
import { hidingCalls } from '@shared/calls'
+import { devServerSummary } from '@shared/dev-servers'
import { ChatRow, TimeSeparator } from './ChatRows'
+import { DevServerTitle } from './DevServersSection'
import { WorkingTransition } from './WorkingTransition'
import { RoutineNotice } from './RoutineNotice'
import { Composer } from './Composer'
@@ -113,6 +115,12 @@ export const ThreadView = memo(function ThreadView({ botId }: { botId: string })
if (!wide) setCompactDetails((c) => !c)
else setShowSettings((s) => !s)
}, [wide])
+ const devServers = devServerSummary(bot?.devServers ?? [])
+ // The title's port leads to its row, whichever page the inspector was left on.
+ const openFromTitle = useCallback(() => {
+ if (devServers.kind !== 'none') setDetailsTab('details')
+ toggleDetails()
+ }, [devServers.kind, toggleDetails])
useEffect(
() =>
@@ -172,10 +180,11 @@ export const ThreadView = memo(function ThreadView({ botId }: { botId: string })
) : null}
</div>
{/* The call bar takes the pill's place; its frosted glass would show the name blurred. */}
- <button className={`title-pill ${calling ? 'hidden-by-call' : ''}`} inert={calling} onClick={toggleDetails} aria-label={tr('{name}, view details').replaceAll('{name}', () => bot?.name ?? tr('Conversation'))} title="View conversation details">
+ <button className={`title-pill ${calling ? 'hidden-by-call' : ''}`} inert={calling} onClick={openFromTitle} aria-label={tr('{name}, view details').replaceAll('{name}', () => bot?.name ?? tr('Conversation'))} title="View conversation details">
<HStack as="span" gap={7}>
{bot ? isGroup(bot) ? <GroupAvatar members={store.members(bot)} size={22} /> : <BotAvatar bot={bot} size={22} /> : null}
<Text size="body" weight="medium" tone="text" truncate>{bot?.name ?? ''}</Text>
+ <DevServerTitle summary={devServers} />
{/* Grok Bot's hint on hover: the pill opens the details. */}
<span className="title-pill-chevron">
<Icon name="chevron.right" size={10} weight="semibold" color="var(--secondary)" />
diff --git a/apps/desktop/src/renderer/views/thread/dev-servers.css b/apps/desktop/src/renderer/views/thread/dev-servers.css
new file mode 100644
index 00000000..082a2367
--- /dev/null
+++ b/apps/desktop/src/renderer/views/thread/dev-servers.css
@@ -0,0 +1,55 @@
+/* A bot's dev servers: its port in the title, and one line each in the inspector, with its actions out of sight until the row is hovered. */
+.title-pill-port {
+ flex: none;
+ white-space: nowrap;
+}
+
+.dev-server-row {
+ padding-right: 8px;
+}
+.dev-server-row + .dev-server-row {
+ box-shadow: inset 0 0.5px 0 var(--border);
+}
+.dev-server-open {
+ flex: 1;
+ min-width: 0;
+ min-height: 44px;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 0 6px 0 14px;
+ font-size: var(--text-body);
+ text-align: left;
+}
+.dev-server-open:hover .dev-server-name {
+ text-decoration: underline;
+ text-underline-offset: 2px;
+}
+.dev-server-more {
+ flex: none;
+ opacity: 0;
+ transition: opacity var(--hover);
+}
+.dev-server-row:hover .dev-server-more,
+.dev-server-more:focus-visible,
+.dev-server-more[aria-expanded='true'] {
+ opacity: 1;
+}
+
+.dev-server-logs {
+ margin: 8px 16px 16px;
+ padding: 12px;
+ height: min(420px, 60vh);
+ overflow: auto;
+ border-radius: var(--radius-m);
+ background: var(--code-background);
+ font-family: var(--mono);
+ font-size: var(--text-caption);
+ line-height: 1.6;
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+}
+.dev-server-logs-state {
+ min-height: 160px;
+ padding: 16px;
+}
diff --git a/apps/desktop/src/shared/analytics.ts b/apps/desktop/src/shared/analytics.ts
index 08b8e753..c1b8884e 100644
--- a/apps/desktop/src/shared/analytics.ts
+++ b/apps/desktop/src/shared/analytics.ts
@@ -53,6 +53,7 @@ export type AnalyticsEvent =
| { event: 'signed_out' }
| { event: 'star_prompt_answered'; ask: 'first' | 'second'; starred: boolean }
| { event: 'link_opened'; link: Link }
+ | { event: 'dev_server_action'; action: 'open' | 'copy' }
| { event: 'screen_viewed'; screen: Screen }
| { event: 'voice_call_started'; engine: VoiceCallEngine }
| { event: 'voice_call_quality'; engine: VoiceCallEngine; ready_ms?: number; reconnects: number; stuck: VoiceStuck; failure: VoiceFailure }
diff --git a/apps/desktop/src/shared/dev-servers.test.ts b/apps/desktop/src/shared/dev-servers.test.ts
new file mode 100644
index 00000000..1cd04cac
--- /dev/null
+++ b/apps/desktop/src/shared/dev-servers.test.ts
@@ -0,0 +1,77 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { devServerAddress, devServerClick, devServerMenuRows, devServerSummary, devServerValue, type DevServer } from './dev-servers.ts'
+import { normalizeBot } from './models.ts'
+
+const server = (over: Partial<DevServer>): DevServer => ({
+ id: 'a', name: 'web', command: 'npm run dev', folder: '/site', status: 'running', ports: [], startedAt: 1, exitCode: null, managed: true, ...over,
+})
+const port = (n: number, remote: string[] = []) => ({ port: n, local: `http://localhost:${n}`, remote })
+
+test('the title shows nothing without a live server', () => {
+ assert.deepEqual(devServerSummary([]), { kind: 'none' })
+ assert.deepEqual(devServerSummary([server({ status: 'stopped' })]), { kind: 'none' })
+})
+
+test('the title shows the port, and how many more run', () => {
+ assert.deepEqual(devServerSummary([server({ ports: [port(5173)] })]), { kind: 'running', text: ':5173' })
+ const servers = [server({ name: 'watch' }), server({ ports: [port(5173)] }), server({ ports: [port(8787)] })]
+ assert.deepEqual(devServerSummary(servers), { kind: 'running', text: ':5173 +2' })
+})
+
+test('the title names a server without a port', () => {
+ assert.deepEqual(devServerSummary([server({ name: 'watch' })]), { kind: 'running', text: 'watch' })
+})
+
+test('a running server outranks one starting, which outranks one failed', () => {
+ assert.deepEqual(devServerSummary([server({ status: 'failed' }), server({ ports: [port(1)] })]), { kind: 'running', text: ':1' })
+ assert.deepEqual(devServerSummary([server({ status: 'failed' }), server({ status: 'starting' })]), { kind: 'starting' })
+ assert.deepEqual(devServerSummary([server({ status: 'failed' })]), { kind: 'failed' })
+})
+
+test('a server opens at its local address on its own computer', () => {
+ assert.equal(devServerAddress(server({ ports: [port(5173)] }), true), 'http://localhost:5173')
+})
+
+test('elsewhere, an SSH store included, a server opens only at what other devices can reach', () => {
+ assert.equal(devServerAddress(server({ ports: [port(5173)] }), false), null)
+ assert.equal(devServerAddress(server({ ports: [port(5173, ['http://192.168.1.20:5173'])] }), false), 'http://192.168.1.20:5173')
+})
+
+test('only a running server with a port opens', () => {
+ assert.equal(devServerAddress(server({ status: 'stopped', ports: [port(5173)] }), true), null)
+ assert.equal(devServerAddress(server({}), true), null)
+})
+
+test('a row says its ports or its state', () => {
+ assert.equal(devServerValue(server({ ports: [port(5173), port(24678)] })), ':5173 :24678')
+ assert.equal(devServerValue(server({})), 'Running')
+ assert.equal(devServerValue(server({ status: 'starting' })), 'Starting')
+ assert.equal(devServerValue(server({ status: 'stopped' })), 'Stopped')
+ assert.equal(devServerValue(server({ status: 'failed' })), 'Failed to start')
+})
+
+test('a click opens what can be reached from here, and reads the log of what has no port', () => {
+ assert.deepEqual(devServerClick(server({ ports: [port(5173)] }), true), { kind: 'open', address: 'http://localhost:5173' })
+ assert.deepEqual(devServerClick(server({ ports: [port(5173)] }), false), { kind: 'menu' }, 'its menu says why not')
+ for (const status of ['running', 'starting', 'stopped', 'failed'] as const) {
+ assert.deepEqual(devServerClick(server({ status }), true), { kind: 'logs' }, status)
+ }
+ assert.deepEqual(devServerClick(server({ managed: false }), true), { kind: 'menu' }, 'one from the shell has no log')
+})
+
+test('the menu offers only what applies', () => {
+ assert.deepEqual(devServerMenuRows(server({ ports: [port(5173)] })), ['copyAddress', 'logs', 'restart', 'stop'])
+ assert.deepEqual(devServerMenuRows(server({})), ['logs', 'restart', 'stop'])
+ assert.deepEqual(devServerMenuRows(server({ status: 'starting' })), ['logs', 'stop'])
+ assert.deepEqual(devServerMenuRows(server({ status: 'stopped' })), ['logs', 'start', 'remove'])
+ assert.deepEqual(devServerMenuRows(server({ status: 'failed' })), ['logs', 'start', 'remove'])
+ assert.deepEqual(devServerMenuRows(server({ ports: [port(5173)], managed: false })), ['copyAddress', 'stop'])
+})
+
+test('a status from a newer host reads as stopped', () => {
+ const raw = { id: 'a', status: 'sleeping' } as unknown as DevServer
+ const bot = normalizeBot({ id: 'b', devServers: [raw, server({ status: 'failed' })] })
+ assert.deepEqual(bot.devServers.map((s) => s.status), ['stopped', 'failed'])
+ assert.deepEqual(normalizeBot({ id: 'b' }).devServers, [], 'an older host sends none')
+})
diff --git a/apps/desktop/src/shared/dev-servers.ts b/apps/desktop/src/shared/dev-servers.ts
new file mode 100644
index 00000000..a577803a
--- /dev/null
+++ b/apps/desktop/src/shared/dev-servers.ts
@@ -0,0 +1,92 @@
+/** A program a bot keeps running: the host runs it (`managed`), or the bot left it running through its shell. */
+export interface DevServerPort {
+ port: number
+ /** Works on the computer running it. */
+ local: string
+ /** Work from other devices; empty when it listens only on that computer. */
+ remote: string[]
+}
+
+export interface DevServer {
+ id: string
+ name: string
+ command: string
+ folder: string | null
+ status: 'starting' | 'running' | 'stopped' | 'failed'
+ ports: DevServerPort[]
+ startedAt: number | null
+ exitCode: number | null
+ managed: boolean
+}
+
+const STATUSES: readonly string[] = ['starting', 'running', 'stopped', 'failed'] satisfies DevServer['status'][]
+
+/** A status a newer host adds reads as stopped, rather than breaking the row. */
+export function normalizeDevServer(raw: DevServer): DevServer {
+ return STATUSES.includes(raw.status) ? raw : { ...raw, status: 'stopped' }
+}
+
+/** What the title shows of a bot's servers: nothing until one starts, or stays stopped. */
+export type DevServerSummary =
+ | { kind: 'none' }
+ | { kind: 'starting' }
+ | { kind: 'failed' }
+ | { kind: 'running'; text: string }
+
+export function devServerSummary(servers: DevServer[]): DevServerSummary {
+ const running = servers.filter((s) => s.status === 'running')
+ const first = running.find((s) => s.ports.length > 0) ?? running[0]
+ if (first) {
+ const label = first.ports.length > 0 ? `:${first.ports[0].port}` : first.name
+ return { kind: 'running', text: running.length > 1 ? `${label} +${running.length - 1}` : label }
+ }
+ if (servers.some((s) => s.status === 'starting')) return { kind: 'starting' }
+ if (servers.some((s) => s.status === 'failed')) return { kind: 'failed' }
+ return { kind: 'none' }
+}
+
+/**
+ * The address to open a running server at from here, if there is one. `onThisComputer`: the store is this app's own
+ * computer. Anywhere else (a phone, or a desktop attached over SSH, whose loopback is a tunnel) can't use `local`.
+ */
+export function devServerAddress(server: DevServer, onThisComputer: boolean): string | null {
+ const port = server.ports[0]
+ if (server.status !== 'running' || !port) return null
+ return onThisComputer ? port.local : port.remote[0] ?? null
+}
+
+/** Its row's value: its ports, or a phrase to look up. */
+export function devServerValue(server: DevServer): string {
+ switch (server.status) {
+ case 'starting': return 'Starting'
+ case 'failed': return 'Failed to start'
+ case 'stopped': return 'Stopped'
+ case 'running': return server.ports.length > 0 ? server.ports.map((p) => `:${p.port}`).join(' ') : 'Running'
+ }
+}
+
+export type DevServerClick = { kind: 'open'; address: string } | { kind: 'logs' } | { kind: 'menu' }
+
+/** What clicking its row does: open it, or read its log when it has no port (a watch build, or one that ended). */
+export function devServerClick(server: DevServer, onThisComputer: boolean): DevServerClick {
+ const address = devServerAddress(server, onThisComputer)
+ if (address) return { kind: 'open', address }
+ const listens = server.status === 'running' && server.ports.length > 0
+ return server.managed && !listens ? { kind: 'logs' } : { kind: 'menu' }
+}
+
+export type DevServerMenuRow = 'copyAddress' | 'logs' | 'restart' | 'start' | 'stop' | 'remove'
+
+/** Only what applies. A server the bot started through its shell can only be opened or stopped. */
+export function devServerMenuRows(server: DevServer): DevServerMenuRow[] {
+ const live = server.status === 'running' || server.status === 'starting'
+ const rows: DevServerMenuRow[] = []
+ if (live && server.ports.length > 0) rows.push('copyAddress')
+ if (server.managed) {
+ rows.push('logs')
+ if (server.status !== 'starting') rows.push(live ? 'restart' : 'start')
+ }
+ if (live) rows.push('stop')
+ else if (server.managed) rows.push('remove')
+ return rows
+}
diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.ts
index 2be470e1..808f0107 100644
--- a/apps/desktop/src/shared/models.ts
+++ b/apps/desktop/src/shared/models.ts
@@ -1,5 +1,6 @@
import type { ArtifactCard } from './artifacts'
import type { CallLine } from './calls'
+import { normalizeDevServer, type DevServer } from './dev-servers.ts'
// Wire types for codync-host (see host/src/api/). Field names match the
// host's camelCase JSON. Timestamps are epoch milliseconds.
@@ -43,6 +44,8 @@ export interface Bot {
agentStep: AgentStep | null
/** Agents of its chain (its own included) resting now; one whose `until` passed isn't. */
resting: Resting[]
+ /** What it keeps running (`dev-servers.ts`). */
+ devServers: DevServer[]
pinned: boolean
/** The computer's lead bot: the host makes the first, and the user may pick another (`setLead`) or delete it. Placed in the roster like any bot, never hidden. */
lead: boolean
@@ -110,6 +113,7 @@ export function normalizeBot(raw: Partial<Bot> & { id: string }): Bot {
selfFallbacks: raw.selfFallbacks ?? null,
agentStep: raw.agentStep ?? null,
resting: raw.resting ?? [],
+ devServers: (raw.devServers ?? []).map(normalizeDevServer),
pinned: raw.pinned ?? false,
lead: raw.lead ?? false,
position: raw.position ?? 0,
diff --git a/apps/ios/Kit/Sources/CodyncKit/Analytics/AnalyticsEvent.swift b/apps/ios/Kit/Sources/CodyncKit/Analytics/AnalyticsEvent.swift
index b04f794a..6b176044 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Analytics/AnalyticsEvent.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Analytics/AnalyticsEvent.swift
@@ -29,6 +29,8 @@ public enum AnalyticsEvent: Equatable, Sendable {
case screenViewed(Screen)
case reviewRequested(prompts: Int)
case reviewLinkOpened
+ /// A dev server opened, or its address copied; the host reports what it does itself.
+ case devServerAction(DevServerUse)
public enum Notifications: String, Sendable { case allowed, denied, notAsked = "not_asked" }
public enum OnboardingStep: String, Sendable { case welcome, choose, install, scan }
@@ -43,6 +45,7 @@ public enum AnalyticsEvent: Equatable, Sendable {
public enum Link: String, Sendable {
case github, issues, appStore = "app_store", demo, tailscale, privacy, installCommand = "install_command", installLink = "install_link"
}
+ public enum DevServerUse: String, Sendable { case open, copy }
public enum VoiceEngine: String, Sendable { case onDevice = "on_device", openai, gemini, cloud }
public enum VoiceStuck: String, Sendable { case none, connecting, reconnecting, speaking }
public enum VoiceFailure: String, Sendable { case none, microphone, connection, provider }
@@ -119,6 +122,7 @@ public enum AnalyticsEvent: Equatable, Sendable {
case .screenViewed: "screen_viewed"
case .reviewRequested: "review_requested"
case .reviewLinkOpened: "review_link_opened"
+ case .devServerAction: "dev_server_action"
}
}
@@ -152,6 +156,7 @@ public enum AnalyticsEvent: Equatable, Sendable {
case let .reviewRequested(prompts):
return ["prompts": .int(prompts), "policy": .string("v2")]
case .reviewLinkOpened: return ["source": .string("settings")]
+ case let .devServerAction(use): return ["action": .string(use.rawValue)]
case let .screenViewed(screen): return ["screen": .string(screen.rawValue)]
}
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift
index 9ba47614..7a8ba2c9 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift
@@ -352,6 +352,17 @@ public extension HostClient {
let _: Empty = try await call("unqueue", ["botId": botId, "entryId": entryId])
}
+ func devServer(_ action: DevServer.Action, botId: String, id: String) async throws {
+ let _: Empty = try await call(action.rawValue, ["botId": botId, "id": id])
+ }
+
+ /// The server's recent output.
+ func devServerLogs(botId: String, id: String) async throws -> String {
+ struct Res: Decodable { var text: String }
+ let res: Res = try await call("devServerLogs", ["botId": botId, "id": id])
+ return res.text
+ }
+
func respondPermission(entryId: String, optionId: String?) async throws {
struct Body: Encodable { var entryId: String; var optionId: String? }
let _: Empty = try await call("respondPermission", Body(entryId: entryId, optionId: optionId))
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Bot.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Bot.swift
index 24f6c96c..278e706f 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/Bot.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Bot.swift
@@ -84,6 +84,8 @@ public struct Bot: Codable, Identifiable, Hashable, Sendable {
public var agentStep: AgentStep?
/// Agents of its chain resting now.
public var resting: [AgentRest] = []
+ /// What it keeps running on the computer. Empty from an older host, and for a group.
+ public var devServers: [DevServer] = []
public var unread: Int
public var lastMessage: String?
public var lastAt: Int64
@@ -152,6 +154,7 @@ extension Bot {
workingChat = try c.decodeIfPresent(String.self, forKey: .workingChat)
agentStep = try? c.decodeIfPresent(AgentStep.self, forKey: .agentStep)
resting = (try? c.decodeIfPresent([AgentRest].self, forKey: .resting)) ?? []
+ devServers = (try? c.decodeIfPresent([DevServer].self, forKey: .devServers)) ?? []
unread = try c.decodeIfPresent(Int.self, forKey: .unread) ?? 0
lastMessage = try c.decodeIfPresent(String.self, forKey: .lastMessage)
lastAt = try c.decodeIfPresent(Int64.self, forKey: .lastAt) ?? createdAt
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/DevServer.swift b/apps/ios/Kit/Sources/CodyncKit/Models/DevServer.swift
new file mode 100644
index 00000000..5ccf35db
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/DevServer.swift
@@ -0,0 +1,107 @@
+import Foundation
+
+/// A program a bot keeps running on the computer: the host runs it (`managed`), or the bot left it running through
+/// its own shell. What each state shows and offers is decided here, the same on Android (`DevServer.kt`).
+public struct DevServer: Codable, Identifiable, Hashable, Sendable {
+ public enum Status: String, Codable, Sendable {
+ case starting, running, stopped, failed
+
+ /// A status a newer host adds reads as stopped, rather than losing the bot's servers.
+ public init(from decoder: Decoder) throws {
+ self = Status(rawValue: try decoder.singleValueContainer().decode(String.self)) ?? .stopped
+ }
+ }
+
+ public struct Port: Codable, Hashable, Sendable {
+ public var port: Int
+ /// Works on the computer running it.
+ public var local: String
+ /// Work from other devices; empty when it listens only on that computer.
+ public var remote: [String]
+ }
+
+ /// What the host can be asked to do with a server. Clients name it and never send a command.
+ public enum Action: String, Sendable {
+ case stop = "devServerStop", restart = "devServerRestart", remove = "devServerRemove"
+ }
+
+ /// What tapping its row does.
+ public enum Tap: Equatable, Sendable {
+ case open(String), logs
+ }
+
+ /// A line of its menu.
+ public enum MenuRow: Equatable, Sendable {
+ case onlyOnComputer, open, copyAddress, logs, restart, start, startedByShell, stop, remove
+ }
+
+ public var id: String
+ public var name: String
+ public var command: String
+ public var folder: String?
+ public var status: Status
+ public var ports: [Port]
+ public var startedAt: Int64?
+ public var exitCode: Int?
+ public var managed: Bool
+}
+
+public extension DevServer {
+ /// Where a phone can reach it while it runs; nil when it listens only on its computer.
+ var remoteAddress: String? {
+ status == .running ? ports.lazy.compactMap(\.remote.first).first : nil
+ }
+
+ /// Its row's value: its ports, or a phrase to look up.
+ var rowValue: String {
+ switch status {
+ case .starting: "Starting"
+ case .stopped: "Stopped"
+ case .failed: "Failed to start"
+ case .running: ports.isEmpty ? "Running" : ports.map { ":\($0.port)" }.joined(separator: " ")
+ }
+ }
+
+ /// Open what can be reached, or read the log of what has no port (a watch build, or one that ended).
+ var tap: Tap? {
+ if let remoteAddress { return .open(remoteAddress) }
+ let listens = status == .running && !ports.isEmpty
+ return managed && !listens ? .logs : nil
+ }
+
+ /// Only what applies. A server the bot started through its shell can only be opened or stopped.
+ var menuRows: [MenuRow] {
+ let live = status == .running || status == .starting
+ var rows: [MenuRow] = []
+ if status == .running, !ports.isEmpty, remoteAddress == nil { rows.append(.onlyOnComputer) }
+ if remoteAddress != nil { rows += [.open, .copyAddress] }
+ if managed {
+ rows.append(.logs)
+ if status != .starting { rows.append(live ? .restart : .start) }
+ } else {
+ rows.append(.startedByShell)
+ }
+ if live { rows.append(.stop) } else if managed { rows.append(.remove) }
+ return rows
+ }
+}
+
+/// What the chat's title shows of a bot's servers: nothing until one starts, or once they've all stopped.
+public enum DevServerSummary: Equatable, Sendable {
+ case none, starting, failed
+ case running(String)
+
+ public init(_ servers: [DevServer]) {
+ let running = servers.filter { $0.status == .running }
+ if let first = running.first(where: { !$0.ports.isEmpty }) ?? running.first {
+ let label = first.ports.first.map { ":\($0.port)" } ?? first.name
+ self = .running(running.count > 1 ? "\(label) +\(running.count - 1)" : label)
+ } else if servers.contains(where: { $0.status == .starting }) {
+ self = .starting
+ } else if servers.contains(where: { $0.status == .failed }) {
+ self = .failed
+ } else {
+ self = .none
+ }
+ }
+}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
index 2f36a89a..cc25ba39 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
@@ -1809,5 +1809,28 @@
"Update Codync on {host}: sending now and taking back need {version} or newer.": "Aktualisiere Codync auf {host}: Jetzt senden und Zurücknehmen brauchen {version} oder neuer.",
"Add {name} to your account first": "Füge {name} zuerst zu deinem Konto hinzu",
"Your phone reaches {name} from anywhere through your account. Adding it also turns this on.": "Dein Telefon erreicht {name} von überall über dein Konto. Beim Hinzufügen wird dies auch aktiviert.",
- "Use your own relay": "Eigenes Relay verwenden"
+ "Use your own relay": "Eigenes Relay verwenden",
+ "Dev servers": "Entwicklungsserver",
+ "Failed to start": "Start fehlgeschlagen",
+ "Stopped": "Gestoppt",
+ "Copy address": "Adresse kopieren",
+ "Logs": "Protokolle",
+ "Restart": "Neu starten",
+ "Start": "Starten",
+ "No output yet": "Noch keine Ausgabe",
+ "Only reachable on the computer": "Nur auf dem Computer erreichbar",
+ "Started through the bot's shell: it stops with the bot": "Über die Shell des Bots gestartet: endet mit dem Bot",
+ "Exit code {code}": "Exit-Code {code}",
+ "More actions for {name}": "Weitere Aktionen für {name}",
+ " ↑↓ scroll · r refresh · esc back": " ↑↓ scrollen · r Aktualisieren · esc zurück",
+ "↑↓ select": "↑↓ wählen",
+ "enter open": "enter öffnen",
+ "enter logs": "enter Protokolle",
+ "c copy": "c kopieren",
+ "l logs": "l Protokolle",
+ "r restart": "r neu starten",
+ "r start": "r Starten",
+ "s stop": "s stoppen",
+ "x remove": "x entfernen",
+ "esc close": "esc schließen"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
index cc18b65c..3b9c85e7 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
@@ -1809,5 +1809,28 @@
"Update Codync on {host}: sending now and taking back need {version} or newer.": "Actualiza Codync en {host}: enviar ahora y retirar necesitan {version} o una versión más reciente.",
"Add {name} to your account first": "Primero añade {name} a tu cuenta",
"Your phone reaches {name} from anywhere through your account. Adding it also turns this on.": "Tu teléfono accede a {name} desde cualquier lugar a través de tu cuenta. Al añadirlo también se activa esta opción.",
- "Use your own relay": "Usar tu propio relé"
+ "Use your own relay": "Usar tu propio relé",
+ "Dev servers": "Servidores de desarrollo",
+ "Failed to start": "Error al iniciar",
+ "Stopped": "Detenido",
+ "Copy address": "Copiar dirección",
+ "Logs": "Registros",
+ "Restart": "Reiniciar",
+ "Start": "Iniciar",
+ "No output yet": "Aún no hay salida",
+ "Only reachable on the computer": "Solo accesible en el ordenador",
+ "Started through the bot's shell: it stops with the bot": "Iniciado desde el shell del bot: se detiene con el bot",
+ "Exit code {code}": "Código de salida {code}",
+ "More actions for {name}": "Más acciones para {name}",
+ " ↑↓ scroll · r refresh · esc back": " ↑↓ desplazar · r Actualizar · esc volver",
+ "↑↓ select": "↑↓ elegir",
+ "enter open": "enter abrir",
+ "enter logs": "enter registros",
+ "c copy": "c copiar",
+ "l logs": "l registros",
+ "r restart": "r reiniciar",
+ "r start": "r Iniciar",
+ "s stop": "s detener",
+ "x remove": "x quitar",
+ "esc close": "esc cerrar"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
index 9ae3579b..ac5d94dd 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
@@ -1809,5 +1809,28 @@
"Update Codync on {host}: sending now and taking back need {version} or newer.": "Mettez à jour Codync sur {host} : l’envoi immédiat et le retrait nécessitent {version} ou une version plus récente.",
"Add {name} to your account first": "Ajoutez d'abord {name} à votre compte",
"Your phone reaches {name} from anywhere through your account. Adding it also turns this on.": "Votre téléphone accède à {name} de partout via votre compte. L'ajouter active aussi cette option.",
- "Use your own relay": "Utiliser votre propre relais"
+ "Use your own relay": "Utiliser votre propre relais",
+ "Dev servers": "Serveurs de développement",
+ "Failed to start": "Échec du démarrage",
+ "Stopped": "Arrêté",
+ "Copy address": "Copier l'adresse",
+ "Logs": "Journaux",
+ "Restart": "Redémarrer",
+ "Start": "Démarrer",
+ "No output yet": "Aucune sortie pour le moment",
+ "Only reachable on the computer": "Accessible uniquement sur l'ordinateur",
+ "Started through the bot's shell: it stops with the bot": "Démarré par le shell du bot : il s'arrête avec le bot",
+ "Exit code {code}": "Code de sortie {code}",
+ "More actions for {name}": "Autres actions pour {name}",
+ " ↑↓ scroll · r refresh · esc back": " ↑↓ défiler · r Actualiser · esc retour",
+ "↑↓ select": "↑↓ choisir",
+ "enter open": "enter ouvrir",
+ "enter logs": "enter journaux",
+ "c copy": "c copier",
+ "l logs": "l journaux",
+ "r restart": "r redémarrer",
+ "r start": "r Démarrer",
+ "s stop": "s arrêter",
+ "x remove": "x retirer",
+ "esc close": "esc fermer"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json
index 3f37e6c8..a0257753 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json
@@ -1809,5 +1809,28 @@
"Update Codync on {host}: sending now and taking back need {version} or newer.": "Aggiorna Codync su {host}: per inviare subito e ritirare un messaggio serve la versione {version} o successiva.",
"Add {name} to your account first": "Prima aggiungi {name} al tuo account",
"Your phone reaches {name} from anywhere through your account. Adding it also turns this on.": "Il telefono raggiunge {name} da ovunque tramite il tuo account. Aggiungendolo attivi anche questa opzione.",
- "Use your own relay": "Usa il tuo relay"
+ "Use your own relay": "Usa il tuo relay",
+ "Dev servers": "Server di sviluppo",
+ "Failed to start": "Avvio non riuscito",
+ "Stopped": "Arrestato",
+ "Copy address": "Copia indirizzo",
+ "Logs": "Log",
+ "Restart": "Riavvia",
+ "Start": "Avvia",
+ "No output yet": "Ancora nessun output",
+ "Only reachable on the computer": "Raggiungibile solo sul computer",
+ "Started through the bot's shell: it stops with the bot": "Avviato dalla shell del bot: si arresta con il bot",
+ "Exit code {code}": "Codice di uscita {code}",
+ "More actions for {name}": "Altre azioni per {name}",
+ " ↑↓ scroll · r refresh · esc back": " ↑↓ scorri · r Aggiorna · esc indietro",
+ "↑↓ select": "↑↓ scegli",
+ "enter open": "enter apri",
+ "enter logs": "enter log",
+ "c copy": "c copia",
+ "l logs": "l log",
+ "r restart": "r riavvia",
+ "r start": "r Avvia",
+ "s stop": "s arresta",
+ "x remove": "x rimuovi",
+ "esc close": "esc chiudi"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
index 638fcb26..29521fe6 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
@@ -1809,5 +1809,28 @@
"Update Codync on {host}: sending now and taking back need {version} or newer.": "{host} の Codync をアップデートしてください。今すぐ送信と取り消しには {version} 以降が必要です。",
"Add {name} to your account first": "先に {name} をアカウントに追加してください",
"Your phone reaches {name} from anywhere through your account. Adding it also turns this on.": "スマートフォンはアカウントを通じてどこからでも {name} にアクセスします。追加すると、この機能もオンになります。",
- "Use your own relay": "自分のリレーを使う"
+ "Use your own relay": "自分のリレーを使う",
+ "Dev servers": "開発サーバー",
+ "Failed to start": "起動に失敗",
+ "Stopped": "停止中",
+ "Copy address": "アドレスをコピー",
+ "Logs": "ログ",
+ "Restart": "再起動",
+ "Start": "起動",
+ "No output yet": "まだ出力はありません",
+ "Only reachable on the computer": "コンピュータ上でのみ開けます",
+ "Started through the bot's shell: it stops with the bot": "bot のシェルから起動したため、bot と一緒に停止します",
+ "Exit code {code}": "終了コード {code}",
+ "More actions for {name}": "{name} のその他の操作",
+ " ↑↓ scroll · r refresh · esc back": " ↑↓ スクロール · r 更新 · esc 戻る",
+ "↑↓ select": "↑↓ 選択",
+ "enter open": "enter 開く",
+ "enter logs": "enter ログ",
+ "c copy": "c コピー",
+ "l logs": "l ログ",
+ "r restart": "r 再起動",
+ "r start": "r 起動",
+ "s stop": "s 停止",
+ "x remove": "x 削除",
+ "esc close": "esc 閉じる"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
index 815dc798..9537d2c5 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
@@ -1809,5 +1809,28 @@
"Update Codync on {host}: sending now and taking back need {version} or newer.": "{host}에서 Codync를 업데이트하세요. 지금 보내기와 취소를 쓰려면 {version} 이상이 필요합니다.",
"Add {name} to your account first": "먼저 {name}을(를) 계정에 추가하세요",
"Your phone reaches {name} from anywhere through your account. Adding it also turns this on.": "휴대폰은 계정을 통해 어디서나 {name}에 접근합니다. 추가하면 이 기능도 켜집니다.",
- "Use your own relay": "내 릴레이 사용"
+ "Use your own relay": "내 릴레이 사용",
+ "Dev servers": "개발 서버",
+ "Failed to start": "시작 실패",
+ "Stopped": "중지됨",
+ "Copy address": "주소 복사",
+ "Logs": "로그",
+ "Restart": "다시 시작",
+ "Start": "시작",
+ "No output yet": "아직 출력이 없습니다",
+ "Only reachable on the computer": "컴퓨터에서만 열 수 있습니다",
+ "Started through the bot's shell: it stops with the bot": "bot의 셸에서 시작되어 bot과 함께 중지됩니다",
+ "Exit code {code}": "종료 코드 {code}",
+ "More actions for {name}": "{name} 추가 작업",
+ " ↑↓ scroll · r refresh · esc back": " ↑↓ 스크롤 · r 새로고침 · esc 뒤로",
+ "↑↓ select": "↑↓ 선택",
+ "enter open": "enter 열기",
+ "enter logs": "enter 로그",
+ "c copy": "c 복사",
+ "l logs": "l 로그",
+ "r restart": "r 다시 시작",
+ "r start": "r 시작",
+ "s stop": "s 중지",
+ "x remove": "x 제거",
+ "esc close": "esc 닫기"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json
index c08d64b4..a32f36aa 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json
@@ -1809,5 +1809,28 @@
"Update Codync on {host}: sending now and taking back need {version} or newer.": "Atualize o Codync em {host}: enviar agora e retirar precisam da versão {version} ou mais recente.",
"Add {name} to your account first": "Primeiro adicione {name} à sua conta",
"Your phone reaches {name} from anywhere through your account. Adding it also turns this on.": "Seu telefone acessa {name} de qualquer lugar pela sua conta. Ao adicionar, isto também é ativado.",
- "Use your own relay": "Usar seu próprio relay"
+ "Use your own relay": "Usar seu próprio relay",
+ "Dev servers": "Servidores de desenvolvimento",
+ "Failed to start": "Falha ao iniciar",
+ "Stopped": "Parado",
+ "Copy address": "Copiar endereço",
+ "Logs": "Registros",
+ "Restart": "Reiniciar",
+ "Start": "Iniciar",
+ "No output yet": "Ainda sem saída",
+ "Only reachable on the computer": "Acessível apenas no computador",
+ "Started through the bot's shell: it stops with the bot": "Iniciado pelo shell do bot: para junto com o bot",
+ "Exit code {code}": "Código de saída {code}",
+ "More actions for {name}": "Mais ações para {name}",
+ " ↑↓ scroll · r refresh · esc back": " ↑↓ rolar · r Atualizar · esc voltar",
+ "↑↓ select": "↑↓ escolher",
+ "enter open": "enter abrir",
+ "enter logs": "enter registros",
+ "c copy": "c copiar",
+ "l logs": "l registros",
+ "r restart": "r reiniciar",
+ "r start": "r Iniciar",
+ "s stop": "s parar",
+ "x remove": "x remover",
+ "esc close": "esc fechar"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json
index f05cc0f7..95239248 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json
@@ -1809,5 +1809,28 @@
"Update Codync on {host}: sending now and taking back need {version} or newer.": "Обновите Codync на {host}: отправке сейчас и отзыву нужна версия {version} или новее.",
"Add {name} to your account first": "Сначала добавьте {name} в аккаунт",
"Your phone reaches {name} from anywhere through your account. Adding it also turns this on.": "Телефон подключается к {name} из любой точки через ваш аккаунт. При добавлении эта функция тоже включится.",
- "Use your own relay": "Использовать свой ретранслятор"
+ "Use your own relay": "Использовать свой ретранслятор",
+ "Dev servers": "Серверы разработки",
+ "Failed to start": "Не удалось запустить",
+ "Stopped": "Остановлен",
+ "Copy address": "Скопировать адрес",
+ "Logs": "Журнал",
+ "Restart": "Перезапустить",
+ "Start": "Запустить",
+ "No output yet": "Вывода пока нет",
+ "Only reachable on the computer": "Доступен только на компьютере",
+ "Started through the bot's shell: it stops with the bot": "Запущен из оболочки бота: остановится вместе с ботом",
+ "Exit code {code}": "Код выхода {code}",
+ "More actions for {name}": "Другие действия: {name}",
+ " ↑↓ scroll · r refresh · esc back": " ↑↓ прокрутка · r Обновить · esc назад",
+ "↑↓ select": "↑↓ выбор",
+ "enter open": "enter открыть",
+ "enter logs": "enter журнал",
+ "c copy": "c копировать",
+ "l logs": "l журнал",
+ "r restart": "r перезапуск",
+ "r start": "r Запустить",
+ "s stop": "s стоп",
+ "x remove": "x убрать",
+ "esc close": "esc закрыть"
}
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 2f90c937..3a44fc79 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
@@ -1809,5 +1809,28 @@
"Update Codync on {host}: sending now and taking back need {version} or newer.": "请在 {host} 上更新 Codync:立即发送和收回需要 {version} 或更高版本。",
"Add {name} to your account first": "请先将 {name} 加入你的账户",
"Your phone reaches {name} from anywhere through your account. Adding it also turns this on.": "你的手机会通过账户从任何地方连接 {name}。加入后也会开启此功能。",
- "Use your own relay": "使用自己的中继"
+ "Use your own relay": "使用自己的中继",
+ "Dev servers": "Dev servers",
+ "Failed to start": "启动失败",
+ "Stopped": "已停止",
+ "Copy address": "复制网址",
+ "Logs": "日志",
+ "Restart": "重启",
+ "Start": "启动",
+ "No output yet": "还没有输出",
+ "Only reachable on the computer": "只能在电脑上打开",
+ "Started through the bot's shell: it stops with the bot": "不是通过 Codync 启动,会随 bot 一起停止",
+ "Exit code {code}": "退出代码 {code}",
+ "More actions for {name}": "{name} 的更多操作",
+ " ↑↓ scroll · r refresh · esc back": " ↑↓ 滚动 · r 刷新 · esc 返回",
+ "↑↓ select": "↑↓ 选择",
+ "enter open": "enter 打开",
+ "enter logs": "enter 日志",
+ "c copy": "c 复制",
+ "l logs": "l 日志",
+ "r restart": "r 重启",
+ "r start": "r 启动",
+ "s stop": "s 停止",
+ "x remove": "x 移除",
+ "esc close": "esc 关闭"
}
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 85090ea7..ff638eaa 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
@@ -1809,5 +1809,28 @@
"Update Codync on {host}: sending now and taking back need {version} or newer.": "請在 {host} 上更新 Codync:立即送出和收回需要 {version} 或更新的版本。",
"Add {name} to your account first": "請先將 {name} 加入你的賬戶",
"Your phone reaches {name} from anywhere through your account. Adding it also turns this on.": "你的手機會透過賬戶從任何地方連到 {name}。加入後也會開啟這個功能。",
- "Use your own relay": "使用自己的中繼"
+ "Use your own relay": "使用自己的中繼",
+ "Dev servers": "Dev servers",
+ "Failed to start": "啟動失敗",
+ "Stopped": "已停止",
+ "Copy address": "複製網址",
+ "Logs": "記錄",
+ "Restart": "重啟",
+ "Start": "啟動",
+ "No output yet": "還沒有輸出",
+ "Only reachable on the computer": "只能在電腦上開啟",
+ "Started through the bot's shell: it stops with the bot": "不是透過 Codync 啟動,會跟著 bot 一起停",
+ "Exit code {code}": "結束代碼 {code}",
+ "More actions for {name}": "{name} 的更多動作",
+ " ↑↓ scroll · r refresh · esc back": " ↑↓ 捲動 · r 重新整理 · esc 返回",
+ "↑↓ select": "↑↓ 選擇",
+ "enter open": "enter 開啟",
+ "enter logs": "enter 記錄",
+ "c copy": "c 複製",
+ "l logs": "l 記錄",
+ "r restart": "r 重啟",
+ "r start": "r 啟動",
+ "s stop": "s 停止",
+ "x remove": "x 移除",
+ "esc close": "esc 關閉"
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/BotDetailsView.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/BotDetailsView.swift
index e0f0f7f1..d892a7ef 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Bots/BotDetailsView.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/BotDetailsView.swift
@@ -122,6 +122,7 @@ struct BotDetailsView: View {
switch tab {
case .details:
VStack(alignment: .leading, spacing: 28) {
+ if let bot, !bot.devServers.isEmpty { DevServersSection(bot: bot) }
if let draft = Binding($draft) {
BotSettingsForm(draft: draft, error: saveError, scrolls: false, part: .often)
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/DevServersSection.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/DevServersSection.swift
new file mode 100644
index 00000000..b083db1c
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/DevServersSection.swift
@@ -0,0 +1,178 @@
+import CodyncKit
+import SwiftUI
+
+/// What a bot keeps running: a row is its name and ports, tapping it opens it, the rest is behind `⋯`.
+struct DevServersSection: View {
+ let bot: Bot
+ @State private var logs: DevServer?
+
+ var body: some View {
+ CardSection("Dev servers") {
+ ForEach(bot.devServers) { server in
+ DevServerRow(botId: bot.id, server: server) { logs = server }
+ }
+ }
+ .codyncSheet(item: $logs) { DevServerLogsView(botId: bot.id, server: $0).id($0.id) }
+ }
+}
+
+private struct DevServerRow: View {
+ let botId: String
+ let server: DevServer
+ let showLogs: () -> Void
+ @Environment(BotStore.self) private var model
+ @Environment(\.openURL) private var openURL
+
+ var body: some View {
+ HStack(spacing: 8) {
+ switch server.tap {
+ case let .open(address): Button { open(address) } label: { line }.buttonStyle(.plain)
+ case .logs: Button(action: showLogs) { line }.buttonStyle(.plain)
+ case nil: line
+ }
+ DropdownMenu(items: menuItems) {
+ Image(systemName: "ellipsis")
+ .font(.system(size: 15, weight: .medium))
+ .foregroundStyle(Palette.secondary)
+ .frame(width: 44, height: 44)
+ .contentShape(Rectangle())
+ }
+ .accessibilityLabel(L10n.tr("More actions for {name}").replacingOccurrences(of: "{name}", with: server.name))
+ // A 44 pt target in a row of the card's height, its glyph near the card's edge.
+ .padding(.vertical, -6)
+ .padding(.trailing, -12)
+ }
+ }
+
+ private var line: some View {
+ HStack(spacing: 8) {
+ Text(server.name)
+ .foregroundStyle(Palette.text)
+ .lineLimit(1)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ if server.status == .starting { Spinner(size: 11) }
+ Text(L10n.tr(server.rowValue))
+ .monospacedDigit()
+ .foregroundStyle(server.status == .failed ? Palette.danger : Palette.secondary)
+ .lineLimit(1)
+ // A long name gives way, never the ports.
+ .fixedSize()
+ }
+ .contentShape(Rectangle())
+ }
+
+ private func menuItems() -> [MenuItem] {
+ server.menuRows.enumerated().map { index, row in item(row, divider: index > 0) }
+ }
+
+ private func item(_ row: DevServer.MenuRow, divider: Bool) -> MenuItem {
+ switch row {
+ case .onlyOnComputer: MenuItem("Only reachable on the computer", enabled: false) {}
+ case .startedByShell: MenuItem("Started through the bot's shell: it stops with the bot", enabled: false) {}
+ case .open: MenuItem("Open", icon: "arrow.up.right") { if let address = server.remoteAddress { open(address) } }
+ case .copyAddress: MenuItem("Copy address", icon: "doc.on.doc") { copyAddress() }
+ case .logs: MenuItem("Logs", icon: "doc.text", action: showLogs)
+ case .restart: MenuItem("Restart", icon: "arrow.clockwise") { act(.restart) }
+ case .start: MenuItem("Start", icon: "arrow.clockwise") { act(.restart) }
+ case .stop: MenuItem("Stop", icon: "stop.fill", destructive: true, divider: divider) { act(.stop) }
+ case .remove: MenuItem("Remove", icon: "trash", destructive: true, divider: divider) { act(.remove) }
+ }
+ }
+
+ private func open(_ address: String) {
+ guard let url = URL(string: address) else { return }
+ Analytics.shared.capture(.devServerAction(.open))
+ openURL(url)
+ }
+
+ private func copyAddress() {
+ Analytics.shared.capture(.devServerAction(.copy))
+ Pasteboard.copy(server.remoteAddress)
+ }
+
+ private func act(_ action: DevServer.Action) {
+ model.devServerAction(action, botId: botId, id: server.id)
+ }
+}
+
+/// A server's recent output, to read.
+private struct DevServerLogsView: View {
+ private enum Output {
+ case loading, text(String), failed(String)
+ }
+
+ let botId: String
+ let server: DevServer
+ @Environment(BotStore.self) private var model
+ @State private var output = Output.loading
+ /// Moves to read the logs again.
+ @State private var reads = 0
+
+ var body: some View {
+ VStack(spacing: 0) {
+ ModalHeader {
+ VStack(alignment: .leading, spacing: 1) {
+ Text(server.name)
+ Text(detail)
+ .font(.system(size: 11, weight: .regular, design: .monospaced))
+ .foregroundStyle(Palette.secondary)
+ .truncationMode(.middle)
+ }
+ } trailing: {
+ IconButton("Refresh", systemImage: "arrow.clockwise") { reads += 1 }
+ }
+ content.frame(maxWidth: .infinity, maxHeight: .infinity)
+ }
+ .background(Palette.background)
+ .task(id: reads) { await read() }
+ }
+
+ /// The command, and how it ended if it failed.
+ private var detail: String {
+ guard server.status == .failed, let code = server.exitCode else { return server.command }
+ return "\(server.command) · \(L10n.tr("Exit code {code}").replacingOccurrences(of: "{code}", with: "\(code)"))"
+ }
+
+ @ViewBuilder private var content: some View {
+ switch output {
+ case .loading:
+ Spinner()
+ case let .text(text) where text.isEmpty:
+ Text(L10n.tr("No output yet")).foregroundStyle(Palette.secondary)
+ case let .text(text):
+ ScrollView {
+ Text(text)
+ .font(.system(size: 12, design: .monospaced))
+ .foregroundStyle(Palette.text)
+ .textSelection(.enabled)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, 20)
+ .padding(.bottom, 20)
+ }
+ case let .failed(error):
+ VStack(spacing: 12) {
+ Text(L10n.tr(error))
+ .foregroundStyle(Palette.danger)
+ .multilineTextAlignment(.center)
+ .textSelection(.enabled)
+ Button(L10n.tr("Try again")) {
+ output = .loading
+ reads += 1
+ }
+ .buttonStyle(.secondary)
+ }
+ .padding(20)
+ }
+ }
+
+ private func read() async {
+ let result: Output
+ do {
+ result = .text(try await model.devServerLogs(botId: botId, id: server.id))
+ } catch {
+ result = .failed(error.localizedDescription)
+ }
+ // A newer read, or the sheet closing, took over from this one.
+ if !Task.isCancelled { output = result }
+ }
+}
diff --git a/apps/ios/Kit/Sources/CodyncUI/MenuItem.swift b/apps/ios/Kit/Sources/CodyncUI/MenuItem.swift
index 6f209a2e..d82c0367 100644
--- a/apps/ios/Kit/Sources/CodyncUI/MenuItem.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/MenuItem.swift
@@ -13,13 +13,15 @@ public struct MenuItem: Identifiable {
public var divider: Bool
/// Shows `title` as it is, never translated: a name the user gave (a section's).
public var verbatim: Bool
+ /// False for a line that only says something: it shows dimmed and can't be picked.
+ public var enabled: Bool
/// The rows of the submenu this row opens ("Move to section ▸") instead of running `action`;
/// one level deep: a row inside it can't open another.
public var submenu: [MenuItem] = []
public var action: () -> Void
public init(_ title: String, icon: String? = nil, image: Image? = nil, selected: Bool? = nil, destructive: Bool = false,
- divider: Bool = false, verbatim: Bool = false, action: @escaping () -> Void) {
+ divider: Bool = false, verbatim: Bool = false, enabled: Bool = true, action: @escaping () -> Void) {
self.title = title
self.icon = icon
self.image = image
@@ -27,6 +29,7 @@ public struct MenuItem: Identifiable {
self.destructive = destructive
self.divider = divider
self.verbatim = verbatim
+ self.enabled = enabled
self.action = action
}
@@ -109,6 +112,7 @@ private struct ContextActions: ViewModifier {
Toggle(isOn: Binding(get: { selected }, set: { _ in action() })) { menuLabel(item) }
} else {
Button(role: role, action: item.action) { menuLabel(item) }
+ .disabled(!item.enabled)
}
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift
index 5f2216e4..9274908d 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift
@@ -85,6 +85,17 @@ extension BotStore {
/// The bot's own agent again, off the fallback it runs on.
public func switchBack(_ botId: String) { perform(replay: true) { try await $0.switchBack(botId) } }
+ // MARK: dev servers
+
+ /// A refusal shows; the bot's next update shows the rest.
+ public func devServerAction(_ action: DevServer.Action, botId: String, id: String) {
+ perform { try await $0.devServer(action, botId: botId, id: id) }
+ }
+
+ func devServerLogs(botId: String, id: String) async throws -> String {
+ try await withLink(replay: true) { try await $0.devServerLogs(botId: botId, id: id) }
+ }
+
// MARK: remote screen
/// Takes control from bots (they can still look) or hands it back.
diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift
index 11f9e085..0babc053 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift
@@ -140,17 +140,38 @@ public struct ThreadView: View {
}
.frame(width: 12)
.accessibilityHidden(true)
- Text(L10n.tr(model.connectionLabel))
- .lineLimit(1)
- .truncationMode(.middle)
+ HStack(spacing: 3) {
+ Text(L10n.tr(model.connectionLabel))
+ .lineLimit(1)
+ .truncationMode(.middle)
+ if let devServerLabel {
+ Text("·")
+ if devServerSummary == .starting { Spinner(size: 8) }
+ Text(devServerLabel)
+ .monospacedDigit()
+ .lineLimit(1)
+ .foregroundStyle(devServerSummary == .failed ? Palette.danger : Palette.secondary)
+ }
+ }
}
.font(.system(size: 10, weight: .medium))
.foregroundStyle(Palette.secondary)
.accessibilityElement(children: .ignore)
- .accessibilityLabel("\(model.hostName), \(L10n.tr(connectionDescription))")
+ .accessibilityLabel([model.hostName, L10n.tr(connectionDescription), devServerLabel].compactMap(\.self).joined(separator: ", "))
.help("\(model.hostName) · \(L10n.tr(connectionDescription))")
}
+ private var devServerSummary: DevServerSummary { DevServerSummary(bot?.devServers ?? []) }
+
+ private var devServerLabel: String? {
+ switch devServerSummary {
+ case .none: nil
+ case .starting: L10n.tr("Starting")
+ case .failed: L10n.tr("Failed to start")
+ case let .running(text): text
+ }
+ }
+
private var connectionSymbol: String {
guard model.connection == .online else { return "wifi.slash" }
switch model.hostRoute {
@@ -383,7 +404,9 @@ extension ThreadView {
ToolbarItem(placement: .principal) {
VStack(spacing: 0) {
header
- connectionSubtitle
+ // The port shows here, so a tap on it opens the details too.
+ Button(action: openDetails) { connectionSubtitle }
+ .buttonStyle(.plain)
}
}
if model.screen != nil {
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/DevServerTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/DevServerTests.swift
new file mode 100644
index 00000000..4613540d
--- /dev/null
+++ b/apps/ios/Kit/Tests/CodyncKitTests/DevServerTests.swift
@@ -0,0 +1,92 @@
+import Foundation
+import Testing
+@testable import CodyncKit
+
+private func server(_ status: DevServer.Status = .running, name: String = "web", ports: [DevServer.Port] = [],
+ managed: Bool = true) -> DevServer {
+ DevServer(id: "a", name: name, command: "npm run dev", folder: "/site", status: status, ports: ports, startedAt: 1,
+ exitCode: nil, managed: managed)
+}
+
+private func port(_ number: Int, remote: [String] = []) -> DevServer.Port {
+ DevServer.Port(port: number, local: "http://localhost:\(number)", remote: remote)
+}
+
+private let reachable = port(5173, remote: ["http://192.168.1.20:5173"])
+
+@Suite struct DevServerTests {
+ @Test func theTitleShowsNothingWithoutALiveServer() {
+ #expect(DevServerSummary([]) == .none)
+ #expect(DevServerSummary([server(.stopped)]) == .none)
+ }
+
+ @Test func theTitleShowsThePortAndHowManyMoreRun() {
+ #expect(DevServerSummary([server(ports: [port(5173)])]) == .running(":5173"))
+ let three = [server(name: "watch"), server(ports: [port(5173)]), server(ports: [port(8787)])]
+ #expect(DevServerSummary(three) == .running(":5173 +2"))
+ }
+
+ @Test func theTitleNamesAServerWithoutAPort() {
+ #expect(DevServerSummary([server(name: "watch")]) == .running("watch"))
+ }
+
+ @Test func runningOutranksStartingWhichOutranksFailed() {
+ #expect(DevServerSummary([server(.failed), server(ports: [port(1)])]) == .running(":1"))
+ #expect(DevServerSummary([server(.failed), server(.starting)]) == .starting)
+ #expect(DevServerSummary([server(.failed), server(.stopped)]) == .failed)
+ }
+
+ @Test func aRowSaysItsPortsOrItsState() {
+ #expect(server(ports: [port(5173), port(24678)]).rowValue == ":5173 :24678")
+ #expect(server().rowValue == "Running")
+ #expect(server(.starting).rowValue == "Starting")
+ #expect(server(.stopped).rowValue == "Stopped")
+ #expect(server(.failed).rowValue == "Failed to start")
+ }
+
+ @Test func tappingOpensWhatAPhoneCanReachAndLogsWhatEnded() {
+ #expect(server(ports: [reachable]).tap == .open("http://192.168.1.20:5173"))
+ // The first port listens only on the computer; the second doesn't.
+ #expect(server(ports: [port(1), reachable]).tap == .open("http://192.168.1.20:5173"))
+ #expect(server(ports: [port(5173)]).tap == nil)
+ #expect(server().tap == .logs)
+ #expect(server(.starting).tap == .logs)
+ #expect(server(.stopped).tap == .logs)
+ #expect(server(.failed).tap == .logs)
+ #expect(server(.stopped, managed: false).tap == nil)
+ // A stopped server's last address is no longer an address.
+ #expect(server(.stopped, ports: [reachable]).tap == .logs)
+ }
+
+ @Test func theMenuOffersOnlyWhatApplies() {
+ #expect(server(ports: [reachable]).menuRows == [.open, .copyAddress, .logs, .restart, .stop])
+ #expect(server(ports: [port(5173)]).menuRows == [.onlyOnComputer, .logs, .restart, .stop])
+ #expect(server().menuRows == [.logs, .restart, .stop])
+ #expect(server(.starting).menuRows == [.logs, .stop])
+ #expect(server(.stopped).menuRows == [.logs, .start, .remove])
+ #expect(server(.failed).menuRows == [.logs, .start, .remove])
+ }
+
+ @Test func aServerLeftInTheBotsShellCanOnlyBeOpenedOrStopped() {
+ #expect(server(ports: [reachable], managed: false).menuRows == [.open, .copyAddress, .startedByShell, .stop])
+ #expect(server(ports: [port(5173)], managed: false).menuRows == [.onlyOnComputer, .startedByShell, .stop])
+ }
+
+ @Test func aBotDecodesItsServersAndAnOlderHostsWithoutThem() throws {
+ let json = """
+ {"id":"b","devServers":[{"id":"a","name":"web","command":"npm run dev","folder":null,"status":"running",
+ "ports":[{"port":5173,"local":"http://localhost:5173","remote":["http://192.168.1.20:5173"]}],
+ "startedAt":null,"exitCode":null,"managed":true},
+ {"id":"c","name":"w","command":"w","status":"sleeping","ports":[],"managed":false}]}
+ """
+ let bot = try JSONDecoder().decode(Bot.self, from: Data(json.utf8))
+ #expect(bot.devServers.first?.remoteAddress == "http://192.168.1.20:5173")
+ #expect(bot.devServers.last?.status == .stopped)
+ #expect(try JSONDecoder().decode(Bot.self, from: Data(#"{"id":"b"}"#.utf8)).devServers.isEmpty)
+ }
+
+ @Test func theEventNamesWhatWasDoneAndNothingElse() {
+ #expect(AnalyticsEvent.devServerAction(.open).name == "dev_server_action")
+ #expect(AnalyticsEvent.devServerAction(.copy).properties == ["action": .string("copy")])
+ }
+}
diff --git a/apps/maestro/dev-servers.js b/apps/maestro/dev-servers.js
new file mode 100644
index 00000000..e06c23e6
--- /dev/null
+++ b/apps/maestro/dev-servers.js
@@ -0,0 +1,28 @@
+// Makes the bot `dev-servers.yaml` opens, on the host the phone is paired with (HOST_PORT and HOST_TOKEN, passed with
+// `-e`), with a server listening only on the computer and one whose command fails. The tool's call comes through the
+// host's API, so no agent or model runs. `CLEANUP`, when the flow completes, deletes the bot again.
+const api = (method, body) => {
+ const res = http.post(`http://127.0.0.1:${HOST_PORT}/api/${method}`, {
+ headers: { Authorization: `Bearer ${HOST_TOKEN}`, 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ })
+ if (res.status !== 200) throw new Error(`${method}: ${res.status} ${res.body}`)
+ return json(res.body)
+}
+
+if (typeof CLEANUP !== 'undefined') {
+ if (output.bot) api('deleteBot', { botId: output.bot.id })
+} else {
+ const name = `Dev server check ${Math.random().toString(36).slice(2, 6)}`
+ const bot = api('createBot', {
+ name, backend: 'custom', command: 'unused', connectors: [], skills: [], permission: 'auto', notify: false,
+ }).bot
+ const start = (server, command) =>
+ api('chatCall', { botId: bot.id, name: 'start_dev_server', arguments: { name: server, command } })
+ // Below where the system hands out ports, so it isn't taken for one of its own.
+ const port = 20000 + Math.floor(Math.random() * 10000)
+ start('docs', 'echo no such script; exit 3')
+ start('web', `python3 -m http.server ${port} --bind 127.0.0.1`)
+ output.bot = { name, id: bot.id }
+ output.port = String(port)
+}
diff --git a/apps/maestro/dev-servers.yaml b/apps/maestro/dev-servers.yaml
new file mode 100644
index 00000000..3a5e21bc
--- /dev/null
+++ b/apps/maestro/dev-servers.yaml
@@ -0,0 +1,70 @@
+# A bot's dev servers on the phones: the port under the chat's title, then their section first in the bot's details, a
+# row's ⋯ menu with what applies, the logs sheet, and stop, start and remove. The phone must already be signed in and
+# paired with the host (a worktree's sandbox, docs/guides/dev-app.md#worktree-sandboxes), so run it apart from `welcome`,
+# whose clearState undoes that; the flow makes its own bot there:
+# maestro --device "<simulator udid>,<adb serial>" test --shard-all 2 --include-tags dev-servers \
+# -e HOST_PORT=<sandbox port> -e HOST_TOKEN="$(cat ~/.codync-dev-<sandbox name>/token)" apps/maestro
+appId: com.pokai.Codync.ios.dev
+tags:
+ - dev-servers
+onFlowComplete:
+ - runScript:
+ file: dev-servers.js
+ env:
+ CLEANUP: "true"
+---
+- runScript: dev-servers.js
+- runFlow:
+ when:
+ platform: iOS
+ commands:
+ - launchApp:
+ appId: com.pokai.Codync.ios.dev
+ arguments:
+ "-reviewInvitationOff": true
+- runFlow:
+ when:
+ platform: Android
+ commands:
+ - launchApp:
+ appId: com.pokai.Codync.android.dev
+- tapOn: ${output.bot.name}
+- assertVisible: ".*:${output.port}.*"
+- takeScreenshot: dev-servers-title
+- tapOn: ".*:${output.port}.*"
+- assertVisible: "Dev servers"
+- assertVisible: "web"
+- assertVisible: "docs"
+- assertVisible: "Failed to start"
+- takeScreenshot: dev-servers-details
+# It listens only on the computer: the menu says so, and offers no way to open it.
+- tapOn: "More actions for web"
+- assertVisible: "Only reachable on the computer"
+- assertNotVisible: "Copy address"
+- assertVisible: "Restart"
+- tapOn: "Logs"
+- assertVisible: ".*-m http.server ${output.port}.*"
+- takeScreenshot: dev-servers-logs
+- tapOn: "Close"
+- tapOn: "More actions for web"
+- tapOn: "Stop"
+- assertVisible: "Stopped"
+- assertNotVisible: ".*:${output.port}.*"
+- tapOn: "More actions for web"
+- tapOn: "Start"
+- assertVisible: ":${output.port}"
+- tapOn: "More actions for web"
+- tapOn: "Stop"
+- assertVisible: "Stopped"
+- tapOn: "More actions for web"
+- tapOn: "Remove"
+- assertNotVisible: "web"
+# One that failed: a tap on its row reads why.
+- tapOn: "docs"
+- assertVisible: ".*Exit code 3"
+- assertVisible: "no such script"
+- tapOn: "Close"
+- tapOn: "More actions for docs"
+- assertVisible: "Start"
+- tapOn: "Remove"
+- assertNotVisible: "Dev servers"
diff --git a/docs/README.md b/docs/README.md
index 7e0a570d..72cf17da 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -44,6 +44,7 @@ Source review, a passing build, local integration tests and production acceptanc
- [Bot import](features/bot-import.md) (agents from a Grok Bot export file become bots)
- [Agent fallbacks](features/agent-fallback.md) (the next agent carries a turn on when the bot's own runs out of usage)
- [Routines](features/routines.md)
+- [Dev servers](features/dev-servers.md) (programs a bot keeps running: the host runs them, every client shows their port)
- [Voice calls](features/voice-call.md)
- [iOS Shortcuts](features/ios-shortcuts.md)
- [File attachments](features/file-attachments.md)
diff --git a/docs/architecture/conversation-runtime.md b/docs/architecture/conversation-runtime.md
index 43ffa55a..2c04a2be 100644
--- a/docs/architecture/conversation-runtime.md
+++ b/docs/architecture/conversation-runtime.md
@@ -2,7 +2,7 @@
- **Chat ≠ session**: a bot is one endless transcript (SQLite `entries`, ordered by `seq`); the ACP session underneath is reopened with `session/load`, or `session/resume` on an agent without it (DeepSeek Harness), or replaced by *New session*. The chat never says when the session underneath changes (New session, an agent, model or folder change, a failed resume); only a rollover's handoff card mentions a fresh conversation ([context and memory](../features/context-and-memory.md)), and one line says when another agent takes over or the bot's own comes back.
- **Agent fallbacks**: when the bot's agent can't answer (out of usage, rate limited, signed out, won't start), the next agent in its list carries the same turn on, told what the last one did; each agent keeps its own session, parked while another answers, and agents rest computer-wide until they recover: [docs/features/agent-fallback.md](../features/agent-fallback.md).
-- **Agent processes**: a bot's agent starts on its first message and keeps its sessions loaded between messages. A session unused for 30 minutes is closed (agents with `session/close`; a routine run's session as soon as the run ends), and once all of them are idle the agent stops with its process group, as it does right after a routine run when no other session is open; the next message starts it again and reopens the session (`agent/bot/lifecycle.rs`). Nothing is released mid-turn or while a queue, approval or request waits. Agents that can't reopen sessions stay, and so do agents with something running detached in a session of its own, like a dev server from Claude Code's shell tool (stopping the agent would orphan it); MCP servers don't count, even in a process group of their own as Codex starts them. Codex keeps a closed session's MCP servers until the agent stops, and codex-acp never closes the thread it titles each new session in ([codex-acp#628](https://github.com/agentclientprotocol/codex-acp/issues/628)), so on Codex only the agent stopping gives them back. Windows has no sessions to tell a dev server from an MCP server, so there the agent's job is checked instead: anything that isn't the agent or Codync's MCP servers holds it, which also keeps an agent with an MCP server from the user's own config or a shell it keeps open, and one with no MCP server left, whose own last process can't be told from a dev server (`agent/bot/background_work.rs`).
+- **Agent processes**: a bot's agent starts on its first message and keeps its sessions loaded between messages. A session unused for 30 minutes is closed (agents with `session/close`; a routine run's session as soon as the run ends), and once all of them are idle the agent stops with its process group, as it does right after a routine run when no other session is open; the next message starts it again and reopens the session (`agent/bot/lifecycle.rs`). Nothing is released mid-turn or while a queue, approval or request waits. Agents that can't reopen sessions stay, and so do agents with something running detached in a session of its own, like a dev server from Claude Code's shell tool (stopping the agent would orphan it); MCP servers don't count, even in a process group of their own as Codex starts them. Codex keeps a closed session's MCP servers until the agent stops, and codex-acp never closes the thread it titles each new session in ([codex-acp#628](https://github.com/agentclientprotocol/codex-acp/issues/628)), so on Codex only the agent stopping gives them back. Windows has no sessions to tell a dev server from an MCP server, so there the agent's job is checked instead: anything that isn't the agent or Codync's MCP servers holds it, which also keeps an agent with an MCP server from the user's own config or a shell it keeps open, and one with no MCP server left, whose own last process can't be told from a dev server (`agent/bot/background_work.rs`). A dev server the bot starts with `start_dev_server` belongs to the host and doesn't hold the agent ([dev servers](../features/dev-servers.md)).
- **Group chats and replies** are host features every client drives through the same methods (`send` with `replyTo`, `createBot {kind: group}`); clients never route, parse mentions or build quotes themselves. A group is a roster row whose members answer in their own sessions (Grok Bot's room turns); a reply stays in its chat and session, its quote read before its text: [docs/features/groups-and-replies.md](../features/groups-and-replies.md).
- **A session that fails** with an internal error its agent gives no category (JSON-RPC `-32603` without `data.errorKind`) is closed right after the turn, when the agent can close and reopen sessions: Claude's adapter otherwise answers every later prompt on it with "The Claude Agent session has ended". The next message reopens it and the conversation carries on (`acp::may_end_session`).
- **Lead bot**: the host makes the first one per computer (`chat/lead.rs`), and the user may pick another (`setLead`) or delete it; on top of every roster, never hidden; its instructions ask for initiative, the *Check in* routine made with the first runs twice a day, and it opens a call with a turn of its own (`Cmd::Prompt`, no user message): [docs/features/lead-bot.md](../features/lead-bot.md).
diff --git a/docs/architecture/file-structure.md b/docs/architecture/file-structure.md
index 1d8b44be..49978fd5 100644
--- a/docs/architecture/file-structure.md
+++ b/docs/architecture/file-structure.md
@@ -96,6 +96,7 @@ Codync/
| Compaction timing and rollover | `host/src/agent/bot/compaction.rs`, the handoff card in `host/src/chat/handoff.rs`; the rules in `codync-mem`'s `compaction.rs` |
| Group room turns / bot-to-bot requests | `host/src/chat/group.rs` / `team.rs` |
| Voice calls (the call, the voice's instructions and tools, transcripts, call lines) | `host/src/chat/calls/` (`mod.rs`, `context.rs`, `project.rs` the git state, `tools.rs`, `announce.rs` what the voice hears while the call lasts, `speech.rs` text as a voice says it); the user's messages it relays go through `host/src/chat/messages.rs` like typed ones; clients' `CallLink` (iPhone `CodyncUI/Call/CallLink.swift`, desktop `views/call/call-link.ts`, Android `core/Calls.kt` + `HostCallLink.kt`) and call rows (`CallRows`); the call on the iPhone's Lock Screen (`CodyncUI/Call/CallActivity.swift`, the Live Activity) and Android's call notification (`VoiceService.kt`) |
+| Dev servers (programs a bot keeps running) | `host/src/dev_servers/` (`run.rs` starting and stopping, `scan.rs` restoring and reading ports, `ports.rs`, `tools.rs` the bot's tools, `logs.rs`, `detected.rs` what a bot left running through its shell, `platform.rs`); desktop `views/thread/DevServersSection.tsx` (+ `src/shared/dev-servers.ts`); iPhone `CodyncUI/Bots/DevServersSection.swift`; Android `DevServersSection.kt`; terminal `host/src/tui/manage/dev_servers.rs` and `view/dev_servers.rs` |
| Team management (bots creating and changing bots) | `host/src/chat/manage.rs`, its approval card (`Cmd::Approve`) in `agent/bot/updates.rs` |
| codync-network (your computers' network) | `host/crates/network` (the crate: roster, letters, reach, budgets, `rules.rs`; `node/endpoint.rs` for where a computer is), `host/src/network/` (one node per network in `mod.rs`, the saved networks in `saved.rs`, its bots' address names in `handles.rs`, the `network*` methods, `networkView` and the `network` event in `api.rs`), `host/src/network_cli.rs`; across-computer bot requests in `host/src/chat/team/remote.rs`; desktop `apps/desktop/src/renderer/views/settings/NetworkSection.tsx`, `NetworkCard.tsx`, `NetworkSheets.tsx`, `RuleSheet.tsx` and the bot editor's `views/bots/NetworkSwitches.tsx` (+ `store/network.ts`, `lib/network-copy.ts`, `src/shared/network.ts`); iPhone `apps/ios/Kit/Sources/CodyncUI/NetworkSheet.swift` (+ `CodyncKit/Models/Network.swift`); Android `NetworkSheet.kt`, `AppStoreNetwork.kt` (+ `core/Network.kt`); terminal `host/src/tui/manage/network.rs`, `network_setup.rs`, `network_rules.rs` and `view/network.rs`, `view/network_rules.rs` |
| Prompt snapshots and memory | `host/src/chat/context.rs`, `memory/` (`api.rs` the apps' read-only view, `tools.rs` and `file_tools.rs` the MCP tools, `files.rs` the folders and scan, `turns.rs` which bot's turn a found change is credited to, `file_api.rs`, `dream.rs`, `import.rs`); the rules in `host/crates/memory` (`codync-mem`: files and facts in `files/`, dreaming in `dream/`, tombstones in `store.rs`, the old entries in `legacy.rs`); harnesses' own memory turned off in `host/src/agent/own_memory.rs` |
diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.md
index 1b778065..4ec9f3e5 100644
--- a/docs/design/ui-conventions.md
+++ b/docs/design/ui-conventions.md
@@ -97,7 +97,7 @@ Desktop conversations start with the details inspector closed; the title menu op
Preserve the original character avatar design: dotted shading, highlight-only color, silhouettes and animation. Desktop roster avatars remain 30 points and iPhone roster avatars remain 46 points. iPhone shares readable secondary text and message previews; its native navigation remains platform-specific. Terminal avatars already use solid color and the terminal has no persistent details inspector; its secondary text uses the same readable palette.
-The details inspector (`apps/desktop/src/renderer/views/thread/DetailsPanel.tsx`) copies Grok Bot's: share (Create template) and close (X) as round buttons in the corner, in the page color with a soft ring, over a 54-point band that drags the window; the bot's 60-point avatar, name and runtime centered on top; then page tabs (`TabChoice`: plain labels, the chosen one on a light capsule) for **Details**, **Library** (the chat's [artifacts and files](../features/artifacts.md)), **Memory** and **Settings**, all in one scroll. The chat's `<<` button (in the same ringed style) and the title pill open it; hovering the pill shows a `>` after the name. Details holds what changes often: Instructions, Agent (the agent with its logo, its model, fast mode and its [fallbacks](../features/agent-fallback.md#apps)), the Use the computer switch and Routines (one card per routine); Settings holds the rest: Profile (avatar row, name, and "Created by" for a bot another bot created), Workspace (computer, workspace, permissions), Activity, Connectors and Skills. Both are parts of `BotSettingsForm` (`part`), saved as you edit; the editor sheet shows all of it. Every bot settings form (these, the editor sheets, the terminal's form) keeps a change made elsewhere while it is open (a bot that manages the team, another device): it takes the new value in each field not edited there, or the terminal sends only what it changed. Memory is the read-only memory card, its sections in the same tabs; each layer's note ends with "To change it, tell the bot." and the Dreams tab has an info button. Every group in the panel is Grok Bot's outlined card (an outline on the page, no fill, inputs filled instead), a row with a note puts its control under the note, and long notes (skill descriptions, explanations, a note's description) stop at two lines with an ellipsis. A group shows its avatar, name, bot count and members instead of tabs. Use 16-point horizontal insets and 28-point section gaps; sections use the `CardSection` look: filled 16-point groups without borders, hairline-split rows, a note under each option. The iPhone's Details sheet (`BotDetailsView`, from tapping the chat's title, a routine notice or a failure's Add a fallback) has the same corner buttons, header, tabs, pages, outlined cards (`cardStyle`) and two-line notes (`noteLines`), and saves as you edit too. Android's (`BotDetailsView.kt`) ports it, without the Memory tab until the read-only memory screen is ported ([Android plan](../plans/android-app.md)).
+The details inspector (`apps/desktop/src/renderer/views/thread/DetailsPanel.tsx`) copies Grok Bot's: share (Create template) and close (X) as round buttons in the corner, in the page color with a soft ring, over a 54-point band that drags the window; the bot's 60-point avatar, name and runtime centered on top; then page tabs (`TabChoice`: plain labels, the chosen one on a light capsule) for **Details**, **Library** (the chat's [artifacts and files](../features/artifacts.md)), **Memory** and **Settings**, all in one scroll. The chat's `<<` button (in the same ringed style) and the title pill open it; hovering the pill shows a `>` after the name. Details holds what changes often: [Dev servers](../features/dev-servers.md) when the bot has some, Instructions, Agent (the agent with its logo, its model, fast mode and its [fallbacks](../features/agent-fallback.md#apps)), the Use the computer switch and Routines (one card per routine); Settings holds the rest: Profile (avatar row, name, and "Created by" for a bot another bot created), Workspace (computer, workspace, permissions), Activity, Connectors and Skills. Both are parts of `BotSettingsForm` (`part`), saved as you edit; the editor sheet shows all of it. Every bot settings form (these, the editor sheets, the terminal's form) keeps a change made elsewhere while it is open (a bot that manages the team, another device): it takes the new value in each field not edited there, or the terminal sends only what it changed. Memory is the read-only memory card, its sections in the same tabs; each layer's note ends with "To change it, tell the bot." and the Dreams tab has an info button. Every group in the panel is Grok Bot's outlined card (an outline on the page, no fill, inputs filled instead), a row with a note puts its control under the note, and long notes (skill descriptions, explanations, a note's description) stop at two lines with an ellipsis. A group shows its avatar, name, bot count and members instead of tabs. Use 16-point horizontal insets and 28-point section gaps; sections use the `CardSection` look: filled 16-point groups without borders, hairline-split rows, a note under each option. The iPhone's Details sheet (`BotDetailsView`, from tapping the chat's title, a routine notice or a failure's Add a fallback) has the same corner buttons, header, tabs, pages, outlined cards (`cardStyle`) and two-line notes (`noteLines`), and saves as you edit too. Android's (`BotDetailsView.kt`) ports it, without the Memory tab until the read-only memory screen is ported ([Android plan](../plans/android-app.md)).
Routines are a compact grouped list: name, a one-line schedule (or the live run state), and an on/off switch per row; tapping a row opens the same form as +, filled in, with delete and test run beside Save. On the desktop the form card fits its content. Requests to the bot are typed directly in chat; + opens the form, where When to run is a type choice (a segmented control on the desktop, the system menu on iPhone) and a schedule is a Repeat choice (Hourly, Daily, Weekdays, Weekly, Custom) with only the fields that choice needs (minute, time, weekday, or a typed cron for Custom) and a time zone picked from a searchable list. On the desktop these sit in one `CardSection` of labeled rows, Repeat and the weekday as `ChipChoice` chips with the chosen one on a light capsule. The empty state is one line of text. A saved webhook routine's form shows the public URL and key as monospaced rows (in the same group on the desktop) with copy, show/hide and replace-key (confirmed) icon buttons, and one caption on how to send and that deliveries pass through the Codync cloud. Agent metadata uses Runtime and Workspace labels for personal bots, or Project folder for explicitly configured projects; project paths remain selectable and wrap. Personal workspace paths stay out of the default details UI. Keep status and section headings readable in both appearances through `Palette`.
@@ -160,7 +160,7 @@ and states.
remote-screen viewer and voice-call UI are not in the TUI.
- A bot's pages in the TUI match the inspector's tabs: `R` opens Details (the agent, model and first line of the instructions, which `i` edits in
Settings; Use the computer, which `u` switches; then Routines), `L` Library, `M` Memory and `e` Settings, each with the
- Details / Library / Memory / Settings line on top; ⇧← ⇧→ moves between them. Settings with unsaved edits asks for ^S (or Esc) first.
+ Details / Library / Memory / Settings line on top; ⇧← ⇧→ moves between them. Settings with unsaved edits asks for ^S (or Esc) first. Dev servers aren't on these pages: `/servers` or a click on the port opens a sheet of their own.
### Verification
diff --git a/docs/features/dev-servers.md b/docs/features/dev-servers.md
new file mode 100644
index 00000000..ef5de10d
--- /dev/null
+++ b/docs/features/dev-servers.md
@@ -0,0 +1,144 @@
+# Dev servers
+
+A bot can leave a program running on the computer: a dev server, a watch build. The host runs it, not the agent, so it
+keeps running when the agent stops, crashes or restarts, and every client shows its port and can stop it. It came out
+of [#343](https://github.com/leepokai/Codync/issues/343), where an agent kept alive for its dev server also kept its
+MCP helpers.
+
+It is independent of the bot, not isolated: a dev server runs as the user, with the user's files and network. The
+code is in `host/src/dev_servers/`.
+
+## Why the host runs them
+
+A program started through an agent's shell tool is a descendant of the agent. On Windows the agent's job ends
+everything in it. On macOS and Linux the host kills the agent's process group, so a program in that group goes too, and
+one that detached into its own session survives with nobody tracking it. Taking the tree down with the agent is
+deliberate, and stays right for what an agent starts itself. So that such a server isn't lost, `background_work` keeps
+the agent running while it sees one, with its helpers and memory.
+
+A server started through `start_dev_server` is the host's own child, in a tree of its own (`agent/process.rs`, the same
+owner agents use), so the agent can be stopped when idle while it runs.
+
+| Event | The server |
+|---|---|
+| Agent stopped when idle, crashed or changed; new session; routine run ended | Keeps running |
+| User or bot stops it | Its whole tree stops: SIGTERM, then SIGKILL after 3 s on Unix; the job ends at once on Windows |
+| It ends by itself | Stopped (exit 0) or failed; it doesn't start again |
+| Bot deleted | Stopped and removed |
+| Host updated or restarted | Stopped, then started again |
+| Computer restarted | Listed as stopped; one action starts it. An abandoned server shouldn't come back at every login |
+| Host crashed | Windows: the job closes and it ends. Unix: it survives, and the next host start kills it, matching pid and process start time, so it can't hold the port |
+
+`ponytail:` it doesn't survive the host, so its in-memory state is lost on a host update. Surviving would take log files
+instead of pipes, a named job on Windows and re-adopting by pid.
+
+## Bot tools
+
+On the existing `chat` helper (`dev_servers/tools.rs`): a new MCP server would add a process to every session.
+
+| Tool | What it does |
+|---|---|
+| `start_dev_server {command, name?, folder?}` | Starts it, in the bot's folder by default. The same bot, folder (`.` and a trailing separator don't count) and command returns that server; a stopped one starts again, without a new card if someone allowed it on one. Waits up to 20 s for a port or an exit, then answers with the status, ports and the end of its log |
+| `list_dev_servers` | This bot's servers, what it left running through its shell included |
+| `stop_dev_server {id}` | Stops one of this bot's servers |
+| `dev_server_logs {id, lines?}` | The end of its log (200 lines by default, at most 1000) |
+
+- At most 5 run per bot, however they start (a bot or a person); past that the error lists them.
+- A start finishes in a task of its own, so a request that goes away (a closed connection, a cancelled tool call) can't leave it half started. A stop that comes meanwhile ends it as soon as it's up.
+- The command ends when its first process ends, so bots give it as they'd run it in the foreground.
+- Bots hear about them in the tool's description and one line of their instructions (`BRIEF`). Nothing forces it: see
+ [what a bot leaves running](#what-a-bot-leaves-running).
+- Output goes to `~/.codync/dev-servers/<id>.log`, the current run only, rotated at 5 MB.
+- The environment is the host's own, never the agent's, which can hold its API keys.
+
+## Approval and safety
+
+- **Under Ask, a start waits on an approval card** with the command and folder (`chat::manage::approve`, as `update_bot`).
+ Under Auto it runs, like the agent's own commands. A server first started under Auto had no card, so it gets one when
+ the bot, now under Ask, starts it again (`Saved::approved`).
+- **The command runs outside any sandbox the agent has** (Codex has one). A sandboxed agent under Auto therefore has a
+ way out of it through this tool. The card under Ask is the control; decided 2026-11-05 to match the agent's own
+ commands under Auto.
+- **Clients never send a command.** They name a server (`devServerStop`, `devServerRestart`, `devServerRemove`,
+ `devServerLogs`), so a phone can only re-run what a bot started. The bot tools stay loopback-only (`chatCall` is in
+ `LOCAL_ONLY`), and a bot reaches only its own servers.
+- A command can hold a secret, so the tool's description says to keep them in the project's env files. Commands reach
+ clients over the E2E channel, and never reach analytics.
+
+## Ports
+
+No guessing what counts as a dev server: **one that listens gets its port shown**, one that doesn't (a watch build) shows
+only its status.
+
+- `dev_servers/ports.rs` reads TCP listeners with the [`listeners`](https://crates.io/crates/listeners) crate and keeps
+ those in the server's tree (`Process::members`: its process group on Unix, its job on Windows).
+- `dev_servers/scan.rs` reads them every second for a server's first 30 s, then every 10 s, and tells clients only of
+ changes. A server with no port after 5 s counts as running.
+- The host works out the addresses, so clients don't: `local` works on the computer, `remote` from other devices. A
+ loopback bind has no `remote`; a bind on all interfaces gets the computer's Tailscale and LAN addresses, or its public
+ one on a machine with neither, because that's where it is open. They're worked out again when the computer's addresses
+ change (a scan compares `if_addrs`, which starts no process; `tailscale status` does).
+
+## Wire
+
+Additive, so no `minApp` raise: non-group bots carry `devServers`.
+
+```json
+"devServers": [{
+ "id": "…", "name": "web", "command": "npm run dev", "folder": "/Users/me/site",
+ "status": "running",
+ "ports": [{"port": 5173, "local": "http://localhost:5173", "remote": ["http://192.168.1.20:5173"]}],
+ "startedAt": 1793923200000, "exitCode": null, "managed": true
+}]
+```
+
+`status` is `starting`, `running`, `stopped` or `failed`. `managed` is false for what a bot left running through its shell.
+
+## UI
+
+Nothing new in the chat beyond the port itself, and no color but the danger color for a failure: the apps are black and
+white, and color comes from the bots.
+
+- **Title:** the desktop's title pill shows `Builder :5173` in quiet text; the phones' subtitle shows `Connected · :5173`;
+ the terminal's header shows it on the right. With more running it's `:5173 +2`; with no port, the server's name; none
+ running, `Starting` or `Failed to start`; stopped, nothing. Opening the bot's details is what the title already does.
+- **Details:** a **Dev servers** section first on the Details tab, shown only when the bot has servers. A row is one line:
+ name and port (or `Running`, `Starting`, `Stopped`, `Failed to start`). A click opens it in the browser, or with no port
+ to open (a watch build, or one that ended) its logs; the rest (copy address, logs, restart, stop, remove) is behind
+ `⋯`, which on the desktop shows only when the row is hovered.
+- **Other devices:** a server listening only on its computer can't be opened from a phone, or from a desktop over SSH
+ (`store === app.local`, not `isLoopback`: an SSH store is loopback through its tunnel). Its menu says so. A server on all
+ interfaces opens at its first `remote` address.
+- **Logs:** a sheet with the last 200 lines and a refresh button; for a failed server, its exit code.
+- **Terminal:** `/servers` or a click on the port opens a sheet instead of a section; keys in `tui/manage/dev_servers.rs`,
+ the footer listing those that apply to the selected server. `codync-host tui --url` may be a tunnel, which looks local,
+ so it shows the address instead of opening a browser.
+
+Each client: desktop `views/thread/DevServersSection.tsx` and `src/shared/dev-servers.ts`; iPhone
+`CodyncUI/Bots/DevServersSection.swift`; Android `DevServersSection.kt`; terminal `tui/manage/dev_servers.rs` and
+`tui/view/dev_servers.rs`.
+
+## What a bot leaves running
+
+Instructions aren't a guarantee, and some agents have their own background-shell feature. `dev_servers/detected.rs` lists
+what an agent started outside Codync's helpers and listens below port 32768 (above is where systems hand out ports: an
+agent's own callback or inspector). The agent's own processes, by program name (its harness's `bins` and its command's
+first word, unless that's a runtime like `node`), don't count: `opencode acp` listens on 4096. Processes that share a
+socket are one server (a pre-fork server), whose Stop ends them all. These show with `managed: false`, marked as stopping
+with the bot, and offer only open, copy and stop: they can't leave the agent's tree. `background_work` still keeps their
+agent running. The `dev_server_detected` event measures how often this happens.
+
+## Tests
+
+`host/tests/dev_server_e2e.rs` runs on every system host CI does, and walks the table above: its Unix-only parts are a
+crashed host's leftover process and an agent stopped after a routine's run (Windows can't tell that fixture from one with
+a server, see `background_work`). `apps/desktop/e2e/dev-servers.spec.ts` and `apps/maestro/dev-servers.yaml` walk the
+clients.
+
+## Later
+
+- **Phone preview:** tunnel a port over the E2E channel into an in-app web view. Hot reload needs WebSockets, so it's a
+ plan of its own. A cheaper step first: open the page on the computer and watch it over remote screen.
+- **Desktop over SSH:** forward the port with the tunnel code in `apps/desktop/src/main/ssh.ts`.
+- **All servers on one screen**, across bots, when one bot's details stop being enough.
+- **Starting a server from the apps**, which would mean clients sending commands, so it needs its own safety design.
diff --git a/docs/features/marketplace.md b/docs/features/marketplace.md
index 30d2de6d..5078e479 100644
--- a/docs/features/marketplace.md
+++ b/docs/features/marketplace.md
@@ -79,9 +79,10 @@ Typing `/` at the start of a message to a bot (desktop, iPhone, Android, termina
| Command | Title | Does |
| --- | --- | --- |
| `/fast` | Fast mode | Switches [Fast mode](#fast-mode) with `updateBot`; listed only while the bot offers it. Its detail says what picking it does, or why the agent refused it (warning color). |
+| `/servers` | Dev servers | Terminal only, listed while the bot has [dev servers](dev-servers.md): opens the sheet, which it has in place of the other clients' inspector section. |
| `/<skill id>` | the skill's name | Fills in `/<skill id> ` for the rest of the message. |
-Picking a built-in command, or sending a message that is just one (`/fast`), runs it in the client and clears the box; nothing reaches the agent. Return on a skill whose name is already typed out sends the message. The host sees a message starting with `/<id of a skill the bot has on>` and hands the agent `[Codync: the user picked the "<name>" skill for this message. Read <path> first and follow it.]` followed by the rest of the message; the chat keeps the text as typed. Any other `/command`, including `/fast` for a bot without Fast mode on offer, reaches the agent unchanged, so its own commands keep working.
+Picking a built-in command, or sending a message that is just one (`/fast`), runs it in the client and clears the box; nothing reaches the agent. Return on a skill whose name is already typed out sends the message. The host sees a message starting with `/<id of a skill the bot has on>` and hands the agent `[Codync: the user picked the "<name>" skill for this message. Read <path> first and follow it.]` followed by the rest of the message; the chat keeps the text as typed. Any other `/command`, including `/fast` for a bot without Fast mode on offer and `/servers` for a bot without dev servers, reaches the agent unchanged, so its own commands keep working.
## Sign-in for remote connectors (`host/src/market/oauth.rs`)
diff --git a/docs/guides/user-docs.md b/docs/guides/user-docs.md
index c9c18cd2..bcfcff68 100644
--- a/docs/guides/user-docs.md
+++ b/docs/guides/user-docs.md
@@ -25,6 +25,7 @@ the change.
| `teamwork` | Bots messaging bots, bots on your other computers, Manage the team | [bot collaboration](../features/bot-collaboration.md), [codync-network](../features/codync-network.md) |
| `cloud-assistants` | The MCP connector for ChatGPT, Claude and other assistants: turning it on, adding it, what it can do, privacy | [cloud assistants](../features/cloud-assistants.md) |
| `routines` | Schedules, webhooks, runs | [routines](../features/routines.md) |
+| `dev-servers` | Programs a bot keeps running: starting, ports, stopping | [dev servers](../features/dev-servers.md) |
| `artifacts` | Artifacts, the Library | [artifacts](../features/artifacts.md) |
| `memory` | Layers, dreaming, the agent's own memory | [context and memory](../features/context-and-memory.md), [bot memory](../design/bot-memory.md) |
| `connectors-and-skills` | MCP connectors, apps, skills | [connector credentials](../features/connector-credentials.md), [extensions](../features/marketplace.md) |
diff --git a/docs/plans/android-app.md b/docs/plans/android-app.md
index 640ddac1..0e45dc95 100644
--- a/docs/plans/android-app.md
+++ b/docs/plans/android-app.md
@@ -19,7 +19,7 @@ emulator against a real host; device acceptance is listed separately.
| Roster | Ported: rows, menus, pin/hide/delete, Make lead agent, groups, sections (move to, fold per device, rename, remove), drag to reorder (host-synced order) and TalkBack Move up/down, a heading per computer once there are several (fold, drag to reorder on this phone, its Extensions), the computer filter (show, hide, All computers; stays open while picking), the newer-release reminder, pull to refresh (also in Computer management) | — |
| Conversation | Ported: bubbles, Markdown/code, permissions, reactions, quote replies, Full conversation, bot-to-bot exchange lines and their conversation, routine notices that open their routine, files a bot shares (verified download, then the share sheet), sent images full size, pull down to reconnect, jump to latest, read receipts for every conversation on screen | Physical keyboard and TalkBack |
| Composer | Ported: files/photos/paste (groups too, image thumbnails, Paste only when the clipboard holds files), `/` commands (Fast mode, skills listed fresh on `/`), @mentions in groups, call/send/stop/interrupt button, dictation (the mic, its recording pill, the engine menu beside it: On device through Android's recognizer, or OpenAI / Gemini transcribed on the user's key with *Transcribing…*, and the *Couldn't dictate* dialog) | Dictation with a live microphone and a provider key on a device |
-| Bot and group editors | Ported: avatar (a row that unfolds the picker), profile, agent and model options, Fast mode, workspace folder picker, permissions, activity, connectors, skills (with their details); the bot details sheet (`BotDetailsView`, from the chat's title, a routine notice or Add a fallback): Details (instructions, agent, Use the computer, Routines), Library, Memory, Settings (Codync's skill and connector switches), saved as you edit, Create template; a group's title opens its editor. An agent's own skills, connectors, rules and plugins are on its sheet in Extensions, under Sign in | — |
+| Bot and group editors | Ported: avatar (a row that unfolds the picker), profile, agent and model options, Fast mode, workspace folder picker, permissions, activity, connectors, skills (with their details); the bot details sheet (`BotDetailsView`, from the chat's title, a routine notice or Add a fallback): Details (dev servers, instructions, agent, Use the computer, Routines), Library, Memory, Settings (Codync's skill and connector switches), saved as you edit, Create template; a group's title opens its editor. An agent's own skills, connectors, rules and plugins are on its sheet in Extensions, under Sign in | — |
| Memory | Ported, read-only (`MemoryCard.kt`, `MemoryInfoSheet.kt`): About you and This bot with each `MEMORY.md` line and who wrote it, notes and their reader, dreams, the harness's own memory switch (or Shared) and its tab, the info sheets; handoff cards (keep the conversation, edit or unfold what it carries) | — |
| Routines | Ported: list with switches, editor (schedule, webhook panel, run settings), test run, delete | Live provider/routine acceptance |
| Extensions | Ported: agents (install, sign-in, setup terminal, and the skills, connectors, rules and plugins that agent already has), registry connectors, Composio apps, skills, installed list, custom connector, own skill, credentials, chat connection request card | Real provider OAuth, 1Password |
diff --git a/docs/reference/analytics-events.md b/docs/reference/analytics-events.md
index 55655fa2..49ba0af8 100644
--- a/docs/reference/analytics-events.md
+++ b/docs/reference/analytics-events.md
@@ -86,6 +86,10 @@ host answers and sends it once the host is up.
| `routine_deleted` | host | `deleteRoutine` | — |
| `routine_run` | host | `runRoutine` | — |
| `routine_retried` | host | `retryRoutineRun` (the retry button on a failed run's notice) | — |
+| `dev_server_started` | host | A bot's `start_dev_server` finished | `outcome` (`port`, `no_port`, `exited`, `refused`, `limit`, `failed`) |
+| `dev_server_stopped` | host | A dev server ended | `by` (`user`, `bot`, `restart`, `exited`, `failed`) |
+| `dev_server_action` | host (`devServerStop`, `devServerRestart`, `devServerRemove`, `devServerLogs`), host `track` (desktop, terminal UI), iOS, Android | Someone acted on a dev server | `action` (`stop`, `restart`, `remove`, `logs`, `open`, `copy`) |
+| `dev_server_detected` | host | A bot left a listening program running through its own shell | `kind` (`shell`) |
| `voice_call_started` | host `track` (desktop), iOS, Android | A voice call starts, with the engine it really uses after any fallback | `engine` (`on_device`; `openai`/`gemini` realtime; `cloud`: cloud speech to text and back) |
| `voice_call_quality` | host `track` (desktop), iOS, Android | One engine of a call is replaced or the call ends | `engine` (as `voice_call_started`), `ready_ms` (milliseconds until the provider confirmed the session and the microphone delivered; left out if it never was), `reconnects`, `stuck` (`none`/`connecting`/`reconnecting` over 20 s/`speaking`: playback stalled after the voice's turn), `failure` (`none`/`microphone`/`connection`/`provider`) |
| `voice_call_finished` | host | `endCall` (older apps `logCall`) | `seconds` |
diff --git a/host/Cargo.lock b/host/Cargo.lock
index 8d6666b4..10e39f9f 100644
--- a/host/Cargo.lock
+++ b/host/Cargo.lock
@@ -756,6 +756,7 @@ dependencies = [
"image",
"keyring",
"libc",
+ "listeners",
"portable-pty",
"qrcode",
"ratatui",
@@ -2693,6 +2694,19 @@ version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
+[[package]]
+name = "listeners"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "504c4ecfa20498c07ae4ff19b632d212e1fdcef83195b8e9eb2552306c42205f"
+dependencies = [
+ "byteorder",
+ "cc",
+ "libc",
+ "rustix",
+ "windows",
+]
+
[[package]]
name = "litemap"
version = "0.8.3"
diff --git a/host/Cargo.toml b/host/Cargo.toml
index 47b1e1ab..139d4f57 100644
--- a/host/Cargo.toml
+++ b/host/Cargo.toml
@@ -67,6 +67,7 @@ zeroize = "1"
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] }
resvg = { version = "0.49", default-features = false }
zip = { version = "9.2.0", default-features = false, features = ["deflate"] }
+listeners = "0.6.1"
[target.'cfg(target_os = "macos")'.dependencies]
keyring = { version = "3.6.3", features = ["apple-native"] }
@@ -77,7 +78,7 @@ dbus-secret-service = { version = "4.1.0", features = ["vendored"] }
[target.'cfg(windows)'.dependencies]
keyring = { version = "3.6.3", features = ["windows-native"] }
-windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_System_JobObjects", "Win32_System_Threading", "Win32_System_Diagnostics_ToolHelp", "Win32_Security"] }
+windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_System_JobObjects", "Win32_System_Threading", "Win32_System_Diagnostics_ToolHelp", "Win32_Security", "Win32_System_SystemInformation"] }
# rust-skills lint-* rules: all default groups plus pedantic, with the
# library-oriented pedantic lints turned off for this binary crate.
diff --git a/host/src/agent/acp.rs b/host/src/agent/acp.rs
index e2654ea4..8af60e00 100644
--- a/host/src/agent/acp.rs
+++ b/host/src/agent/acp.rs
@@ -198,11 +198,8 @@ impl Acp {
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
- // Its own group, so `kill` can stop everything it started.
- #[cfg(unix)]
- process.process_group(0);
- #[cfg(windows)]
- process.creation_flags(windows_sys::Win32::System::Threading::CREATE_SUSPENDED);
+ // So `kill` can stop everything it started.
+ super::process::own_tree(&mut process);
let mut child = process.spawn().with_context(|| format!("starting `{command}`"))?;
let stdin = child.stdin.take().expect("stdin is piped");
let stdout = child.stdout.take().expect("stdout is piped");
diff --git a/host/src/agent/backends.rs b/host/src/agent/backends.rs
index 511db8d2..ed21fb21 100644
--- a/host/src/agent/backends.rs
+++ b/host/src/agent/backends.rs
@@ -149,6 +149,11 @@ pub fn belongs_to_other(backend: &str, program: &str) -> bool {
&& !HARNESSES.iter().any(|h| own(h) && h.bins.contains(&name))
}
+/// The CLI names `backend`'s harness goes by.
+pub fn bins(backend: &str) -> &'static [&'static str] {
+ HARNESSES.iter().find(|h| h.answers_to(backend)).map_or(&[], |h| h.bins)
+}
+
pub fn is_known(id: &str) -> bool {
harness(id).is_some() || registry::agent(id).is_some()
}
diff --git a/host/src/agent/bot/background_work.rs b/host/src/agent/bot/background_work.rs
index f7242559..a54ce0b6 100644
--- a/host/src/agent/bot/background_work.rs
+++ b/host/src/agent/bot/background_work.rs
@@ -1,9 +1,7 @@
//! Whether an agent still runs something that stopping it would end, which keeps it running when it's idle.
use crate::agent::acp::Acp;
-#[cfg(any(windows, test))]
-use crate::agent::process::JobProcess;
-use std::collections::HashMap;
+use crate::agent::process::{self, JobProcess};
/// Whether something the agent started runs detached, in a session of its own, like a dev server
/// from its shell tool. Stopping the agent would orphan it and lose track of it, so the agent
@@ -18,20 +16,11 @@ pub(super) async fn background_work(acp: &Acp) -> bool {
#[cfg(unix)]
async fn detached_work(leader: Option<u32>) -> bool {
let Some(leader) = leader else { return true };
- let listed = tokio::process::Command::new("ps").args(["-A", "-o", "pid=,ppid="]).output().await;
- let Ok(listed) = listed.inspect_err(|e| tracing::warn!(error = format!("{e:#}"), "couldn't list processes")) else {
+ let listed = process::list_processes().await;
+ let Ok(processes) = listed.inspect_err(|e| tracing::warn!(error = format!("{e:#}"), "couldn't list processes"))
+ else {
return true;
};
- if !listed.status.success() {
- return true;
- }
- let processes: Vec<(u32, u32)> = String::from_utf8_lossy(&listed.stdout)
- .lines()
- .filter_map(|line| {
- let mut fields = line.split_whitespace().map(str::parse);
- Some((fields.next()?.ok()?, fields.next()?.ok()?))
- })
- .collect();
detached_descendant(&processes, leader, session)
}
@@ -71,43 +60,30 @@ const CONSOLE_HOST: &str = "conhost.exe";
// remembering which process started the servers, if it matters.
#[cfg(any(windows, test))]
fn runs_something_else(processes: &[JobProcess], own: &str) -> bool {
- let by_pid: HashMap<u32, &JobProcess> = processes.iter().map(|p| (p.pid, p)).collect();
let is_console = |p: &JobProcess| p.name.eq_ignore_ascii_case(CONSOLE_HOST);
- // Every step stays inside `processes`, so `take` reaches every ancestor and ends pid links that loop (reused pids).
- let ours = |p: &JobProcess| {
- std::iter::successors(Some(p), |c| by_pid.get(&c.parent).copied())
- .take(processes.len())
- .any(|c| c.name.eq_ignore_ascii_case(own))
- };
+ let ours = process::under_program(processes, own);
let starts_nothing =
|p: &JobProcess| !processes.iter().any(|c| c.parent == p.pid && c.pid != p.pid && !is_console(c));
processes.iter().filter(|p| !is_console(p) && !ours(p)).any(starts_nothing)
}
-/// `processes`: (pid, parent pid) rows; `session` finds a live process's session.
+/// `processes`: what's on the computer; `session` finds a live process's session. One that exited since the listing
+/// holds nothing.
#[cfg(any(unix, test))]
-fn detached_descendant(processes: &[(u32, u32)], leader: u32, session: impl Fn(u32) -> Option<i32>) -> bool {
+fn detached_descendant(processes: &[JobProcess], leader: u32, session: impl Fn(u32) -> Option<i32>) -> bool {
let Some(own) = session(leader) else { return true };
- let mut children: HashMap<u32, Vec<u32>> = HashMap::new();
- for &(pid, parent) in processes {
- children.entry(parent).or_default().push(pid);
- }
- let mut stack = vec![leader];
- while let Some(parent) = stack.pop() {
- for &pid in children.get(&parent).into_iter().flatten() {
- // One that exited since the listing holds nothing.
- if session(pid).is_some_and(|sid| sid != own) {
- return true;
- }
- stack.push(pid);
- }
- }
- false
+ process::descendants(processes, leader).iter().any(|p| session(p.pid).is_some_and(|sid| sid != own))
}
#[cfg(test)]
mod tests {
use super::*;
+ use std::collections::HashMap;
+
+ /// (pid, parent) rows.
+ fn rows(pairs: &[(u32, u32)]) -> Vec<JobProcess> {
+ pairs.iter().map(|&(pid, parent)| JobProcess { pid, parent, name: "x".into() }).collect()
+ }
#[test]
fn only_work_in_another_session_holds_the_agent() {
@@ -115,16 +91,16 @@ mod tests {
let sessions: HashMap<u32, i32> = [(10, 5), (11, 5), (12, 5), (20, 20), (21, 20), (30, 30)].into();
let session = |pid| sessions.get(&pid).copied();
let agent = [(10, 1), (11, 10), (12, 11), (40, 1)];
- assert!(!detached_descendant(&agent, 10, session));
+ assert!(!detached_descendant(&rows(&agent), 10, session));
// The shell tool runs `npm run dev` in a session of its own.
let mut busy = agent.to_vec();
busy.extend([(20, 11), (21, 20)]);
- assert!(detached_descendant(&busy, 10, session));
+ assert!(detached_descendant(&rows(&busy), 10, session));
// Someone else's process in another session isn't the agent's.
- assert!(!detached_descendant(&[(10, 1), (30, 1)], 10, session));
+ assert!(!detached_descendant(&rows(&[(10, 1), (30, 1)]), 10, session));
// A child that exited since the listing holds nothing; an agent that can't be looked up is unsure.
- assert!(!detached_descendant(&[(10, 1), (50, 10)], 10, session));
- assert!(detached_descendant(&agent, 99, session));
+ assert!(!detached_descendant(&rows(&[(10, 1), (50, 10)]), 10, session));
+ assert!(detached_descendant(&rows(&agent), 99, session));
}
#[test]
diff --git a/host/src/agent/bot/session.rs b/host/src/agent/bot/session.rs
index cd7e5e45..c80a6c31 100644
--- a/host/src/agent/bot/session.rs
+++ b/host/src/agent/bot/session.rs
@@ -135,9 +135,11 @@ impl Actor {
self.hub.set_runtime(&self.id(), |r| r.activity = "Starting agent…".into());
let mut env = env.to_vec();
own_memory::apply(&self.cfg, &mut env, &mut command).await;
- start_agent(&command[0], &self.cfg.cwd, &env, budget).await.inspect_err(|e| {
+ let conn = start_agent(&command[0], &self.cfg.cwd, &env, budget).await.inspect_err(|e| {
tracing::info!(command = command[0].as_str(), error = format!("{e:#}"), "agent failed to start");
- })
+ })?;
+ self.hub.dev_servers.agent_started(&self.cfg.id, &conn.acp, &self.cfg.backend, &command[0]);
+ Ok(conn)
}
/// `ensure_session` for the turn: a routine run's setup must end by its time limit, and setup cut short
diff --git a/host/src/agent/mod.rs b/host/src/agent/mod.rs
index b53578b6..9d4e3cd0 100644
--- a/host/src/agent/mod.rs
+++ b/host/src/agent/mod.rs
@@ -16,6 +16,6 @@ pub mod registry;
pub mod term;
pub mod workspace;
-mod process;
+pub(crate) mod process;
#[cfg(windows)]
mod process_windows;
diff --git a/host/src/agent/process.rs b/host/src/agent/process.rs
index 88e224b1..701d19f0 100644
--- a/host/src/agent/process.rs
+++ b/host/src/agent/process.rs
@@ -1,6 +1,7 @@
-//! Own the agent's descendants even after its leader exits or the actor unwinds.
+//! Own a program's descendants (an agent's, a dev server's) even after its leader exits or its owner unwinds.
use anyhow::{Context, Result};
+use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::process::Child;
@@ -10,8 +11,7 @@ use tokio::time::Instant;
const REAP_TIMEOUT: Duration = Duration::from_secs(5);
const POLL: Duration = Duration::from_millis(100);
-/// One process in an agent's job on Windows.
-#[cfg(any(windows, test))]
+/// One process in an agent's tree: on Windows its job, on Unix what `ps` lists under it.
#[derive(Clone)]
pub(crate) struct JobProcess {
pub(crate) pid: u32,
@@ -19,7 +19,72 @@ pub(crate) struct JobProcess {
pub(crate) name: String,
}
-pub(super) struct Process {
+/// Every process on this computer.
+#[cfg(unix)]
+pub(crate) async fn list_processes() -> Result<Vec<JobProcess>> {
+ let listed = tokio::process::Command::new("ps").args(["-A", "-o", "pid=,ppid=,comm="]).output().await?;
+ anyhow::ensure!(listed.status.success(), "ps failed");
+ Ok(parse_ps(&String::from_utf8_lossy(&listed.stdout)))
+}
+
+/// Rows of `ps -o pid=,ppid=,comm=`; a name may hold spaces.
+#[cfg(any(unix, test))]
+pub(crate) fn parse_ps(listed: &str) -> Vec<JobProcess> {
+ listed
+ .lines()
+ .filter_map(|line| {
+ let mut fields = line.trim_start().splitn(2, char::is_whitespace);
+ let pid = fields.next()?.parse().ok()?;
+ let mut fields = fields.next()?.trim_start().splitn(2, char::is_whitespace);
+ let parent = fields.next()?.parse().ok()?;
+ let name = fields.next().unwrap_or_default().trim().to_owned();
+ Some(JobProcess { pid, parent, name })
+ })
+ .collect()
+}
+
+/// Everything under `leader` in `rows`, without it.
+#[cfg(any(unix, test))]
+pub(crate) fn descendants(rows: &[JobProcess], leader: u32) -> Vec<JobProcess> {
+ let mut found: Vec<JobProcess> = Vec::new();
+ let mut parents = vec![leader];
+ while let Some(parent) = parents.pop() {
+ for row in rows.iter().filter(|row| row.parent == parent && row.pid != parent) {
+ if !found.iter().any(|known| known.pid == row.pid) {
+ parents.push(row.pid);
+ found.push(row.clone());
+ }
+ }
+ }
+ found
+}
+
+/// A process's program name without its folder.
+pub(crate) fn program_name(name: &str) -> &str {
+ name.rsplit(['/', '\\']).next().unwrap_or(name)
+}
+
+/// Tells whether a process in `tree` is `program`, or something it started. Every step stays inside `tree`, so `take`
+/// reaches every ancestor and ends pid links that loop (reused pids).
+pub(crate) fn under_program<'a>(tree: &'a [JobProcess], program: &'a str) -> impl Fn(&JobProcess) -> bool + 'a {
+ let by_pid: HashMap<u32, &JobProcess> = tree.iter().map(|p| (p.pid, p)).collect();
+ move |process| {
+ std::iter::successors(Some(process), |c| by_pid.get(&c.parent).copied())
+ .take(tree.len())
+ .any(|c| program_name(&c.name).eq_ignore_ascii_case(program))
+ }
+}
+
+/// Sets `command` up so [`Process::new`] can own everything it starts: a process group of its own on Unix,
+/// suspended until its job holds it on Windows.
+pub(crate) fn own_tree(command: &mut tokio::process::Command) {
+ #[cfg(unix)]
+ command.process_group(0);
+ #[cfg(windows)]
+ command.creation_flags(windows_sys::Win32::System::Threading::CREATE_SUSPENDED);
+}
+
+pub(crate) struct Process {
// Drop the tree before Child can reap the leader and make its PID reusable.
tree: Tree,
child: Child,
@@ -27,7 +92,7 @@ pub(super) struct Process {
}
impl Process {
- pub(super) fn new(child: Child) -> Result<Self> {
+ pub(crate) fn new(child: Child) -> Result<Self> {
let tree = Tree::new(&child)?;
let owned = Self { tree, child, stopping: false };
#[cfg(windows)]
@@ -64,7 +129,7 @@ impl Process {
}
#[cfg(unix)]
- fn exited(&self) -> std::io::Result<bool> {
+ pub(crate) fn exited(&self) -> std::io::Result<bool> {
let Some(pid) = self.child.id() else { return Ok(true) };
// SAFETY: zero is a valid siginfo value; waitid writes only into this object.
let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
@@ -88,7 +153,7 @@ impl Process {
}
#[cfg(windows)]
- fn exited(&self) -> std::io::Result<bool> {
+ pub(crate) fn exited(&self) -> std::io::Result<bool> {
use windows_sys::Win32::Foundation::{WAIT_FAILED, WAIT_OBJECT_0};
let Some(handle) = self.child.raw_handle() else { return Ok(true) };
// SAFETY: the child owns this valid process handle; a zero timeout cannot block.
@@ -105,6 +170,45 @@ impl Process {
super::process_windows::job_members(&self.tree.handle)
}
+ /// Which of `candidates` belong to this program's tree. A descendant that left the group for a session of its
+ /// own isn't counted on Unix: stopping the program wouldn't reach it either.
+ #[cfg(unix)]
+ pub(crate) fn members(&self, candidates: &[u32]) -> Vec<u32> {
+ let Some(group) = self.tree.group else { return Vec::new() };
+ let in_group = |pid: u32| {
+ // SAFETY: getpgid only reads the process table.
+ libc::pid_t::try_from(pid).is_ok_and(|pid| unsafe { libc::getpgid(pid) } == group)
+ };
+ candidates.iter().copied().filter(|pid| in_group(*pid)).collect()
+ }
+
+ /// Which of `candidates` belong to this program's job.
+ #[cfg(windows)]
+ pub(crate) fn members(&self, candidates: &[u32]) -> Vec<u32> {
+ let members = self.job_members().unwrap_or_default();
+ candidates.iter().copied().filter(|pid| members.contains(pid)).collect()
+ }
+
+ /// How the leader ended, once it was reaped; `None` for a signal.
+ pub(crate) fn exit_code(&mut self) -> Option<i32> {
+ self.child.try_wait().ok().flatten().and_then(|status| status.code())
+ }
+
+ /// Ends a program that takes no input: asks it to stop and gives it `grace` to (Windows has no such request for a
+ /// program without a console of ours, so its job ends at once).
+ pub(crate) async fn stop_gracefully(&mut self, grace: Duration) {
+ #[cfg(unix)]
+ {
+ self.tree.interrupt();
+ self.stop_within(grace).await;
+ }
+ #[cfg(windows)]
+ {
+ let _ = grace;
+ self.kill().await;
+ }
+ }
+
/// The graceful-shutdown task keeps ownership until its deadline.
pub(super) fn begin_stop(&mut self) -> bool {
!std::mem::replace(&mut self.stopping, true)
@@ -127,16 +231,16 @@ impl Process {
self.kill().await;
}
- pub(super) async fn kill(&mut self) {
+ pub(crate) async fn kill(&mut self) {
if let Err(error) = self.tree.terminate() {
- tracing::warn!(%error, "couldn't terminate agent descendants");
+ tracing::warn!(%error, "couldn't terminate a program's descendants");
}
let result = tokio::time::timeout(REAP_TIMEOUT, self.child.kill()).await;
match result {
Ok(Ok(())) => {}
Ok(Err(error)) if error.kind() == std::io::ErrorKind::InvalidInput => {}
- Ok(Err(error)) => tracing::warn!(%error, "couldn't reap agent process"),
- Err(error) => tracing::warn!(%error, "agent process did not exit before the cleanup deadline"),
+ Ok(Err(error)) => tracing::warn!(%error, "couldn't reap a program's process"),
+ Err(error) => tracing::warn!(%error, "a program's process did not exit before the cleanup deadline"),
}
}
}
@@ -149,7 +253,7 @@ struct Tree {
#[cfg(unix)]
impl Tree {
fn new(child: &Child) -> Result<Self> {
- let pid = child.id().context("agent exited before process ownership was established")?;
+ let pid = child.id().context("the program exited before process ownership was established")?;
Ok(Self { group: Some(libc::pid_t::try_from(pid)?) })
}
@@ -167,6 +271,12 @@ impl Tree {
}
}
+ fn interrupt(&self) {
+ let Some(group) = self.group else { return };
+ // SAFETY: as in `terminate`; the group is still owned and only receives a signal.
+ unsafe { libc::kill(-group, libc::SIGTERM) };
+ }
+
fn terminate(&mut self) -> std::io::Result<()> {
let Some(group) = self.group.take() else { return Ok(()) };
// SAFETY: spawn put this still-owned, unreaped child in its own process group.
@@ -185,7 +295,7 @@ impl Tree {
impl Drop for Tree {
fn drop(&mut self) {
if let Err(error) = self.terminate() {
- tracing::warn!(%error, "couldn't release agent process group");
+ tracing::warn!(%error, "couldn't release a program's process group");
}
}
}
@@ -206,7 +316,7 @@ impl Tree {
// SAFETY: null uses default security and an unnamed, newly owned job.
let raw = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
if raw.is_null() {
- return Err(std::io::Error::last_os_error()).context("creating agent process job");
+ return Err(std::io::Error::last_os_error()).context("creating a program's job");
}
// SAFETY: CreateJobObjectW transferred a unique valid handle to this owner.
let handle = unsafe { std::os::windows::io::OwnedHandle::from_raw_handle(raw) };
@@ -223,12 +333,12 @@ impl Tree {
)
} == 0
{
- return Err(std::io::Error::last_os_error()).context("configuring agent process job");
+ return Err(std::io::Error::last_os_error()).context("configuring a program's job");
}
- let process = child.raw_handle().context("agent exited before process ownership was established")?;
+ let process = child.raw_handle().context("the program exited before process ownership was established")?;
// SAFETY: the child and job handles remain owned and valid during assignment.
if unsafe { AssignProcessToJobObject(handle.as_raw_handle(), process) } == 0 {
- return Err(std::io::Error::last_os_error()).context("owning agent process descendants");
+ return Err(std::io::Error::last_os_error()).context("owning a program's descendants");
}
Ok(Self { handle })
}
diff --git a/host/src/analytics.rs b/host/src/analytics.rs
index 22dfe9e7..7a1ab3d9 100644
--- a/host/src/analytics.rs
+++ b/host/src/analytics.rs
@@ -80,6 +80,14 @@ pub enum Event {
RoutineDeleted,
RoutineRun,
RoutineRetried,
+ /// A bot's `start_dev_server` ended (`outcome`).
+ DevServerStarted,
+ /// A dev server ended (`by`).
+ DevServerStopped,
+ /// A person acted on a dev server (`action`).
+ DevServerAction,
+ /// A bot left a server running through its own shell, not `start_dev_server`.
+ DevServerDetected,
VoiceCallStarted,
VoiceCallFinished,
/// How one engine of a call fared (time to ready, reconnects, a phase stuck, failure).
@@ -155,6 +163,10 @@ impl Event {
Self::RoutineDeleted => "routine_deleted",
Self::RoutineRun => "routine_run",
Self::RoutineRetried => "routine_retried",
+ Self::DevServerStarted => "dev_server_started",
+ Self::DevServerStopped => "dev_server_stopped",
+ Self::DevServerAction => "dev_server_action",
+ Self::DevServerDetected => "dev_server_detected",
Self::VoiceCallStarted => "voice_call_started",
Self::VoiceCallFinished => "voice_call_finished",
Self::VoiceCallQuality => "voice_call_quality",
diff --git a/host/src/analytics/observe.rs b/host/src/analytics/observe.rs
index 90be6f50..da62bfed 100644
--- a/host/src/analytics/observe.rs
+++ b/host/src/analytics/observe.rs
@@ -108,6 +108,11 @@ fn call_event(method: &str, b: &Value, p: &mut Map<String, Value>) -> Option<Eve
"deleteRoutine" => Event::RoutineDeleted,
"runRoutine" => Event::RoutineRun,
"retryRoutineRun" => Event::RoutineRetried,
+ "devServerStop" | "devServerRestart" | "devServerRemove" | "devServerLogs" => {
+ let action = method.trim_start_matches("devServer").to_ascii_lowercase();
+ p.insert("action".into(), action.into());
+ Event::DevServerAction
+ }
"logCall" | "endCall" => {
p.insert("seconds".into(), b["seconds"].as_u64().unwrap_or(0).into());
Event::VoiceCallFinished
diff --git a/host/src/analytics/observe/tests.rs b/host/src/analytics/observe/tests.rs
index f81cef9e..7cb297fa 100644
--- a/host/src/analytics/observe/tests.rs
+++ b/host/src/analytics/observe/tests.rs
@@ -89,6 +89,10 @@ fn settings_routines_screen_and_devices() {
props("setRoutineEnabled", &json!({"botId": "b", "id": "r", "enabled": false})),
Some((Event::RoutineToggled, json!({"enabled": false, "client": "local"})))
);
+ assert_eq!(
+ props("devServerRestart", &json!({"botId": "b", "id": "s"})),
+ Some((Event::DevServerAction, json!({"action": "restart", "client": "local"})))
+ );
assert_eq!(props("screenTakeover", &json!({"on": true})).map(|(e, _)| e), Some(Event::ScreenTakenOver));
assert!(props("screenTakeover", &json!({"on": false})).is_none(), "handing it back");
assert_eq!(props("pairing", &json!({})), Some((Event::PairingCodeCreated, json!({"client": "local"}))));
diff --git a/host/src/analytics/reported.rs b/host/src/analytics/reported.rs
index fa45aa47..9a47524e 100644
--- a/host/src/analytics/reported.rs
+++ b/host/src/analytics/reported.rs
@@ -33,6 +33,9 @@ pub enum App {
#[derive(Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "event", rename_all = "snake_case")]
pub enum Reported {
+ DevServerAction {
+ action: DevServerAction,
+ },
AppOpened {
/// Opened by the login item (desktop).
#[serde(skip_serializing_if = "Option::is_none")]
@@ -230,6 +233,16 @@ pub enum ReachOutcome {
Other,
}
+/// What the apps do with a dev server on their own (the host's methods report the rest).
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum DevServerAction {
+ Open,
+ Copy,
+ #[serde(other)]
+ Other,
+}
+
/// Why a computer couldn't be added to the account.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
@@ -330,6 +343,7 @@ mod tests {
Event::StarPromptAnswered,
),
(json!({"event": "link_opened", "app": "desktop", "link": "install_command"}), Event::LinkOpened),
+ (json!({"event": "dev_server_action", "app": "desktop", "action": "open"}), Event::DevServerAction),
(json!({"event": "screen_viewed", "app": "tui", "screen": "bot_details"}), Event::ScreenViewed),
(json!({"event": "voice_call_started", "app": "desktop", "engine": "on_device"}), Event::VoiceCallStarted),
(
diff --git a/host/src/api/bots.rs b/host/src/api/bots.rs
index 9bb1b48d..03a56f7c 100644
--- a/host/src/api/bots.rs
+++ b/host/src/api/bots.rs
@@ -51,6 +51,8 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value
crate::chat::fallbacks::call(hub, bot, name, &b["arguments"]).await?
} else if crate::chat::artifacts::TOOLS.contains(&name) {
crate::chat::artifacts::call(hub, bot, name, &b["arguments"]).await?
+ } else if crate::dev_servers::TOOLS.contains(&name) {
+ crate::dev_servers::call(hub, bot, name, &b["arguments"]).await?
} else {
crate::chat::outbox::call(hub, bot, name, &b["arguments"]).await?
}
@@ -109,6 +111,22 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value
tokio::task::spawn_blocking(move || hub.rename_section(&from, to.as_deref())).await??;
json!({})
}
+ // The apps name a dev server, and never send a command.
+ "devServerStop" => {
+ crate::dev_servers::stop(hub, str_arg(&b, "botId")?, str_arg(&b, "id")?, "user").await?;
+ json!({})
+ }
+ "devServerRestart" => {
+ crate::dev_servers::restart(hub, str_arg(&b, "botId")?, str_arg(&b, "id")?).await?;
+ json!({})
+ }
+ "devServerRemove" => {
+ crate::dev_servers::remove(hub, str_arg(&b, "botId")?, str_arg(&b, "id")?)?;
+ json!({})
+ }
+ "devServerLogs" => {
+ json!({"text": crate::dev_servers::shown_logs(hub, str_arg(&b, "botId")?, str_arg(&b, "id")?).await?})
+ }
"deleteBot" => {
hub.delete_bot(str_arg(&b, "botId")?)?;
json!({})
diff --git a/host/src/background.rs b/host/src/background.rs
index a9210ce3..740cd161 100644
--- a/host/src/background.rs
+++ b/host/src/background.rs
@@ -21,6 +21,7 @@ pub fn start(hub: &Arc<Hub>) -> JoinSet<()> {
tokio::spawn(market::automatic_loop(hub.clone()));
tokio::spawn(voice::refresh_loop(hub.clone()));
tokio::spawn(crate::chat::calls::sweep_loop(hub.clone()));
+ tokio::spawn(crate::dev_servers::scan_loop(hub.clone()));
let mut agent_checks = JoinSet::new();
agent_checks.spawn({
let hub = hub.clone();
diff --git a/host/src/chat/context.rs b/host/src/chat/context.rs
index d7dd1e05..a55c141a 100644
--- a/host/src/chat/context.rs
+++ b/host/src/chat/context.rs
@@ -239,6 +239,8 @@ pub fn render(store: &Store, cfg: &BotConfig) -> String {
);
lines.push(String::new());
lines.push(format!("Workspace: your default working directory is {}. {} Keep your own files and outputs there. For another project, use explicit paths or change directory for that command; don't change your bot configuration to work elsewhere. This directory is not a sandbox or a grant of access: follow the user's instructions and your permissions, and don't assume other bots' files are yours.", cfg.cwd, if crate::agent::workspace::is_managed(cfg) { "Codync allocated it for you alone." } else { "The user chose this project folder." }));
+ lines.push(String::new());
+ lines.push(crate::dev_servers::BRIEF.to_owned());
if let Some(skills) = crate::market::skills_brief(store, &cfg.skills) {
lines.push(String::new());
lines.push(skills);
diff --git a/host/src/chat/manage.rs b/host/src/chat/manage.rs
index 2a0a4e25..8d3b2329 100644
--- a/host/src/chat/manage.rs
+++ b/host/src/chat/manage.rs
@@ -210,7 +210,7 @@ async fn update(hub: &Arc<Hub>, source: &BotConfig, args: &Value) -> Result<Valu
}
/// Under Ask the change waits for the user's Allow on an approval card in the bot's chat.
-async fn approve(hub: &Hub, source: &BotConfig, title: String, detail: String) -> Result<()> {
+pub(crate) async fn approve(hub: &Hub, source: &BotConfig, title: String, detail: String) -> Result<()> {
if source.permission == Permission::Auto {
return Ok(());
}
diff --git a/host/src/dev_servers/detected.rs b/host/src/dev_servers/detected.rs
new file mode 100644
index 00000000..2cbab168
--- /dev/null
+++ b/host/src/dev_servers/detected.rs
@@ -0,0 +1,238 @@
+//! Servers a bot left running through its own shell. They can't leave the agent's tree (a job on Windows holds them,
+//! and on Unix a started process has no new parent to go to), so they only show, marked as stopping with the bot.
+
+use super::ports::{self, Listening, Port};
+use super::{Status, View, platform, report};
+use crate::LockExt;
+use crate::agent::acp::Acp;
+use crate::agent::backends;
+use crate::agent::process::{self, JobProcess, program_name};
+use crate::analytics::Event;
+use crate::hub::Hub;
+use anyhow::{Result, bail};
+use std::collections::HashMap;
+use std::net::SocketAddr;
+use std::sync::Arc;
+
+const ID_PREFIX: &str = "detected:";
+/// Above this is where systems pick a port for whoever asks for any: an agent's own callback or inspector, not a
+/// server someone would open.
+// ponytail: guesses by range; ask agents what they listen on if a real server sits above it.
+const HIGHEST_PORT: u16 = 32767;
+/// What launches an agent and runs servers just as well, so its name says nothing about the agent.
+const RUNTIMES: [&str; 20] = [
+ "node",
+ "npx",
+ "npm",
+ "pnpm",
+ "yarn",
+ "bun",
+ "bunx",
+ "deno",
+ "python",
+ "python3",
+ "uv",
+ "uvx",
+ "ruby",
+ "java",
+ "sh",
+ "bash",
+ "zsh",
+ "cmd",
+ "powershell",
+ "pwsh",
+];
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Detected {
+ /// Everything holding its sockets, lowest first (a pre-fork server has several); the first names it.
+ pub pids: Vec<u32>,
+ pub name: String,
+ pub sockets: Vec<SocketAddr>,
+ pub ports: Vec<Port>,
+}
+
+impl Detected {
+ pub(super) fn view(&self) -> View {
+ View {
+ id: format!("{ID_PREFIX}{}", self.pids[0]),
+ name: self.name.clone(),
+ command: self.name.clone(),
+ folder: None,
+ status: Status::Running,
+ ports: self.ports.clone(),
+ started_at: None,
+ exit_code: None,
+ managed: false,
+ }
+ }
+}
+
+/// An agent to look under.
+pub struct RunningAgent {
+ pub bot: String,
+ pub acp: Arc<Acp>,
+ pub programs: Vec<String>,
+}
+
+/// The names an agent's own processes go by: its harness's CLIs and the program its command line runs. They can listen
+/// below [`HIGHEST_PORT`] (`opencode acp` does) and stay running under a wrapper script or `cmd`.
+pub fn agent_programs(backend: &str, command: &str) -> Vec<String> {
+ let mut programs: Vec<String> = backends::bins(backend).iter().map(|bin| (*bin).to_owned()).collect();
+ let name = plain_name(first_word(command));
+ let says_nothing = name.is_empty() || RUNTIMES.contains(&name) || name.starts_with("python");
+ if !says_nothing && !programs.iter().any(|program| program == name) {
+ programs.push(name.to_owned());
+ }
+ programs
+}
+
+/// The command line's program, past any leading `KEY=value`, without its quotes.
+fn first_word(command: &str) -> &str {
+ let mut rest = command.trim_start();
+ loop {
+ if let Some(quote) = rest.chars().next().filter(|c| matches!(c, '\'' | '"')) {
+ return rest[1..].split(quote).next().unwrap_or_default();
+ }
+ let (word, after) = rest.split_once(char::is_whitespace).unwrap_or((rest, ""));
+ if after.is_empty() || !word.contains('=') {
+ return word;
+ }
+ rest = after.trim_start();
+ }
+}
+
+/// A program's name without its folder or Windows' extension.
+fn plain_name(program: &str) -> &str {
+ let name = program_name(program);
+ name.strip_suffix(".exe").or_else(|| name.strip_suffix(".EXE")).unwrap_or(name)
+}
+
+/// Ends a detected server of `bot` named by `id`. False when `id` isn't one, so it's a server of the host's own.
+pub fn stop(hub: &Hub, bot: &str, id: &str) -> Result<bool> {
+ let Some(first) = id.strip_prefix(ID_PREFIX) else { return Ok(false) };
+ let first: u32 = first.parse()?;
+ let server = hub.dev_servers.detected.locked().get_mut(bot).and_then(|servers| {
+ let at = servers.iter().position(|server| server.pids[0] == first)?;
+ Some(servers.remove(at))
+ });
+ let Some(server) = server else { bail!("unknown dev server") };
+ for pid in server.pids {
+ platform::end_process(pid);
+ }
+ hub.emit_bot(bot);
+ Ok(true)
+}
+
+/// Finds what each bot's agent left listening, and tells clients when that changed. `moved`: this computer's addresses
+/// changed, so the ones worked out before no longer hold.
+pub async fn scan(hub: &Hub, agents: &[RunningAgent], listening: &[Listening], moved: bool) {
+ let own_program = std::env::current_exe().ok().and_then(|exe| Some(exe.file_name()?.to_str()?.to_owned()));
+ let Some(own_program) = own_program else { return };
+ let Some(trees) = agent_trees(agents).await else { return };
+ let mut found: HashMap<String, Vec<Detected>> = HashMap::new();
+ for (agent, tree) in agents.iter().zip(&trees) {
+ let known = hub.dev_servers.detected.locked().get(&agent.bot).cloned().unwrap_or_default();
+ let mut servers = servers_in(tree, &own_program, &agent.programs, listening);
+ for server in &mut servers {
+ let same = known.iter().find(|before| before.sockets == server.sockets).filter(|_| !moved);
+ server.ports = if let Some(before) = same {
+ before.ports.clone()
+ } else {
+ let sockets = server.sockets.clone();
+ tokio::task::spawn_blocking(move || ports::urls(&sockets)).await.unwrap_or_default()
+ };
+ }
+ if !servers.is_empty() {
+ found.insert(agent.bot.clone(), servers);
+ }
+ }
+ let (changed, new) = {
+ let mut detected = hub.dev_servers.detected.locked();
+ let changes = changes(&detected, &found);
+ *detected = found;
+ changes
+ };
+ for _ in 0..new {
+ report(hub, Event::DevServerDetected, "kind", "shell");
+ }
+ for bot in changed {
+ hub.emit_bot(&bot);
+ }
+}
+
+/// The bots whose list changed, and how many servers are new.
+pub(super) fn changes(
+ before: &HashMap<String, Vec<Detected>>,
+ found: &HashMap<String, Vec<Detected>>,
+) -> (Vec<String>, usize) {
+ let mut bots: Vec<String> =
+ found.iter().filter(|(bot, servers)| before.get(*bot) != Some(*servers)).map(|(bot, _)| bot.clone()).collect();
+ bots.extend(before.keys().filter(|bot| !found.contains_key(*bot)).cloned());
+ let is_new = |bot: &str, server: &Detected| {
+ !before.get(bot).is_some_and(|known| known.iter().any(|known| known.pids[0] == server.pids[0]))
+ };
+ let new = found.iter().map(|(bot, servers)| servers.iter().filter(|server| is_new(bot, server)).count()).sum();
+ (bots, new)
+}
+
+/// What in `tree` listens, one entry per server: processes that share a socket are one server, and neither Codync's
+/// helpers nor the agent's own processes are one. Its addresses are worked out later.
+pub(super) fn servers_in(
+ tree: &[JobProcess],
+ own_program: &str,
+ programs: &[String],
+ listening: &[Listening],
+) -> Vec<Detected> {
+ let is_ours = process::under_program(tree, own_program);
+ let is_agent = |p: &JobProcess| programs.iter().any(|own| plain_name(&p.name).eq_ignore_ascii_case(own));
+ let mut outside: Vec<u32> = tree.iter().filter(|p| !is_ours(p) && !is_agent(p)).map(|p| p.pid).collect();
+ outside.sort_unstable();
+ let mut servers: Vec<Detected> = Vec::new();
+ for pid in outside {
+ let sockets: Vec<SocketAddr> =
+ ports::sockets_of(listening, &[pid]).into_iter().filter(|socket| socket.port() <= HIGHEST_PORT).collect();
+ if sockets.is_empty() {
+ continue;
+ }
+ let sharing = servers.iter_mut().find(|server| server.sockets.iter().any(|socket| sockets.contains(socket)));
+ if let Some(server) = sharing {
+ server.pids.push(pid);
+ server.sockets.extend(sockets);
+ server.sockets.sort();
+ server.sockets.dedup();
+ } else {
+ let name = listening.iter().find(|l| l.pid == pid).map_or_else(String::new, |l| l.name.clone());
+ servers.push(Detected { pids: vec![pid], name, sockets, ports: Vec::new() });
+ }
+ }
+ servers
+}
+
+/// What each of `agents` started, without the agent itself, listed once per scan: `None` when that failed, so nothing
+/// is taken to have ended.
+#[cfg(unix)]
+async fn agent_trees(agents: &[RunningAgent]) -> Option<Vec<Vec<JobProcess>>> {
+ if agents.is_empty() {
+ return Some(Vec::new());
+ }
+ let everything = process::list_processes()
+ .await
+ .inspect_err(|error| tracing::debug!(error = format!("{error:#}"), "couldn't list processes"))
+ .ok()?;
+ let tree = |agent: &RunningAgent| {
+ agent.acp.pid().map_or_else(Vec::new, |leader| process::descendants(&everything, leader))
+ };
+ Some(agents.iter().map(tree).collect())
+}
+
+/// Everything in each of `agents`' jobs, its own processes too: [`servers_in`] leaves those out by name. A failed read
+/// shows nothing.
+#[cfg(windows)]
+async fn agent_trees(agents: &[RunningAgent]) -> Option<Vec<Vec<JobProcess>>> {
+ let mut trees = Vec::new();
+ for agent in agents {
+ trees.push(agent.acp.job_processes().await.unwrap_or_default());
+ }
+ Some(trees)
+}
diff --git a/host/src/dev_servers/logs.rs b/host/src/dev_servers/logs.rs
new file mode 100644
index 00000000..74900138
--- /dev/null
+++ b/host/src/dev_servers/logs.rs
@@ -0,0 +1,126 @@
+//! A dev server's output: `~/.codync/dev-servers/<id>.log`, the current run only, rotated once so it stays bounded.
+
+use anyhow::Result;
+use std::io::{ErrorKind, Read as _, Seek as _, SeekFrom};
+use std::path::PathBuf;
+use std::sync::Arc;
+use tokio::io::{AsyncRead, AsyncReadExt as _, AsyncWriteExt as _};
+use tokio::process::{ChildStderr, ChildStdout};
+use tokio::sync::Mutex;
+
+/// A log moves aside at this size; the one before it is dropped.
+const ROTATE_AT: u64 = 5 * 1024 * 1024;
+/// How far back from the end `tail` reads.
+const TAIL_BYTES: u64 = 256 * 1024;
+/// Lines the apps show, and the most a bot can ask for.
+pub const SHOWN_LINES: usize = 200;
+pub const MOST_LINES: usize = 1000;
+
+fn folder() -> PathBuf {
+ crate::service::data_dir().join("dev-servers")
+}
+
+fn path(id: &str) -> PathBuf {
+ folder().join(format!("{id}.log"))
+}
+
+fn rotated(id: &str) -> PathBuf {
+ folder().join(format!("{id}.log.1"))
+}
+
+struct Writer {
+ id: String,
+ file: tokio::fs::File,
+ size: u64,
+}
+
+impl Writer {
+ async fn write(&mut self, bytes: &[u8]) -> Result<()> {
+ if self.size + bytes.len() as u64 > ROTATE_AT {
+ tokio::fs::rename(path(&self.id), rotated(&self.id)).await?;
+ self.file = tokio::fs::File::create(path(&self.id)).await?;
+ self.size = 0;
+ }
+ self.file.write_all(bytes).await?;
+ self.size += bytes.len() as u64;
+ Ok(())
+ }
+}
+
+/// Starts a new log for this run and copies `stdout` and `stderr` into it until they close.
+pub async fn capture(id: &str, stdout: ChildStdout, stderr: ChildStderr) -> Result<()> {
+ tokio::fs::create_dir_all(folder()).await?;
+ remove(&rotated(id));
+ let file = tokio::fs::File::create(path(id)).await?;
+ let writer = Arc::new(Mutex::new(Writer { id: id.to_owned(), file, size: 0 }));
+ tokio::spawn(pump(stdout, writer.clone()));
+ tokio::spawn(pump(stderr, writer));
+ Ok(())
+}
+
+async fn pump(mut from: impl AsyncRead + Unpin, writer: Arc<Mutex<Writer>>) {
+ let mut buffer = vec![0; 8192];
+ loop {
+ match from.read(&mut buffer).await {
+ Ok(0) | Err(_) => break,
+ Ok(read) => {
+ if let Err(error) = writer.lock().await.write(&buffer[..read]).await {
+ // Keep reading: a full disk mustn't block the server on a full pipe.
+ tracing::debug!(error = format!("{error:#}"), "couldn't write a dev server's log");
+ }
+ }
+ }
+ }
+}
+
+/// Why it couldn't start, where its output would have been.
+pub fn note(id: &str, text: &str) {
+ let written = std::fs::create_dir_all(folder()).and_then(|()| std::fs::write(path(id), text));
+ if let Err(error) = written {
+ tracing::debug!(%error, "couldn't write a dev server's log");
+ }
+}
+
+pub fn delete(id: &str) {
+ remove(&path(id));
+ remove(&rotated(id));
+}
+
+fn remove(file: &std::path::Path) {
+ if let Err(error) = std::fs::remove_file(file)
+ && error.kind() != ErrorKind::NotFound
+ {
+ tracing::warn!(%error, file = %file.display(), "couldn't delete a dev server's log");
+ }
+}
+
+/// The log's last `lines` lines, as plain text.
+pub async fn tail(id: &str, lines: usize) -> Result<String> {
+ let (current, before) = (path(id), rotated(id));
+ let text = tokio::task::spawn_blocking(move || {
+ let mut text = read_end(&current);
+ if text.lines().count() < lines {
+ text = read_end(&before) + &text;
+ }
+ text
+ })
+ .await?;
+ Ok(last_lines(&crate::usage::strip_ansi(&text), lines))
+}
+
+fn read_end(path: &std::path::Path) -> String {
+ let read = || -> std::io::Result<Vec<u8>> {
+ let mut file = std::fs::File::open(path)?;
+ let size = file.metadata()?.len();
+ file.seek(SeekFrom::Start(size.saturating_sub(TAIL_BYTES)))?;
+ let mut bytes = Vec::new();
+ file.read_to_end(&mut bytes)?;
+ Ok(bytes)
+ };
+ read().map(|bytes| String::from_utf8_lossy(&bytes).into_owned()).unwrap_or_default()
+}
+
+pub(super) fn last_lines(text: &str, lines: usize) -> String {
+ let all: Vec<&str> = text.lines().collect();
+ all[all.len().saturating_sub(lines)..].join("\n")
+}
diff --git a/host/src/dev_servers/mod.rs b/host/src/dev_servers/mod.rs
new file mode 100644
index 00000000..1a6c4730
--- /dev/null
+++ b/host/src/dev_servers/mod.rs
@@ -0,0 +1,331 @@
+//! Programs a bot keeps running (a dev server, a watch build). The host runs them, not the agent, so they outlive the
+//! agent's idle stop, crash or restart, and every client can show their ports and stop them. What a bot leaves running
+//! through its own shell instead can't move out of the agent's tree; [`detected`] only shows it.
+//! Design: docs/features/dev-servers.md.
+
+mod detected;
+mod logs;
+mod platform;
+mod ports;
+mod run;
+mod scan;
+#[cfg(test)]
+mod tests;
+mod tools;
+
+pub use run::{remove, restart, stop};
+pub use scan::scan_loop;
+pub use tools::{BRIEF, START, TOOLS, call, tools};
+
+use crate::LockExt;
+use crate::agent::acp::Acp;
+use crate::agent::process::Process;
+use crate::analytics::{self, Event};
+use crate::hub::Hub;
+use crate::store::Store;
+use anyhow::{Result, anyhow, bail};
+use detected::Detected;
+use ports::Port;
+use serde::{Deserialize, Serialize};
+use serde_json::{Map, Value, json};
+use std::collections::HashMap;
+use std::net::SocketAddr;
+use std::sync::{Arc, Mutex, Weak};
+use std::time::Duration;
+use tokio::sync::{Notify, watch};
+
+const KV_PREFIX: &str = "dev-server:";
+/// Running at once per bot: a loop of retries can't fill the computer.
+const MAX_RUNNING: usize = 5;
+/// What a server gets to stop by itself before the rest of its tree is killed.
+const STOP_GRACE: Duration = Duration::from_secs(3);
+/// How long a stop waits: the grace, then a moment for what's left to be killed.
+const STOP_WAIT: Duration = Duration::from_secs(STOP_GRACE.as_secs() + 2);
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum Status {
+ Starting,
+ Running,
+ Failed,
+ /// Also how a client reads a status from a newer host.
+ #[default]
+ #[serde(other)]
+ Stopped,
+}
+
+impl Status {
+ /// Whether its program is running, or on its way.
+ pub fn active(self) -> bool {
+ matches!(self, Self::Starting | Self::Running)
+ }
+}
+
+/// A server as clients and bots see it.
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct View {
+ id: String,
+ name: String,
+ command: String,
+ folder: Option<String>,
+ status: Status,
+ ports: Vec<Port>,
+ started_at: Option<i64>,
+ exit_code: Option<i32>,
+ managed: bool,
+}
+
+/// A server's first process, told from a later one with the same pid. Windows keeps none: a job ends with the host
+/// that owns it.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+struct Leader {
+ pid: u32,
+ start: String,
+}
+
+/// What survives a host restart.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct Saved {
+ id: String,
+ bot: String,
+ name: String,
+ command: String,
+ folder: String,
+ created_at: i64,
+ /// Whether it should run: true until someone stops it or it ends by itself.
+ wanted: bool,
+ /// Whether someone allowed it on a card, so it can start again without one.
+ approved: bool,
+ leader: Option<Leader>,
+ boot_ms: Option<i64>,
+}
+
+struct Run {
+ stop: watch::Sender<bool>,
+ ended: watch::Receiver<bool>,
+ process: Arc<tokio::sync::Mutex<Process>>,
+}
+
+impl Run {
+ fn ask_to_stop(&self) -> watch::Receiver<bool> {
+ self.stop.send_replace(true);
+ self.ended.clone()
+ }
+}
+
+struct Live {
+ saved: Saved,
+ status: Status,
+ sockets: Vec<SocketAddr>,
+ ports: Vec<Port>,
+ started_at: Option<i64>,
+ exit_code: Option<i32>,
+ run: Option<Run>,
+ /// A stop came while its program was still starting, with no run to stop yet.
+ stop_asked: bool,
+}
+
+impl Live {
+ fn stopped(saved: Saved) -> Self {
+ Self {
+ saved,
+ status: Status::Stopped,
+ sockets: Vec::new(),
+ ports: Vec::new(),
+ started_at: None,
+ exit_code: None,
+ run: None,
+ stop_asked: false,
+ }
+ }
+
+ fn view(&self) -> View {
+ View {
+ id: self.saved.id.clone(),
+ name: self.saved.name.clone(),
+ command: self.saved.command.clone(),
+ folder: Some(self.saved.folder.clone()),
+ status: self.status,
+ ports: self.ports.clone(),
+ started_at: self.started_at,
+ exit_code: self.exit_code,
+ managed: true,
+ }
+ }
+
+ /// A new run begins: nothing of the last one stays.
+ fn begin(&mut self, now: i64) {
+ self.status = Status::Starting;
+ self.exit_code = None;
+ self.sockets.clear();
+ self.ports.clear();
+ self.started_at = Some(now);
+ }
+
+ /// Its run ended, because someone `asked` or by itself; one that ends by itself isn't wanted back.
+ fn ended(&mut self, asked: bool, code: Option<i32>) {
+ self.run = None;
+ self.sockets.clear();
+ self.ports.clear();
+ self.exit_code = code;
+ self.status = if asked || code == Some(0) { Status::Stopped } else { Status::Failed };
+ if !asked {
+ self.saved.wanted = false;
+ }
+ }
+
+ /// What a scan read: `ports` when its addresses were worked out again. The first socket, or enough time without
+ /// one, makes it running. Returns whether clients should hear of it.
+ fn observed(&mut self, sockets: Vec<SocketAddr>, ports: Option<Vec<Port>>, now: i64) -> bool {
+ let settled = self.status == Status::Starting
+ && (!sockets.is_empty() || self.started_at.is_some_and(|at| now - at >= scan::SETTLE_MS));
+ if settled {
+ self.status = Status::Running;
+ }
+ let mut moved = false;
+ if let Some(ports) = ports {
+ self.sockets = sockets;
+ moved = ports != self.ports;
+ self.ports = ports;
+ }
+ settled || moved
+ }
+}
+
+/// An agent that was started, and the programs it runs under.
+struct Agent {
+ acp: Weak<Acp>,
+ programs: Vec<String>,
+}
+
+#[derive(Default)]
+pub struct DevServers {
+ live: Mutex<HashMap<String, Live>>,
+ detected: Mutex<HashMap<String, Vec<Detected>>>,
+ agents: Mutex<HashMap<String, Agent>>,
+ /// Wakes the port scan for a server that just started.
+ wake: Notify,
+}
+
+impl DevServers {
+ /// A bot's servers as clients see them: its own, oldest first, then what its agent left running.
+ pub fn wire(&self, bot: &str) -> Value {
+ let mut own: Vec<(i64, View)> = self
+ .live
+ .locked()
+ .values()
+ .filter(|live| live.saved.bot == bot)
+ .map(|live| (live.saved.created_at, live.view()))
+ .collect();
+ own.sort_by_key(|(created_at, _)| *created_at);
+ let mut servers: Vec<View> = own.into_iter().map(|(_, view)| view).collect();
+ if let Some(found) = self.detected.locked().get(bot) {
+ servers.extend(found.iter().map(Detected::view));
+ }
+ json!(servers)
+ }
+
+ /// `command`: the line it was started with, on `backend`'s harness.
+ pub fn agent_started(&self, bot: &str, acp: &Arc<Acp>, backend: &str, command: &str) {
+ let agent = Agent { acp: Arc::downgrade(acp), programs: detected::agent_programs(backend, command) };
+ self.agents.locked().insert(bot.to_owned(), agent);
+ }
+
+ /// A deleted bot's servers end with it: dropping a server's run makes it stop.
+ pub fn forget_bot(&self, store: &Store, bot: &str) {
+ self.agents.locked().remove(bot);
+ self.detected.locked().remove(bot);
+ let ids: Vec<String> =
+ self.live.locked().iter().filter(|(_, live)| live.saved.bot == bot).map(|(id, _)| id.clone()).collect();
+ for id in ids {
+ self.live.locked().remove(&id);
+ if let Err(error) = forget(store, &id) {
+ tracing::warn!(error = format!("{error:#}"), "couldn't forget a dev server");
+ }
+ }
+ }
+
+ /// Stops every server and waits for them, keeping what's wanted so the next start brings it back.
+ pub async fn shutdown(&self) {
+ let ended: Vec<watch::Receiver<bool>> =
+ self.live.locked().values().filter_map(|live| live.run.as_ref()).map(Run::ask_to_stop).collect();
+ let waits = ended.into_iter().map(|mut ended| async move {
+ let _ = ended.wait_for(|done| *done).await;
+ });
+ if tokio::time::timeout(STOP_WAIT, futures::future::join_all(waits)).await.is_err() {
+ tracing::warn!("some dev servers didn't stop in time");
+ }
+ }
+
+ /// A bot's server by what it runs and where: starting the same thing twice isn't two servers.
+ fn same(&self, bot: &str, folder: &str, command: &str) -> Option<String> {
+ self.live
+ .locked()
+ .values()
+ .find(|live| live.saved.bot == bot && live.saved.folder == folder && live.saved.command == command)
+ .map(|live| live.saved.id.clone())
+ }
+
+ fn view(&self, bot: &str, id: &str) -> Result<View> {
+ self.live
+ .locked()
+ .get(id)
+ .filter(|live| live.saved.bot == bot)
+ .map(Live::view)
+ .ok_or_else(|| anyhow!("unknown dev server"))
+ }
+
+ fn approved(&self, id: &str) -> bool {
+ self.live.locked().get(id).is_some_and(|live| live.saved.approved)
+ }
+
+ fn note_approved(&self, store: &Store, id: &str) {
+ if let Some(live) = self.live.locked().get_mut(id) {
+ live.saved.approved = true;
+ save(store, &live.saved);
+ }
+ }
+}
+
+fn key(id: &str) -> String {
+ format!("{KV_PREFIX}{id}")
+}
+
+fn save(store: &Store, saved: &Saved) {
+ let written =
+ serde_json::to_string(saved).map_err(anyhow::Error::from).and_then(|json| store.kv_set(&key(&saved.id), &json));
+ if let Err(error) = written {
+ tracing::warn!(error = format!("{error:#}"), "couldn't save a dev server");
+ }
+}
+
+/// Leaves nothing of a server behind.
+fn forget(store: &Store, id: &str) -> Result<()> {
+ logs::delete(id);
+ store.kv_delete(&key(id))
+}
+
+fn report(hub: &Hub, event: Event, key: &str, value: &str) {
+ let mut properties = Map::new();
+ properties.insert(key.into(), value.into());
+ analytics::capture(hub, event, properties);
+}
+
+/// Refuses another running server past the limit, saying which ones run.
+fn check_room(hub: &Hub, bot: &str) -> Result<()> {
+ let running =
+ hub.dev_servers.live.locked().values().filter(|live| live.saved.bot == bot && live.status.active()).count();
+ if running >= MAX_RUNNING {
+ report(hub, Event::DevServerStarted, "outcome", "limit");
+ bail!("at most {MAX_RUNNING} dev servers run at once; stop one first. Running: {}", hub.dev_servers.wire(bot));
+ }
+ Ok(())
+}
+
+/// A server's recent output, for the apps.
+pub async fn shown_logs(hub: &Hub, bot: &str, id: &str) -> Result<String> {
+ hub.dev_servers.view(bot, id)?;
+ logs::tail(id, logs::SHOWN_LINES).await
+}
diff --git a/host/src/dev_servers/platform.rs b/host/src/dev_servers/platform.rs
new file mode 100644
index 00000000..d3982fad
--- /dev/null
+++ b/host/src/dev_servers/platform.rs
@@ -0,0 +1,88 @@
+//! What differs per system: when it booted, whether a saved pid is still the same process, ending one process.
+
+#[cfg(unix)]
+use std::process::Command;
+
+/// Boot times read twice can differ a little (Windows derives it from an uptime counter).
+const SAME_BOOT_WITHIN_MS: i64 = 120_000;
+
+pub fn same_boot(saved: Option<i64>, now: Option<i64>) -> bool {
+ saved.zip(now).is_some_and(|(saved, now)| (saved - now).abs() <= SAME_BOOT_WITHIN_MS)
+}
+
+/// When this computer booted. Blocking.
+#[cfg(target_os = "linux")]
+pub fn boot_ms() -> Option<i64> {
+ let stat = std::fs::read_to_string("/proc/stat").ok()?;
+ let seconds: i64 = stat.lines().find_map(|line| line.strip_prefix("btime "))?.trim().parse().ok()?;
+ Some(seconds * 1000)
+}
+
+/// When this computer booted. Blocking.
+#[cfg(all(unix, not(target_os = "linux")))]
+pub fn boot_ms() -> Option<i64> {
+ let out = Command::new("sysctl").args(["-n", "kern.boottime"]).output().ok()?;
+ // { sec = 1793887393, usec = 0 } Thu Nov 5 ...
+ let text = String::from_utf8_lossy(&out.stdout).into_owned();
+ let seconds: i64 = text.split("sec = ").nth(1)?.split(',').next()?.trim().parse().ok()?;
+ Some(seconds * 1000)
+}
+
+/// When this computer booted.
+#[cfg(windows)]
+pub fn boot_ms() -> Option<i64> {
+ // SAFETY: takes nothing and only reads a counter.
+ let uptime = unsafe { windows_sys::Win32::System::SystemInformation::GetTickCount64() };
+ Some(crate::store::now_ms() - i64::try_from(uptime).ok()?)
+}
+
+/// What tells this process from a later one with the same pid. Blocking.
+#[cfg(unix)]
+pub fn process_start(pid: u32) -> Option<String> {
+ let out = Command::new("ps").args(["-o", "lstart=", "-p", &pid.to_string()]).output().ok()?;
+ let start = String::from_utf8_lossy(&out.stdout).trim().to_owned();
+ (!start.is_empty()).then_some(start)
+}
+
+/// Windows ends a job with the host that owns it, so nothing outlives it to check.
+#[cfg(windows)]
+pub fn process_start(_pid: u32) -> Option<String> {
+ None
+}
+
+/// Ends what a crashed host left running, if `pid` is still that process. Blocking.
+#[cfg(unix)]
+pub fn kill_if_same(pid: u32, start: &str) {
+ if process_start(pid).as_deref() != Some(start) {
+ return;
+ }
+ let Ok(group) = libc::pid_t::try_from(pid) else { return };
+ // SAFETY: only sends a signal; the check above says the group is still the server's.
+ unsafe { libc::kill(-group, libc::SIGKILL) };
+}
+
+#[cfg(windows)]
+pub fn kill_if_same(_pid: u32, _start: &str) {}
+
+/// Asks one process to end.
+#[cfg(unix)]
+pub fn end_process(pid: u32) {
+ let Ok(pid) = libc::pid_t::try_from(pid) else { return };
+ // SAFETY: only sends a signal to a pid a scan just found in the agent's tree.
+ unsafe { libc::kill(pid, libc::SIGTERM) };
+}
+
+/// Ends one process.
+#[cfg(windows)]
+pub fn end_process(pid: u32) {
+ use windows_sys::Win32::Foundation::CloseHandle;
+ use windows_sys::Win32::System::Threading::{OpenProcess, PROCESS_TERMINATE, TerminateProcess};
+ // SAFETY: the handle is checked, used once and closed; the pid came from a scan just now.
+ unsafe {
+ let handle = OpenProcess(PROCESS_TERMINATE, 0, pid);
+ if !handle.is_null() {
+ TerminateProcess(handle, 1);
+ CloseHandle(handle);
+ }
+ }
+}
diff --git a/host/src/dev_servers/ports.rs b/host/src/dev_servers/ports.rs
new file mode 100644
index 00000000..adc6ebd4
--- /dev/null
+++ b/host/src/dev_servers/ports.rs
@@ -0,0 +1,89 @@
+//! What listens on this computer, and the addresses clients show for it.
+
+use anyhow::{Result, anyhow};
+use serde::Serialize;
+use std::collections::BTreeMap;
+use std::net::{IpAddr, SocketAddr};
+
+/// A process listening on a TCP socket.
+#[derive(Clone, Debug)]
+pub struct Listening {
+ pub pid: u32,
+ pub name: String,
+ pub socket: SocketAddr,
+}
+
+/// One port as clients show it: `local` works on this computer, `remote` from other devices. Empty `remote`: the
+/// server listens only on this computer, as most dev servers do by default.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
+#[allow(clippy::struct_field_names, reason = "the wire's name")]
+pub struct Port {
+ pub port: u16,
+ pub local: String,
+ pub remote: Vec<String>,
+}
+
+/// Every TCP listener on the computer. Blocking.
+pub fn listening() -> Result<Vec<Listening>> {
+ let all = listeners::get_all().map_err(|error| anyhow!("{error}"))?;
+ Ok(all
+ .into_iter()
+ .filter(|l| l.protocol == listeners::Protocol::TCP && l.state == listeners::SocketState::Listen)
+ .map(|l| Listening { pid: l.process.pid, name: l.process.name, socket: l.socket })
+ .collect())
+}
+
+/// The sockets of `pids`, in a stable order so a scan can tell whether they changed.
+pub fn sockets_of(listening: &[Listening], pids: &[u32]) -> Vec<SocketAddr> {
+ let mut sockets: Vec<SocketAddr> = listening.iter().filter(|l| pids.contains(&l.pid)).map(|l| l.socket).collect();
+ sockets.sort();
+ sockets.dedup();
+ sockets
+}
+
+/// This computer's addresses, to notice when it moves to another network. Blocking, but starts no process.
+pub fn interfaces() -> Vec<IpAddr> {
+ let mut all: Vec<IpAddr> =
+ if_addrs::get_if_addrs().unwrap_or_default().iter().map(if_addrs::Interface::ip).collect();
+ all.sort();
+ all
+}
+
+/// The addresses for `sockets`. Blocking: reading this computer's addresses may start a process.
+pub fn urls(sockets: &[SocketAddr]) -> Vec<Port> {
+ urls_with(sockets, |port| {
+ let usual = crate::service::interface_addresses(port);
+ // With only a public address, what listens on all interfaces is open at that one: say so.
+ if usual.is_empty() { crate::service::public_addresses(port) } else { usual }
+ })
+}
+
+/// `reachable`: this computer's addresses other devices can reach, for a port.
+pub(super) fn urls_with(sockets: &[SocketAddr], reachable: impl Fn(u16) -> Vec<String>) -> Vec<Port> {
+ let mut by_port: BTreeMap<u16, Vec<SocketAddr>> = BTreeMap::new();
+ for socket in sockets {
+ by_port.entry(socket.port()).or_default().push(*socket);
+ }
+ by_port
+ .into_iter()
+ .map(|(port, sockets)| {
+ let everywhere = sockets.iter().any(|s| s.ip().is_unspecified());
+ let on_loopback = everywhere || sockets.iter().any(|s| s.ip().is_loopback());
+ let specific: Vec<String> = sockets
+ .iter()
+ .filter(|s| !s.ip().is_unspecified() && !s.ip().is_loopback())
+ .map(|s| match s {
+ SocketAddr::V4(s) => format!("http://{}:{port}", s.ip()),
+ SocketAddr::V6(s) => format!("http://[{}]:{port}", s.ip()),
+ })
+ .collect();
+ let remote = if everywhere { reachable(port) } else { specific.clone() };
+ let local = if on_loopback {
+ format!("http://localhost:{port}")
+ } else {
+ specific.first().cloned().unwrap_or_else(|| format!("http://localhost:{port}"))
+ };
+ Port { port, local, remote }
+ })
+ .collect()
+}
diff --git a/host/src/dev_servers/run.rs b/host/src/dev_servers/run.rs
new file mode 100644
index 00000000..1f433554
--- /dev/null
+++ b/host/src/dev_servers/run.rs
@@ -0,0 +1,223 @@
+//! Starting and stopping: a server is the host's own child in a tree of its own.
+
+use super::{
+ Leader, Live, Run, STOP_GRACE, STOP_WAIT, Saved, Status, check_room, detected, forget, logs, platform, report, save,
+};
+use crate::LockExt;
+use crate::agent::process::{self, Process};
+use crate::analytics::Event;
+use crate::hub::Hub;
+use crate::store::now_ms;
+use anyhow::{Context, Result, bail};
+use std::process::Stdio;
+use std::sync::Arc;
+use std::time::Duration;
+use tokio::sync::watch;
+
+const EXIT_POLL: Duration = Duration::from_millis(200);
+
+/// Adds a new server and starts it. `approved`: someone allowed it on a card.
+pub(super) async fn create(
+ hub: &Arc<Hub>,
+ bot: &str,
+ name: String,
+ command: String,
+ folder: String,
+ approved: bool,
+) -> Result<String> {
+ let id = uuid::Uuid::now_v7().to_string();
+ let saved = Saved {
+ id: id.clone(),
+ bot: bot.to_owned(),
+ name,
+ command,
+ folder,
+ created_at: now_ms(),
+ wanted: true,
+ approved,
+ leader: None,
+ boot_ms: None,
+ };
+ save(&hub.store, &saved);
+ hub.dev_servers.live.locked().insert(id.clone(), Live::stopped(saved));
+ launch(hub, &id).await?;
+ Ok(id)
+}
+
+/// Starts a stopped server: the host's own child in a tree of its own, its output going to its log.
+pub(super) async fn launch(hub: &Arc<Hub>, id: &str) -> Result<()> {
+ let saved = {
+ let mut live = hub.dev_servers.live.locked();
+ let entry = live.get_mut(id).context("unknown dev server")?;
+ if entry.run.is_some() || entry.status == Status::Starting {
+ // On its way already, and wanted after all.
+ entry.stop_asked = false;
+ return Ok(());
+ }
+ entry.begin(now_ms());
+ entry.saved.clone()
+ };
+ hub.emit_bot(&saved.bot);
+ // A task of its own: a request that goes away (a closed connection, a cancelled tool call) can't abandon it halfway.
+ tokio::spawn(start(hub.clone(), saved)).await?
+}
+
+async fn start(hub: Arc<Hub>, saved: Saved) -> Result<()> {
+ let spawned = spawn(&hub, &saved).await;
+ match &spawned {
+ Ok(()) => hub.dev_servers.wake.notify_one(),
+ Err(error) => {
+ let known = hub.dev_servers.live.locked().get_mut(&saved.id).map(|entry| {
+ entry.status = Status::Failed;
+ entry.saved.wanted = false;
+ save(&hub.store, &entry.saved);
+ });
+ if known.is_some() {
+ logs::note(&saved.id, &format!("{error:#}"));
+ }
+ hub.emit_bot(&saved.bot);
+ }
+ }
+ spawned
+}
+
+async fn spawn(hub: &Arc<Hub>, saved: &Saved) -> Result<()> {
+ // Not `shell::exec`: a command line may start with variables or chain several commands. The login shell's
+ // environment, never the agent's: that one can hold its API keys.
+ let mut command = crate::shell::line(&saved.command).tokio();
+ command
+ .current_dir(&saved.folder)
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .kill_on_drop(true);
+ process::own_tree(&mut command);
+ let mut child = command.spawn().with_context(|| format!("starting `{}`", saved.command))?;
+ let pid = child.id();
+ let stdout = child.stdout.take().expect("stdout is piped");
+ let stderr = child.stderr.take().expect("stderr is piped");
+ let process = Arc::new(tokio::sync::Mutex::new(Process::new(child)?));
+ logs::capture(&saved.id, stdout, stderr).await?;
+ let (leader, boot_ms) = tokio::task::spawn_blocking(move || {
+ let leader = pid.and_then(|pid| Some(Leader { pid, start: platform::process_start(pid)? }));
+ (leader, platform::boot_ms())
+ })
+ .await?;
+ let (stop, stop_seen) = watch::channel(false);
+ let (ended_tx, ended) = watch::channel(false);
+ let stopped = {
+ let mut live = hub.dev_servers.live.locked();
+ // Removed or stopped while it was starting: dropping `process` here ends it.
+ let entry = live.get_mut(&saved.id).context("unknown dev server")?;
+ let stopped = std::mem::take(&mut entry.stop_asked);
+ if stopped {
+ entry.ended(true, None);
+ } else {
+ entry.saved.wanted = true;
+ entry.saved.leader = leader;
+ entry.saved.boot_ms = boot_ms;
+ save(&hub.store, &entry.saved);
+ entry.run = Some(Run { stop, ended, process: process.clone() });
+ }
+ stopped
+ };
+ if stopped {
+ hub.emit_bot(&saved.bot);
+ } else {
+ tokio::spawn(supervise(hub.clone(), saved.id.clone(), process, stop_seen, ended_tx));
+ }
+ Ok(())
+}
+
+async fn supervise(
+ hub: Arc<Hub>,
+ id: String,
+ process: Arc<tokio::sync::Mutex<Process>>,
+ mut stop: watch::Receiver<bool>,
+ ended: watch::Sender<bool>,
+) {
+ let asked = loop {
+ tokio::select! {
+ // A dropped sender (the server was removed) asks too.
+ _ = stop.changed() => break true,
+ () = tokio::time::sleep(EXIT_POLL) => {
+ if process.lock().await.exited().unwrap_or(true) {
+ break false;
+ }
+ }
+ }
+ };
+ let code = {
+ let mut process = process.lock().await;
+ if asked {
+ process.stop_gracefully(STOP_GRACE).await;
+ } else {
+ process.kill().await;
+ }
+ process.exit_code()
+ };
+ finished(&hub, &id, asked, code);
+ ended.send_replace(true);
+}
+
+fn finished(hub: &Hub, id: &str, asked: bool, code: Option<i32>) {
+ let bot = {
+ let mut live = hub.dev_servers.live.locked();
+ let Some(entry) = live.get_mut(id) else { return };
+ entry.ended(asked, code);
+ if !asked {
+ save(&hub.store, &entry.saved);
+ let by = if entry.status == Status::Failed { "failed" } else { "exited" };
+ report(hub, Event::DevServerStopped, "by", by);
+ }
+ entry.saved.bot.clone()
+ };
+ hub.emit_bot(&bot);
+}
+
+/// Stops a server and waits until it ended; for what a bot left running through its shell, ends that.
+pub async fn stop(hub: &Hub, bot: &str, id: &str, by: &str) -> Result<()> {
+ if detected::stop(hub, bot, id)? {
+ report(hub, Event::DevServerStopped, "by", by);
+ return Ok(());
+ }
+ let ended = {
+ let mut live = hub.dev_servers.live.locked();
+ let entry = live.get_mut(id).filter(|entry| entry.saved.bot == bot).context("unknown dev server")?;
+ entry.saved.wanted = false;
+ save(&hub.store, &entry.saved);
+ entry.stop_asked = entry.run.is_none() && entry.status == Status::Starting;
+ entry.run.as_ref().map(Run::ask_to_stop)
+ };
+ if let Some(mut ended) = ended
+ && tokio::time::timeout(STOP_WAIT, ended.wait_for(|done| *done)).await.is_err()
+ {
+ tracing::warn!("a dev server didn't stop in time");
+ }
+ report(hub, Event::DevServerStopped, "by", by);
+ Ok(())
+}
+
+/// Starts it again, stopping it first if it runs. A stopped one would be one more, so the limit holds here too.
+pub async fn restart(hub: &Arc<Hub>, bot: &str, id: &str) -> Result<()> {
+ if hub.dev_servers.view(bot, id)?.status.active() {
+ stop(hub, bot, id, "restart").await?;
+ } else {
+ check_room(hub, bot)?;
+ }
+ launch(hub, id).await
+}
+
+pub fn remove(hub: &Hub, bot: &str, id: &str) -> Result<()> {
+ let removed = {
+ let mut live = hub.dev_servers.live.locked();
+ if live.get(id).is_none_or(|entry| entry.saved.bot != bot) {
+ bail!("unknown dev server");
+ }
+ live.remove(id)
+ };
+ drop(removed);
+ forget(&hub.store, id)?;
+ hub.emit_bot(bot);
+ Ok(())
+}
diff --git a/host/src/dev_servers/scan.rs b/host/src/dev_servers/scan.rs
new file mode 100644
index 00000000..75e68894
--- /dev/null
+++ b/host/src/dev_servers/scan.rs
@@ -0,0 +1,158 @@
+//! After a host restart, what was running starts again; from then on, what listens is read and clients told.
+
+use super::run::launch;
+use super::{DevServers, KV_PREFIX, Live, Saved, Status, detected, forget, platform, ports, save};
+use crate::LockExt;
+use crate::agent::process::Process;
+use crate::hub::Hub;
+use crate::store::now_ms;
+use anyhow::Result;
+use std::net::{IpAddr, SocketAddr};
+use std::sync::Arc;
+use std::time::Duration;
+
+/// A server that shows no port by now counts as running (a watch build may never listen).
+pub(super) const SETTLE_MS: i64 = 5_000;
+/// How often ports are read while a server is new, and after that.
+const SCAN_FAST: Duration = Duration::from_secs(1);
+const SCAN_SLOW: Duration = Duration::from_secs(10);
+const NEW_FOR_MS: i64 = 30_000;
+
+/// Brings back what was running before the host stopped, then keeps ports up to date.
+pub async fn scan_loop(hub: Arc<Hub>) {
+ if let Err(error) = resume(&hub).await {
+ tracing::warn!(error = format!("{error:#}"), "couldn't restore dev servers");
+ }
+ let mut interfaces = Vec::new();
+ loop {
+ scan(&hub, &mut interfaces).await;
+ let wait = if hub.dev_servers.any_new() { SCAN_FAST } else { SCAN_SLOW };
+ tokio::select! {
+ () = tokio::time::sleep(wait) => {}
+ () = hub.dev_servers.wake.notified() => {}
+ }
+ }
+}
+
+/// After a host restart a server that was running starts again. After a computer restart it stays stopped, one tap
+/// away: an abandoned server shouldn't come back at every login.
+async fn resume(hub: &Arc<Hub>) -> Result<()> {
+ let keys = hub.store.kv_prefix(KV_PREFIX);
+ let saved: Vec<Saved> = keys
+ .iter()
+ .filter_map(|key| hub.store.kv_get(key))
+ .filter_map(|json| serde_json::from_str(&json).ok())
+ .collect();
+ let booted = tokio::task::spawn_blocking(platform::boot_ms).await?;
+ let mut again = Vec::new();
+ for mut server in saved {
+ let bot_exists = hub.store.bot(&server.bot)?.is_some_and(|row| !row.deleted);
+ if !bot_exists {
+ forget(&hub.store, &server.id)?;
+ continue;
+ }
+ let same_boot = platform::same_boot(server.boot_ms, booted);
+ // A crashed host on Unix leaves the server holding its port.
+ if same_boot && let Some(leader) = server.leader.clone() {
+ tokio::task::spawn_blocking(move || platform::kill_if_same(leader.pid, &leader.start)).await?;
+ }
+ if server.wanted && same_boot {
+ again.push(server.id.clone());
+ } else if server.wanted {
+ server.wanted = false;
+ save(&hub.store, &server);
+ }
+ let bot = server.bot.clone();
+ hub.dev_servers.live.locked().insert(server.id.clone(), Live::stopped(server));
+ hub.emit_bot(&bot);
+ }
+ for id in again {
+ if let Err(error) = launch(hub, &id).await {
+ tracing::warn!(error = format!("{error:#}"), "couldn't restart a dev server");
+ }
+ }
+ Ok(())
+}
+
+impl DevServers {
+ fn any_new(&self) -> bool {
+ let now = now_ms();
+ self.live.locked().values().any(|live| {
+ live.status == Status::Starting
+ || (live.status == Status::Running && live.started_at.is_some_and(|at| now - at < NEW_FOR_MS))
+ })
+ }
+
+ fn agents_running(&self) -> Vec<detected::RunningAgent> {
+ let mut agents = self.agents.locked();
+ agents.retain(|_, agent| agent.acp.strong_count() > 0);
+ agents
+ .iter()
+ .filter_map(|(bot, agent)| {
+ Some(detected::RunningAgent {
+ bot: bot.clone(),
+ acp: agent.acp.upgrade()?,
+ programs: agent.programs.clone(),
+ })
+ })
+ .collect()
+ }
+}
+
+/// Reads what listens, and tells clients what changed. `known`: this computer's addresses at the last scan.
+async fn scan(hub: &Arc<Hub>, known: &mut Vec<IpAddr>) {
+ let servers = &hub.dev_servers;
+ let running: Vec<(String, Arc<tokio::sync::Mutex<Process>>)> = servers
+ .live
+ .locked()
+ .iter()
+ .filter_map(|(id, live)| Some((id.clone(), live.run.as_ref()?.process.clone())))
+ .collect();
+ let agents = servers.agents_running();
+ let had_detected = !servers.detected.locked().is_empty();
+ if running.is_empty() && agents.is_empty() && !had_detected {
+ return;
+ }
+ let read = tokio::task::spawn_blocking(|| anyhow::Ok((ports::listening()?, ports::interfaces()))).await;
+ let (listening, interfaces) = match read.map_err(anyhow::Error::from).flatten() {
+ Ok(read) => read,
+ Err(error) => {
+ tracing::warn!(error = format!("{error:#}"), "couldn't read listening ports");
+ return;
+ }
+ };
+ let moved = *known != interfaces;
+ *known = interfaces;
+ let pids: Vec<u32> = listening.iter().map(|l| l.pid).collect();
+ for (id, process) in running {
+ let members = process.lock().await.members(&pids);
+ let sockets = ports::sockets_of(&listening, &members);
+ update(hub, &id, sockets, moved).await;
+ }
+ detected::scan(hub, &agents, &listening, moved).await;
+}
+
+/// Records a server's sockets. `moved`: this computer's addresses changed, so those of a server on all of them did.
+async fn update(hub: &Hub, id: &str, sockets: Vec<SocketAddr>, moved: bool) {
+ let stale = hub.dev_servers.live.locked().get(id).is_some_and(|live| {
+ live.sockets != sockets || (moved && sockets.iter().any(|socket| socket.ip().is_unspecified()))
+ });
+ // Reading the addresses starts a process, so only when something changed.
+ let ports = if stale {
+ let sockets = sockets.clone();
+ tokio::task::spawn_blocking(move || ports::urls(&sockets)).await.ok()
+ } else {
+ None
+ };
+ let bot = {
+ let mut live = hub.dev_servers.live.locked();
+ let Some(entry) = live.get_mut(id) else { return };
+ // It may have ended while the addresses were read.
+ let ports = ports.filter(|_| entry.run.is_some());
+ if !entry.observed(sockets, ports, now_ms()) {
+ return;
+ }
+ entry.saved.bot.clone()
+ };
+ hub.emit_bot(&bot);
+}
diff --git a/host/src/dev_servers/tests.rs b/host/src/dev_servers/tests.rs
new file mode 100644
index 00000000..e1f5fd3e
--- /dev/null
+++ b/host/src/dev_servers/tests.rs
@@ -0,0 +1,257 @@
+use super::detected::{Detected, agent_programs, changes, servers_in};
+use super::logs::last_lines;
+use super::platform::same_boot;
+use super::ports::{Listening, Port, sockets_of, urls_with};
+use super::scan::SETTLE_MS;
+use super::tools::tidied;
+use super::{Live, Saved, Status};
+use crate::agent::process::{JobProcess, descendants, parse_ps};
+use std::collections::HashMap;
+use std::net::SocketAddr;
+use std::path::Path;
+
+fn socket(text: &str) -> SocketAddr {
+ text.parse().expect("a valid socket address in a test")
+}
+
+fn lan(port: u16) -> Vec<String> {
+ vec![format!("http://192.168.1.20:{port}")]
+}
+
+#[test]
+fn a_loopback_server_is_only_on_this_computer() {
+ let ports = urls_with(&[socket("127.0.0.1:5173")], lan);
+ assert_eq!(ports, [Port { port: 5173, local: "http://localhost:5173".into(), remote: vec![] }]);
+ let v6 = urls_with(&[socket("[::1]:5173")], lan);
+ assert_eq!(v6[0].remote, Vec::<String>::new());
+}
+
+#[test]
+fn a_server_on_all_interfaces_is_reachable_from_other_devices() {
+ let ports = urls_with(&[socket("0.0.0.0:3000")], lan);
+ assert_eq!(ports[0].local, "http://localhost:3000");
+ assert_eq!(ports[0].remote, ["http://192.168.1.20:3000"]);
+}
+
+#[test]
+fn a_server_on_one_address_is_shown_at_that_address() {
+ let ports = urls_with(&[socket("192.168.1.9:8080")], lan);
+ assert_eq!(ports[0].local, "http://192.168.1.9:8080");
+ assert_eq!(ports[0].remote, ["http://192.168.1.9:8080"]);
+}
+
+#[test]
+fn one_port_on_two_families_is_one_port() {
+ let ports = urls_with(&[socket("127.0.0.1:5173"), socket("[::1]:5173"), socket("127.0.0.1:8787")], lan);
+ assert_eq!(ports.iter().map(|p| p.port).collect::<Vec<_>>(), [5173, 8787]);
+}
+
+fn row(pid: u32, text: &str) -> Listening {
+ Listening { pid, name: "node".into(), socket: socket(text) }
+}
+
+#[test]
+fn sockets_belong_to_their_processes_in_a_stable_order() {
+ let listening = [row(1, "127.0.0.1:9000"), row(2, "127.0.0.1:3000"), row(2, "127.0.0.1:1000")];
+ assert_eq!(sockets_of(&listening, &[2]), [socket("127.0.0.1:1000"), socket("127.0.0.1:3000")]);
+}
+
+fn process(pid: u32, parent: u32, name: &str) -> JobProcess {
+ JobProcess { pid, parent, name: name.into() }
+}
+
+fn pids(servers: &[Detected]) -> Vec<Vec<u32>> {
+ servers.iter().map(|server| server.pids.clone()).collect()
+}
+
+#[test]
+fn what_a_helper_started_is_not_a_bots_server() {
+ let tree = [
+ process(10, 1, "claude"),
+ process(11, 10, "/opt/codync-host"),
+ process(12, 11, "node"),
+ process(13, 10, "sh"),
+ process(14, 13, "node"),
+ ];
+ let listening: Vec<Listening> = [12, 14].iter().map(|pid| row(*pid, &format!("127.0.0.1:{pid}00"))).collect();
+ assert_eq!(pids(&servers_in(&tree, "codync-host", &[], &listening)), [[14]]);
+ let windows = [process(20, 1, r"C:\bin\codync-hostw.exe"), process(21, 20, "node.exe"), process(22, 1, "node.exe")];
+ let listening = [row(21, "127.0.0.1:2100"), row(22, "127.0.0.1:2200")];
+ assert_eq!(pids(&servers_in(&windows, "codync-hostw.exe", &[], &listening)), [[22]]);
+}
+
+#[test]
+fn parent_links_that_loop_end() {
+ let tree = [process(1, 2, "a"), process(2, 1, "b")];
+ let listening = [row(1, "127.0.0.1:1000"), row(2, "127.0.0.1:2000")];
+ assert_eq!(pids(&servers_in(&tree, "codync-host", &[], &listening)), [[1], [2]]);
+}
+
+#[test]
+fn an_agents_own_listener_is_not_a_server_it_left_running() {
+ // What Windows lists (the whole job) and what a wrapper script gives on Unix: the real agent under another program.
+ let tree = [process(1, 900, "cmd.exe"), process(2, 1, r"C:\bin\opencode.exe"), process(3, 2, "node.exe")];
+ let listening = [row(2, "127.0.0.1:4096"), row(3, "127.0.0.1:5173")];
+ let programs = agent_programs("opencode", "opencode acp");
+ assert_eq!(pids(&servers_in(&tree, "codync-host", &programs, &listening)), [[3]]);
+ let unix = [process(2, 1, "/usr/local/bin/opencode")];
+ assert_eq!(pids(&servers_in(&unix, "codync-host", &programs, &listening)), Vec::<Vec<u32>>::new());
+}
+
+#[test]
+fn an_agents_programs_are_its_clis_and_its_commands_own() {
+ assert_eq!(agent_programs("opencode", "'/opt/my tools/opencode' acp"), ["opencode"]);
+ assert_eq!(agent_programs("custom", "/opt/my-agent --acp"), ["my-agent"]);
+ assert_eq!(agent_programs("custom", "FOO=1 BAR=2 my-agent"), ["my-agent"]);
+ assert_eq!(agent_programs("custom", r#""C:\tools\my-agent.exe" --acp"#), ["my-agent"]);
+ // These run servers just as well, so a bot on them still gets its servers shown.
+ for runtime in
+ ["python3 -u agent.py", "python3.12 agent.py", "npx -y @x/acp", "node adapter.js", "/bin/sh wrapper.sh"]
+ {
+ assert_eq!(agent_programs("custom", runtime), Vec::<String>::new(), "{runtime}");
+ }
+}
+
+#[test]
+fn processes_sharing_a_socket_are_one_server() {
+ // A server that forks after listening, and another on its own socket.
+ let tree = [process(30, 1, "python3"), process(31, 30, "python3"), process(40, 1, "node")];
+ let listening = [row(31, "127.0.0.1:21000"), row(30, "127.0.0.1:21000"), row(40, "127.0.0.1:5173")];
+ let servers = servers_in(&tree, "codync-host", &[], &listening);
+ assert_eq!(pids(&servers), [vec![30, 31], vec![40]]);
+ assert_eq!(servers[0].view().id, "detected:30");
+}
+
+#[test]
+fn ports_the_system_hands_out_are_not_a_servers() {
+ let tree = [process(1, 900, "node")];
+ assert_eq!(pids(&servers_in(&tree, "codync-host", &[], &[row(1, "127.0.0.1:49152")])), Vec::<Vec<u32>>::new());
+}
+
+fn found(pids: Vec<u32>) -> Detected {
+ Detected { pids, name: "node".into(), sockets: Vec::new(), ports: Vec::new() }
+}
+
+#[test]
+fn a_scan_tells_of_what_changed_and_counts_what_is_new() {
+ let before: HashMap<String, Vec<Detected>> =
+ [("a".to_owned(), vec![found(vec![1])]), ("b".to_owned(), vec![found(vec![2])])].into();
+ let now: HashMap<String, Vec<Detected>> =
+ [("a".to_owned(), vec![found(vec![1])]), ("c".to_owned(), vec![found(vec![3]), found(vec![4])])].into();
+ let (mut bots, new) = changes(&before, &now);
+ bots.sort();
+ assert_eq!(bots, ["b", "c"]);
+ assert_eq!(new, 2);
+}
+
+#[test]
+fn ps_rows_keep_names_with_spaces() {
+ let rows = parse_ps(" 10 1 /Applications/Some App/run\n bad row\n 11 10 sh\n 12 11\n");
+ assert_eq!(rows.iter().map(|r| (r.pid, r.parent)).collect::<Vec<_>>(), [(10, 1), (11, 10), (12, 11)]);
+ assert_eq!(rows[0].name, "/Applications/Some App/run");
+}
+
+#[test]
+fn a_tree_holds_only_what_its_leader_started() {
+ let rows = [process(10, 1, "agent"), process(11, 10, "sh"), process(12, 11, "node"), process(13, 1, "other")];
+ let pids: Vec<u32> = descendants(&rows, 10).iter().map(|p| p.pid).collect();
+ assert_eq!(pids, [11, 12]);
+}
+
+#[test]
+fn a_log_shows_its_last_lines() {
+ assert_eq!(last_lines("a\nb\nc\n", 2), "b\nc");
+ assert_eq!(last_lines("a", 5), "a");
+ assert_eq!(last_lines("", 5), "");
+}
+
+#[test]
+fn a_boot_is_the_same_only_when_both_times_are_known_and_close() {
+ assert!(same_boot(Some(1_000_000), Some(1_060_000)));
+ assert!(!same_boot(Some(1_000_000), Some(1_200_001)));
+ assert!(!same_boot(None, Some(1)));
+ assert!(!same_boot(Some(1), None));
+}
+
+#[test]
+fn one_folder_written_two_ways_is_one_folder() {
+ let plain = Path::new("/site/web");
+ for written in ["/site/web/", "/site/web/.", "/site/./web", "/site//web"] {
+ assert_eq!(tidied(Path::new(written)), plain, "{written}");
+ }
+}
+
+fn live() -> Live {
+ Live::stopped(Saved {
+ id: "a".into(),
+ bot: "b".into(),
+ name: "web".into(),
+ command: "npm run dev".into(),
+ folder: "/site".into(),
+ created_at: 0,
+ wanted: true,
+ approved: false,
+ leader: None,
+ boot_ms: None,
+ })
+}
+
+#[test]
+fn a_new_run_starts_with_nothing_of_the_last_one() {
+ let mut server = live();
+ server.ended(false, Some(3));
+ server.ports = vec![Port { port: 1, local: String::new(), remote: Vec::new() }];
+ server.begin(5);
+ assert_eq!((server.status, server.exit_code, server.started_at), (Status::Starting, None, Some(5)));
+ assert_eq!(server.ports, []);
+}
+
+#[test]
+fn how_a_run_ends_says_what_it_is_now() {
+ let ended = |asked, code| {
+ let mut server = live();
+ server.ended(asked, code);
+ (server.status, server.saved.wanted)
+ };
+ // Someone stopped it, whatever its code: it stays wanted until `stop` says otherwise.
+ assert_eq!(ended(true, None), (Status::Stopped, true));
+ assert_eq!(ended(true, Some(143)), (Status::Stopped, true));
+ // By itself: done, or failed, and it isn't brought back.
+ assert_eq!(ended(false, Some(0)), (Status::Stopped, false));
+ assert_eq!(ended(false, Some(3)), (Status::Failed, false));
+ assert_eq!(ended(false, None), (Status::Failed, false));
+}
+
+#[test]
+fn a_server_settles_on_its_first_socket_or_after_a_while() {
+ let mut server = live();
+ server.begin(0);
+ assert!(!server.observed(Vec::new(), None, SETTLE_MS - 1), "still starting");
+ assert_eq!(server.status, Status::Starting);
+ assert!(server.observed(Vec::new(), None, SETTLE_MS), "a watch build may never listen");
+ assert_eq!(server.status, Status::Running);
+
+ let mut server = live();
+ server.begin(0);
+ assert!(server.observed(vec![socket("127.0.0.1:1")], None, 1));
+ assert_eq!(server.status, Status::Running);
+}
+
+#[test]
+fn clients_hear_of_addresses_only_when_they_differ() {
+ let at =
+ |remote: &str| vec![Port { port: 3000, local: "http://localhost:3000".into(), remote: vec![remote.into()] }];
+ let sockets = vec![socket("0.0.0.0:3000")];
+ let mut server = live();
+ server.begin(0);
+ assert!(server.observed(sockets.clone(), Some(at("http://192.168.1.20:3000")), 1));
+ assert!(!server.observed(sockets.clone(), Some(at("http://192.168.1.20:3000")), 2), "the same network");
+ assert!(server.observed(sockets, Some(at("http://10.0.0.5:3000")), 3), "another network");
+ assert_eq!(server.ports[0].remote, ["http://10.0.0.5:3000"]);
+}
+
+#[test]
+fn a_clients_status_from_a_newer_host_reads_as_stopped() {
+ assert_eq!(serde_json::from_str::<Status>(r#""sleeping""#).expect("any text decodes"), Status::Stopped);
+ assert_eq!(serde_json::from_str::<Status>(r#""failed""#).expect("a known one decodes"), Status::Failed);
+}
diff --git a/host/src/dev_servers/tools.rs b/host/src/dev_servers/tools.rs
new file mode 100644
index 00000000..bacd8700
--- /dev/null
+++ b/host/src/dev_servers/tools.rs
@@ -0,0 +1,181 @@
+//! The bot's side, on the `chat` helper: a separate MCP server would add a process to every session.
+
+use super::run::{create, launch, stop};
+use super::{View, check_room, logs, report};
+use crate::analytics::Event;
+use crate::hub::Hub;
+use crate::store::{BotConfig, Permission};
+use anyhow::{Context, Result, anyhow, bail};
+use serde_json::{Value, json};
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+use std::time::Duration;
+use tokio::time::Instant;
+
+pub const START: &str = "start_dev_server";
+pub const TOOLS: [&str; 4] = [START, "list_dev_servers", "stop_dev_server", "dev_server_logs"];
+
+/// How long a start waits for a port or an early exit before it answers.
+const WAIT_FOR_PORT: Duration = Duration::from_secs(20);
+const WAIT_POLL: Duration = Duration::from_millis(200);
+/// Log lines a start's answer carries.
+const ANSWER_LINES: usize = 20;
+
+/// What a bot's instructions say about them.
+pub const BRIEF: &str = "Long-running programs: start a dev server, a watch build or anything else that keeps running with start_dev_server, not in the background of your shell. It keeps running when your session or agent stops, and the user sees its port and can stop it. Short commands stay in your shell.";
+
+pub fn tools() -> Vec<Value> {
+ vec![
+ json!({
+ "name": START,
+ "description": "Start a program that keeps running (a dev server, a watch build), run by Codync so it outlives your session and the user sees its port. Give the command as you'd run it in the foreground: it ends when its first process ends, so don't add & or nohup. Starting the same command in the same folder again returns the one already running. Waits up to 20 s for a port and answers with the status, ports and the end of its log. Keep secrets in the project's env files, not in the command: the user's apps show it.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "command": {"type": "string", "description": "The command line, e.g. npm run dev."},
+ "name": {"type": "string", "description": "A short name the user sees, e.g. web. Default: the folder's name."},
+ "folder": {"type": "string", "description": "Where to run it, absolute or relative to your working directory. Default: your working directory."},
+ },
+ "required": ["command"],
+ },
+ "annotations": {"readOnlyHint": false, "openWorldHint": true},
+ }),
+ json!({
+ "name": "list_dev_servers",
+ "description": "Your dev servers: id, name, command, status and ports. Includes what you left running through your shell, with managed false: that stops when your agent does.",
+ "inputSchema": {"type": "object", "properties": {}},
+ "annotations": {"readOnlyHint": true},
+ }),
+ json!({
+ "name": "stop_dev_server",
+ "description": "Stop one of your dev servers and everything it started.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {"id": {"type": "string"}},
+ "required": ["id"],
+ },
+ "annotations": {"readOnlyHint": false, "destructiveHint": true},
+ }),
+ json!({
+ "name": "dev_server_logs",
+ "description": "The end of a dev server's output, to see why it failed or what it's doing.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "id": {"type": "string"},
+ "lines": {"type": "integer", "description": "How many lines. Default 200, at most 1000."},
+ },
+ "required": ["id"],
+ },
+ "annotations": {"readOnlyHint": true},
+ }),
+ ]
+}
+
+pub async fn call(hub: &Arc<Hub>, bot: &str, name: &str, args: &Value) -> Result<Value> {
+ match name {
+ START => start(hub, bot, args).await,
+ "list_dev_servers" => Ok(json!({"servers": hub.dev_servers.wire(bot)})),
+ "stop_dev_server" => {
+ stop(hub, bot, arg(args, "id")?, "bot").await?;
+ Ok(json!({"stopped": true}))
+ }
+ "dev_server_logs" => {
+ let id = arg(args, "id")?;
+ hub.dev_servers.view(bot, id)?;
+ let lines = args["lines"].as_u64().map_or(logs::SHOWN_LINES, |n| usize::try_from(n).unwrap_or(usize::MAX));
+ Ok(json!({"log": logs::tail(id, lines.min(logs::MOST_LINES)).await?}))
+ }
+ _ => bail!("unknown tool"),
+ }
+}
+
+fn arg<'a>(args: &'a Value, key: &str) -> Result<&'a str> {
+ args[key].as_str().map(str::trim).filter(|v| !v.is_empty()).ok_or_else(|| anyhow!("{key} is required"))
+}
+
+async fn start(hub: &Arc<Hub>, bot: &str, args: &Value) -> Result<Value> {
+ let command = arg(args, "command")?.to_owned();
+ let cfg = hub.store.bot(bot)?.filter(|row| !row.deleted).map(|row| row.config).context("unknown bot")?;
+ let folder = folder_for(&cfg, args["folder"].as_str()).await?;
+ let on_a_card = cfg.permission != Permission::Auto;
+ let servers = &hub.dev_servers;
+ if let Some(id) = servers.same(bot, &folder, &command) {
+ // A stopped one comes back, with no second card if someone allowed it; under Auto nobody did.
+ if !servers.view(bot, &id)?.status.active() {
+ check_room(hub, bot)?;
+ if !servers.approved(&id) {
+ ask(hub, &cfg, &command, &folder).await?;
+ if on_a_card {
+ servers.note_approved(&hub.store, &id);
+ }
+ }
+ launch(hub, &id).await?;
+ }
+ return answer(hub, bot, &id, true).await;
+ }
+ check_room(hub, bot)?;
+ ask(hub, &cfg, &command, &folder).await?;
+ let name = args["name"]
+ .as_str()
+ .map(str::trim)
+ .filter(|name| !name.is_empty())
+ .map(str::to_owned)
+ .or_else(|| Path::new(&folder).file_name().map(|name| name.to_string_lossy().into_owned()))
+ .unwrap_or_else(|| "dev server".to_owned());
+ let id = match create(hub, bot, name, command, folder, on_a_card).await {
+ Ok(id) => id,
+ Err(error) => {
+ report(hub, Event::DevServerStarted, "outcome", "failed");
+ return Err(error);
+ }
+ };
+ answer(hub, bot, &id, false).await
+}
+
+/// Under Ask, waits on the approval card with the command and folder.
+async fn ask(hub: &Hub, cfg: &BotConfig, command: &str, folder: &str) -> Result<()> {
+ let detail = format!("{command}\n{folder}");
+ let answered = crate::chat::manage::approve(hub, cfg, "Start a dev server".to_owned(), detail).await;
+ if answered.is_err() {
+ report(hub, Event::DevServerStarted, "outcome", "refused");
+ }
+ answered
+}
+
+/// A folder must exist: the error then says so, not a failed start. Written one way, so a folder written two ways
+/// (`.`, a trailing separator) is one server.
+async fn folder_for(cfg: &BotConfig, asked: Option<&str>) -> Result<String> {
+ let asked = asked.map(str::trim).filter(|folder| !folder.is_empty());
+ let path = asked.map_or_else(|| PathBuf::from(&cfg.cwd), |folder| Path::new(&cfg.cwd).join(folder));
+ let found = tokio::fs::metadata(&path).await.is_ok_and(|meta| meta.is_dir());
+ if !found {
+ bail!("no folder at {}", path.display());
+ }
+ Ok(tidied(&path).to_string_lossy().into_owned())
+}
+
+pub(super) fn tidied(path: &Path) -> PathBuf {
+ path.components().collect()
+}
+
+/// Waits for a port or for it to end, then says how it went. A restart's answer comes the same way.
+async fn answer(hub: &Arc<Hub>, bot: &str, id: &str, reused: bool) -> Result<Value> {
+ let deadline = Instant::now() + WAIT_FOR_PORT;
+ let waiting = |view: &View| view.status.active() && view.ports.is_empty();
+ let mut view = hub.dev_servers.view(bot, id)?;
+ while waiting(&view) && Instant::now() < deadline {
+ tokio::time::sleep(WAIT_POLL).await;
+ view = hub.dev_servers.view(bot, id)?;
+ }
+ let outcome = match (view.status.active(), view.ports.is_empty()) {
+ (true, false) => "port",
+ (true, true) => "no_port",
+ (false, _) => "exited",
+ };
+ report(hub, Event::DevServerStarted, "outcome", outcome);
+ let mut answer = json!(view);
+ answer["reused"] = reused.into();
+ answer["log"] = logs::tail(id, ANSWER_LINES).await?.into();
+ Ok(answer)
+}
diff --git a/host/src/hub.rs b/host/src/hub.rs
index e40d8378..2eb5e874 100644
--- a/host/src/hub.rs
+++ b/host/src/hub.rs
@@ -116,6 +116,8 @@ pub struct Hub {
pub terms: Arc<crate::agent::term::Terms>,
/// Model lists being fetched (`agentModels`).
pub model_lists: crate::agent::auth::InFlight,
+ /// The programs bots keep running, and what they left running through their own shells.
+ pub dev_servers: crate::dev_servers::DevServers,
}
impl Hub {
@@ -156,6 +158,7 @@ impl Hub {
screen,
terms: Arc::default(),
model_lists: crate::agent::auth::InFlight::default(),
+ dev_servers: crate::dev_servers::DevServers::default(),
})
}
@@ -199,6 +202,7 @@ impl Hub {
if tokio::time::timeout(Duration::from_secs(5), futures::future::join_all(tasks)).await.is_err() {
tracing::warn!("some bots didn't stop within 5 s");
}
+ self.dev_servers.shutdown().await;
self.keep_awake.locked().set(false);
}
@@ -287,6 +291,7 @@ impl Hub {
let _ = self.send_cmd(id, Cmd::Shutdown);
self.bots.locked().remove(id);
self.runtime.locked().remove(id);
+ self.dev_servers.forget_bot(&self.store, id);
{
let _g = self.emit_lock.locked();
let rev = self.store.delete_bot(id)?;
diff --git a/host/src/hub/sync.rs b/host/src/hub/sync.rs
index 2a881a72..f341e021 100644
--- a/host/src/hub/sync.rs
+++ b/host/src/hub/sync.rs
@@ -18,6 +18,7 @@ impl Hub {
v["harnessMemoryShared"] = crate::agent::own_memory::shared(cfg).into();
v["sharedMemory"] = crate::chat::memory::shared(cfg).into();
v["memoryRev"] = self.store.memory_rev().into();
+ v["devServers"] = self.dev_servers.wire(&cfg.id);
}
let rt = if cfg.is_group() {
// A group has no agent: Fast mode belongs to its members.
diff --git a/host/src/main.rs b/host/src/main.rs
index 9cc61d73..6d7b3167 100644
--- a/host/src/main.rs
+++ b/host/src/main.rs
@@ -8,6 +8,7 @@ mod background;
mod chat;
mod cloud_cli;
mod compat;
+mod dev_servers;
mod environment;
mod hub;
mod icons;
@@ -489,9 +490,7 @@ async fn main() -> Result<()> {
Sub::Mcp { server: McpServer::Network { name, port } } => mcp::serve(name, port, mcp::Server::Network).await,
Sub::Mcp { server: McpServer::Local { connector, port } } => mcp::serve_local(connector, port).await,
Sub::Mcp { server: McpServer::Remote { connector, port } } => mcp::serve_remote(connector, port).await,
- Sub::Tui { url, token, port } => {
- tui::run(url.unwrap_or_else(|| format!("http://127.0.0.1:{port}")), token).await
- }
+ Sub::Tui { url, token, port } => tui::run(url, port, token).await,
}
}
diff --git a/host/src/mcp.rs b/host/src/mcp.rs
index bfbe2968..c796415c 100644
--- a/host/src/mcp.rs
+++ b/host/src/mcp.rs
@@ -78,6 +78,7 @@ pub async fn serve(bot: String, port: u16, server: Server) -> Result<()> {
list.extend(crate::chat::fallbacks::tools());
list.push(crate::chat::reactions::tool());
list.push(crate::chat::skills::tool());
+ list.extend(crate::dev_servers::tools());
}
("codync-chat", crate::chat::outbox::INSTRUCTIONS, tools)
}
@@ -162,6 +163,10 @@ async fn call(port: u16, token: &str, bot: &str, params: &Value, server: Server)
Server::Connectors => ("connectorCall", Duration::from_secs(90)),
Server::Routines => ("routineCall", Duration::from_secs(30)),
Server::Computer => ("computerCall", Duration::from_mins(1)),
+ // Starting a dev server may wait on an approval card, then for its port.
+ Server::Chat if params["name"] == crate::dev_servers::START => {
+ ("chatCall", crate::chat::manage::APPROVAL_TIMEOUT + Duration::from_secs(25))
+ }
Server::Chat => ("chatCall", Duration::from_secs(if params["name"] == "send_file" { 70 } else { 30 })),
Server::Team => ("teamCall", Duration::from_secs(30)),
Server::Manage => ("manageCall", crate::chat::manage::APPROVAL_TIMEOUT + Duration::from_secs(30)),
diff --git a/host/src/service/addresses.rs b/host/src/service/addresses.rs
index aeaf5a3b..233de8bb 100644
--- a/host/src/service/addresses.rs
+++ b/host/src/service/addresses.rs
@@ -12,6 +12,11 @@ pub fn addresses(port: u16) -> Vec<String> {
// Read once: every hello asks, and a bad entry warns once.
static EXTERNAL: LazyLock<Vec<String>> =
LazyLock::new(|| external_urls(&std::env::var("CODYNC_EXTERNAL_URL").unwrap_or_default()));
+ EXTERNAL.iter().cloned().chain(interface_addresses(port)).take(MAX_ADDRESSES).collect()
+}
+
+/// This computer's own addresses that other devices can reach, best first: Tailscale, then LAN.
+pub fn interface_addresses(port: u16) -> Vec<String> {
let mut tailscale = vec![];
let mut lan = vec![];
for iface in if_addrs::get_if_addrs().unwrap_or_default() {
@@ -42,7 +47,23 @@ pub fn addresses(port: u16) -> Vec<String> {
lan.sort_by_key(|ip| (lan_rank(*ip), *ip));
lan.dedup();
let lan = lan.into_iter().map(|ip| format!("http://{ip}:{port}"));
- EXTERNAL.iter().cloned().chain(tailscale).chain(lan).take(MAX_ADDRESSES).collect()
+ tailscale.into_iter().chain(lan).collect()
+}
+
+/// This computer's other addresses, for a server with neither Tailscale nor a private network.
+pub fn public_addresses(port: u16) -> Vec<String> {
+ let mut public: Vec<std::net::Ipv4Addr> = if_addrs::get_if_addrs()
+ .unwrap_or_default()
+ .iter()
+ .filter(|iface| !iface.is_loopback() && !is_container_bridge(&iface.name))
+ .filter_map(|iface| match iface.ip() {
+ std::net::IpAddr::V4(ip) if !ip.is_private() && !ip.is_link_local() => Some(ip),
+ _ => None,
+ })
+ .collect();
+ public.sort();
+ public.dedup();
+ public.into_iter().map(|ip| format!("http://{ip}:{port}")).collect()
}
/// Home networks first, then office ones, so the cap drops the private ranges container and VM networks favor.
diff --git a/host/src/service/mod.rs b/host/src/service/mod.rs
index 0d03acbf..c0053c69 100644
--- a/host/src/service/mod.rs
+++ b/host/src/service/mod.rs
@@ -17,7 +17,7 @@ use std::sync::OnceLock;
use std::time::{Duration, Instant};
mod addresses;
-pub use addresses::addresses;
+pub use addresses::{addresses, interface_addresses, public_addresses};
#[cfg(unix)]
mod unix;
diff --git a/host/src/tui/app/analytics.rs b/host/src/tui/app/analytics.rs
index 200ce59e..f7da2b5c 100644
--- a/host/src/tui/app/analytics.rs
+++ b/host/src/tui/app/analytics.rs
@@ -68,7 +68,7 @@ impl App {
overlay.or_else(|| (self.trace == TraceMode::Full).then_some(Screen::Trace))
}
- fn track(&self, event: Reported) {
+ pub(in crate::tui) fn track(&self, event: Reported) {
self.call("track", Track::body(Reporter::Tui, event), After::Tracked);
}
diff --git a/host/src/tui/app/bot.rs b/host/src/tui/app/bot.rs
index 2a4f848a..f9a9fdc6 100644
--- a/host/src/tui/app/bot.rs
+++ b/host/src/tui/app/bot.rs
@@ -68,6 +68,8 @@ pub struct Bot {
pub agent_step: Option<String>,
/// Agents of its chain resting now.
pub resting: Vec<Rest>,
+ /// What it keeps running.
+ pub dev_servers: Vec<super::super::manage::DevServer>,
pub connectors: Vec<String>,
pub skills: Vec<String>,
pub status: Status,
@@ -206,6 +208,7 @@ impl Bot {
self_fallbacks: v["selfFallbacks"].as_bool().unwrap_or(true),
agent_step: v["agentStep"]["agent"].as_str().map(str::to_owned),
resting: serde_json::from_value(v["resting"].clone()).unwrap_or_default(),
+ dev_servers: serde_json::from_value(v["devServers"].clone()).unwrap_or_default(),
connectors: strs(&v["connectors"]),
skills: strs(&v["skills"]),
status: match v["status"].as_str() {
diff --git a/host/src/tui/app/input.rs b/host/src/tui/app/input.rs
index 26cd514a..7e1852ce 100644
--- a/host/src/tui/app/input.rs
+++ b/host/src/tui/app/input.rs
@@ -410,6 +410,7 @@ impl App {
Some(Click::Composer) => self.start_typing(),
Some(Click::Steps) => self.toggle_steps(),
Some(Click::BotChat(entry)) => self.open_bot_chat(&entry),
+ Some(Click::DevServers) => self.open_dev_servers(),
Some(Click::Section(name)) => {
self.click_section(&name);
self.focus = Focus::Roster;
diff --git a/host/src/tui/app/mod.rs b/host/src/tui/app/mod.rs
index d5ca1877..a15c6a4e 100644
--- a/host/src/tui/app/mod.rs
+++ b/host/src/tui/app/mod.rs
@@ -59,6 +59,8 @@ pub struct App {
pub client: Client,
pub(super) tx: UnboundedSender<Msg>,
pub url: String,
+ /// Whether the host is this computer's. Attached with `--url` nothing tells: a tunnel's address looks local.
+ pub on_this_computer: bool,
pub host: String,
pub home: String,
/// The host's version (`hello`): features newer than `MIN_HOST` check it.
@@ -164,6 +166,7 @@ impl App {
client,
tx,
url,
+ on_this_computer: true,
host: String::new(),
home: String::new(),
host_version: String::new(),
diff --git a/host/src/tui/app/overlay_keys.rs b/host/src/tui/app/overlay_keys.rs
index 9858a25a..1185eecb 100644
--- a/host/src/tui/app/overlay_keys.rs
+++ b/host/src/tui/app/overlay_keys.rs
@@ -120,6 +120,7 @@ impl App {
Overlay::Group(g) => self.group_key(g, k),
Overlay::Memory(m) => self.memory_key(m, k),
Overlay::BotChat(c) => Self::bot_chat_key(c, k),
+ Overlay::DevServers(sheet) => self.dev_servers_key(sheet, k),
Overlay::Routines(l) => self.routines_key(l, k),
Overlay::Routine(f) => self.routine_key(f, k),
Overlay::Library(l) => self.library_key(l, k),
diff --git a/host/src/tui/app/slash.rs b/host/src/tui/app/slash.rs
index f95bb44c..0a7b6578 100644
--- a/host/src/tui/app/slash.rs
+++ b/host/src/tui/app/slash.rs
@@ -11,6 +11,7 @@ use super::{After, App, Bot, Editor};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SlashAction {
Fast,
+ DevServers,
Skill,
}
@@ -29,7 +30,7 @@ impl SlashCommand {
match self.action {
SlashAction::Skill if self.detail.is_empty() => self.title.clone(),
SlashAction::Skill => self.detail.replace('\n', " "),
- SlashAction::Fast => format!("{} · {}", self.title, self.detail),
+ SlashAction::Fast | SlashAction::DevServers => format!("{} · {}", self.title, self.detail),
}
}
}
@@ -50,11 +51,23 @@ impl App {
fn built_in(&self) -> Vec<SlashCommand> {
let bots = self.fast_bots();
let detail = match bots.as_slice() {
- [] => return vec![],
- [bot] if self.bot().is_some_and(|b| !b.group) => bot.fast_detail(),
- _ => group_fast_detail(&bots),
+ [] => None,
+ [bot] if self.bot().is_some_and(|b| !b.group) => Some(bot.fast_detail()),
+ _ => Some(group_fast_detail(&bots)),
};
- vec![SlashCommand { name: "fast".into(), title: "Fast mode".into(), detail, action: SlashAction::Fast }]
+ let fast = detail.map(|detail| SlashCommand {
+ name: "fast".into(),
+ title: "Fast mode".into(),
+ detail,
+ action: SlashAction::Fast,
+ });
+ let servers = self.bot().filter(|bot| !bot.dev_servers.is_empty()).map(|bot| SlashCommand {
+ name: "servers".into(),
+ title: "Dev servers".into(),
+ detail: bot.dev_servers.iter().map(|server| server.name.as_str()).collect::<Vec<_>>().join(", "),
+ action: SlashAction::DevServers,
+ });
+ fast.into_iter().chain(servers).collect()
}
/// Built-in commands, then the skills the bot (or any member of a group) has on, whose name
@@ -132,6 +145,10 @@ impl App {
self.flash(if on { "Fast mode off" } else { "Fast mode on" });
String::new()
}
+ SlashAction::DevServers => {
+ self.open_dev_servers();
+ String::new()
+ }
SlashAction::Skill => format!("/{} ", command.name),
};
if let Some(key) = self.selected.clone() {
@@ -249,6 +266,22 @@ mod tests {
assert!(!app.built_in_command("/fast"), "then it reaches the bots as typed");
}
+ #[tokio::test]
+ async fn servers_opens_the_sheet_only_while_the_bot_has_some() {
+ let mut app = app_with(&json!({"id": "b", "name": "Bot", "devServers": []}));
+ assert!(!names(&app).contains(&"servers".to_owned()));
+ assert!(!app.built_in_command("/servers"), "reaches the agent as typed");
+ assert!(app.overlays.is_empty());
+
+ let server = json!({"id": "a", "name": "web", "status": "running", "ports": [], "managed": true});
+ let mut app = app_with(&json!({"id": "b", "name": "Bot", "devServers": [server]}));
+ app.drafts.insert("b".into(), super::Editor::with("/"));
+ assert!(names(&app).contains(&"servers".to_owned()));
+ assert!(!app.built_in_command("/servers now"), "only the bare command");
+ assert!(app.built_in_command("/servers"));
+ assert!(matches!(app.overlays.last(), Some(super::super::Overlay::DevServers(_))));
+ }
+
#[tokio::test]
async fn sending_just_a_built_in_command_runs_it() {
let mut app = app_with(&json!({"id": "b", "name": "Bot", "fastModeSupport": "offered"}));
diff --git a/host/src/tui/app/tests.rs b/host/src/tui/app/tests.rs
index 4bec36aa..62b8adb1 100644
--- a/host/src/tui/app/tests.rs
+++ b/host/src/tui/app/tests.rs
@@ -24,6 +24,55 @@ async fn routines_keep_the_chat_draft_until_the_user_returns_to_chat() {
assert_eq!(app.drafts["b"].text, "My unfinished message");
}
+#[tokio::test]
+async fn the_dev_servers_sheet_offers_what_each_server_allows() {
+ use crate::tui::manage::DevServersSheet;
+ use crossterm::event::{KeyCode, KeyEvent};
+
+ fn sheet(app: &App) -> &DevServersSheet {
+ let Some(Overlay::DevServers(sheet)) = app.overlays.last() else { panic!("the sheet is open") };
+ sheet
+ }
+
+ let failed = json!({"id": "a", "name": "web", "command": "npm run dev", "folder": "/site", "status": "failed",
+ "ports": [], "startedAt": null, "exitCode": 3, "managed": true});
+ let shell = json!({"id": "detected:9", "name": "node", "command": "node", "folder": null, "status": "running",
+ "ports": [{"port": 5173, "local": "http://localhost:5173", "remote": []}], "startedAt": null, "exitCode": null,
+ "managed": false});
+ let mut app = test_app();
+ let bot = json!({"id": "b", "name": "Bot", "devServers": [failed, shell]});
+ app.bots.insert("b".into(), Bot::parse(&bot).expect("a bot with servers parses"));
+ app.selected = Some("b".into());
+ assert_eq!(app.bots["b"].dev_servers.len(), 2, "what the host sends decodes");
+
+ app.open_dev_servers();
+ assert_eq!(sheet(&app).selected, 0);
+
+ // Enter on one that failed reads why, and its log says how it ended.
+ app.on_key(KeyEvent::from(KeyCode::Enter));
+ let logs = sheet(&app).logs.as_ref().expect("the log opened");
+ assert_eq!(logs.detail, "npm run dev · Exit code 3");
+ app.on_key(KeyEvent::from(KeyCode::Char('r')));
+ assert!(sheet(&app).logs.is_some(), "a refresh stays in the log");
+ app.on_key(KeyEvent::from(KeyCode::Esc));
+ assert!(sheet(&app).logs.is_none(), "esc goes back to the list");
+
+ // One started through the shell has no log to read.
+ app.on_key(KeyEvent::from(KeyCode::Down));
+ assert_eq!(sheet(&app).selected, 1);
+ app.on_key(KeyEvent::from(KeyCode::Char('l')));
+ assert!(sheet(&app).logs.is_none());
+
+ // Attached from elsewhere, its address shows instead of a browser opening here.
+ app.on_this_computer = false;
+ app.on_key(KeyEvent::from(KeyCode::Enter));
+ let (hint, _) = app.hint.as_ref().expect("a hint shows");
+ assert!(hint.starts_with("http://localhost:5173 · "), "{hint}");
+
+ app.on_key(KeyEvent::from(KeyCode::Esc));
+ assert!(app.overlays.is_empty());
+}
+
#[test]
fn fuzzy_is_a_subsequence_match() {
assert!(fuzzy("rx", &["Rex"]));
diff --git a/host/src/tui/app/ui.rs b/host/src/tui/app/ui.rs
index bcafa4d3..fb4a07d8 100644
--- a/host/src/tui/app/ui.rs
+++ b/host/src/tui/app/ui.rs
@@ -5,8 +5,8 @@ use std::collections::BTreeMap;
use std::time::Instant;
use super::super::manage::{
- AgentSetup, AnalyticsSheet, BotChatSheet, Fields, Gear, Library, Market, MemorySheet, NetworkSheet, RoutineForm,
- RoutineList, SkillSheet,
+ AgentSetup, AnalyticsSheet, BotChatSheet, DevServersSheet, Fields, Gear, Library, Market, MemorySheet,
+ NetworkSheet, RoutineForm, RoutineList, SkillSheet,
};
use super::{Editor, Mark};
@@ -331,6 +331,8 @@ pub enum Overlay {
Memory(MemorySheet),
/// A read-only conversation between two bots.
BotChat(BotChatSheet),
+ /// A bot's dev servers.
+ DevServers(DevServersSheet),
Routines(RoutineList),
Routine(Box<RoutineForm>),
Library(Library),
@@ -363,6 +365,8 @@ pub enum Click {
Steps,
/// A bot-message row (entry id): opens the conversation.
BotChat(String),
+ /// The port in the chat's header: opens the bot's dev servers.
+ DevServers,
/// A section's label (its name): folds or unfolds it, like `z`.
Section(String),
}
diff --git a/host/src/tui/manage/dev_servers.rs b/host/src/tui/manage/dev_servers.rs
new file mode 100644
index 00000000..f8ab311e
--- /dev/null
+++ b/host/src/tui/manage/dev_servers.rs
@@ -0,0 +1,305 @@
+//! A bot's dev servers: `/servers` or a click on the port in the chat's header. Clients name a server and never send a
+//! command.
+
+use crossterm::event::{KeyCode, KeyEvent};
+use serde::Deserialize;
+use serde_json::json;
+
+use super::super::app::{After, App, Overlay, copy};
+use super::super::l10n::tr;
+use super::{Reply, open_browser};
+use crate::analytics::reported::{DevServerAction, Reported};
+use crate::dev_servers::Status;
+
+const STARTED_BY_SHELL: &str = "Started through the bot's shell: it stops with the bot";
+const ONLY_ON_COMPUTER: &str = "Only reachable on the computer";
+
+#[derive(Clone, Debug, Default, Deserialize)]
+#[serde(rename_all = "camelCase", default)]
+pub struct DevServer {
+ pub id: String,
+ pub name: String,
+ pub command: String,
+ pub status: Status,
+ pub ports: Vec<DevServerPort>,
+ pub exit_code: Option<i32>,
+ pub managed: bool,
+}
+
+#[derive(Clone, Debug, Default, Deserialize)]
+#[serde(default)]
+pub struct DevServerPort {
+ pub port: u16,
+ pub local: String,
+ pub remote: Vec<String>,
+}
+
+impl DevServer {
+ /// What its row shows beside the name.
+ pub fn value(&self) -> String {
+ match self.status {
+ Status::Starting => "Starting".to_owned(),
+ Status::Failed => "Failed to start".to_owned(),
+ Status::Stopped => "Stopped".to_owned(),
+ Status::Running if self.ports.is_empty() => "Running".to_owned(),
+ Status::Running => self.ports.iter().map(|p| format!(":{}", p.port)).collect::<Vec<_>>().join(" "),
+ }
+ }
+
+ fn opens(&self) -> bool {
+ self.status == Status::Running && !self.ports.is_empty()
+ }
+
+ fn restarts(&self) -> bool {
+ self.managed && self.status != Status::Starting
+ }
+
+ fn stops(&self) -> bool {
+ self.status.active()
+ }
+
+ fn removes(&self) -> bool {
+ self.managed && !self.status.active()
+ }
+
+ /// What the selected server's keys do: the sheet's footer offers only these.
+ pub fn key_hints(&self) -> Vec<&'static str> {
+ let mut keys = vec!["↑↓ select"];
+ if self.opens() {
+ keys.extend(["enter open", "c copy"]);
+ } else if self.managed {
+ keys.push("enter logs");
+ }
+ if self.managed {
+ keys.push("l logs");
+ }
+ if self.restarts() {
+ keys.push(if self.status.active() { "r restart" } else { "r start" });
+ }
+ if self.stops() {
+ keys.push("s stop");
+ }
+ if self.removes() {
+ keys.push("x remove");
+ }
+ keys.push("esc close");
+ keys
+ }
+
+ /// What the sheet says of the selected server beyond its row.
+ pub fn note(&self) -> String {
+ if self.managed { self.exit_note().unwrap_or_default() } else { tr(STARTED_BY_SHELL).into_owned() }
+ }
+
+ fn exit_note(&self) -> Option<String> {
+ let code = self.exit_code.filter(|_| self.status == Status::Failed)?;
+ Some(tr("Exit code {code}").replace("{code}", &code.to_string()))
+ }
+}
+
+/// What the chat's header shows of a bot's servers.
+#[derive(Debug, PartialEq, Eq)]
+pub enum DevServerSummary {
+ Running(String),
+ Starting,
+ Failed,
+}
+
+pub fn summary(servers: &[DevServer]) -> Option<DevServerSummary> {
+ let running: Vec<&DevServer> = servers.iter().filter(|s| s.status == Status::Running).collect();
+ let first = running.iter().find(|s| !s.ports.is_empty()).or_else(|| running.first());
+ if let Some(first) = first {
+ let label = first.ports.first().map_or_else(|| first.name.clone(), |p| format!(":{}", p.port));
+ let more = running.len() - 1;
+ return Some(DevServerSummary::Running(if more > 0 { format!("{label} +{more}") } else { label }));
+ }
+ if servers.iter().any(|s| s.status == Status::Starting) {
+ return Some(DevServerSummary::Starting);
+ }
+ servers.iter().any(|s| s.status == Status::Failed).then_some(DevServerSummary::Failed)
+}
+
+pub struct DevServersSheet {
+ pub bot: String,
+ pub selected: usize,
+ /// The selected server's log, once opened: `None` lists the servers.
+ pub logs: Option<LogsView>,
+}
+
+pub struct LogsView {
+ pub id: String,
+ pub name: String,
+ /// The line under its name: the command, and how it ended if it failed.
+ pub detail: String,
+ pub text: Option<String>,
+ pub scroll: usize,
+}
+
+impl App {
+ pub(in crate::tui) fn open_dev_servers(&mut self) {
+ let Some(bot) = self.bot().filter(|bot| !bot.dev_servers.is_empty()).map(|bot| bot.id.clone()) else { return };
+ self.overlays.push(Overlay::DevServers(DevServersSheet { bot, selected: 0, logs: None }));
+ }
+
+ /// The answer to `read_logs`, for the sheet still showing that server.
+ pub(super) fn dev_server_logs(&mut self, id: &str, text: String) {
+ for overlay in &mut self.overlays {
+ if let Overlay::DevServers(sheet) = overlay
+ && let Some(logs) = sheet.logs.as_mut().filter(|logs| logs.id == id)
+ {
+ logs.text = Some(text);
+ return;
+ }
+ }
+ }
+
+ fn servers_of(&self, bot: &str) -> Vec<DevServer> {
+ self.bots.get(bot).map(|bot| bot.dev_servers.clone()).unwrap_or_default()
+ }
+
+ pub(in crate::tui) fn dev_servers_key(&mut self, mut sheet: DevServersSheet, k: KeyEvent) -> Option<Overlay> {
+ if let Some(logs) = &mut sheet.logs {
+ match k.code {
+ KeyCode::Esc | KeyCode::Char('q') => sheet.logs = None,
+ KeyCode::Up | KeyCode::Char('k') => logs.scroll += 1,
+ KeyCode::Down | KeyCode::Char('j') => logs.scroll = logs.scroll.saturating_sub(1),
+ KeyCode::Char('r') => self.read_logs(&sheet.bot, &logs.id),
+ _ => {}
+ }
+ return Some(Overlay::DevServers(sheet));
+ }
+ let servers = self.servers_of(&sheet.bot);
+ if servers.is_empty() {
+ return None;
+ }
+ sheet.selected = sheet.selected.min(servers.len() - 1);
+ let server = &servers[sheet.selected];
+ let call = |app: &Self, method: &'static str| {
+ app.call(method, json!({"botId": sheet.bot, "id": server.id}), After::Nothing);
+ };
+ match k.code {
+ KeyCode::Esc | KeyCode::Char('q') => return None,
+ KeyCode::Up | KeyCode::Char('k') => sheet.selected = (sheet.selected + servers.len() - 1) % servers.len(),
+ KeyCode::Down | KeyCode::Char('j') => sheet.selected = (sheet.selected + 1) % servers.len(),
+ KeyCode::Enter if server.opens() => self.open_dev_server(server),
+ KeyCode::Enter | KeyCode::Char('l') if server.managed => {
+ sheet.logs = Some(self.logs_of(&sheet.bot, server));
+ }
+ KeyCode::Char('c') if server.opens() => self.copy_dev_server(server),
+ KeyCode::Char('r') if server.restarts() => call(self, "devServerRestart"),
+ KeyCode::Char('s') if server.stops() => call(self, "devServerStop"),
+ KeyCode::Char('x') if server.removes() => call(self, "devServerRemove"),
+ _ => {}
+ }
+ Some(Overlay::DevServers(sheet))
+ }
+
+ fn read_logs(&self, bot: &str, id: &str) {
+ self.call("devServerLogs", json!({"botId": bot, "id": id}), After::Sheet(Reply::DevServerLogs(id.to_owned())));
+ }
+
+ fn logs_of(&self, bot: &str, server: &DevServer) -> LogsView {
+ self.read_logs(bot, &server.id);
+ let detail = match server.exit_note() {
+ Some(note) => format!("{} · {note}", server.command),
+ None => server.command.clone(),
+ };
+ LogsView { id: server.id.clone(), name: server.name.clone(), detail, text: None, scroll: 0 }
+ }
+
+ /// In this computer's browser. Anywhere else (a tunnel looks the same from here) shows where it can be reached.
+ fn open_dev_server(&mut self, server: &DevServer) {
+ let Some(port) = server.ports.first() else { return };
+ if self.on_this_computer && open_browser(&port.local, &self.url) {
+ self.track_dev_server(DevServerAction::Open);
+ return;
+ }
+ let address = match port.remote.first() {
+ Some(address) => address.clone(),
+ None => format!("{} · {}", port.local, tr(ONLY_ON_COMPUTER)),
+ };
+ self.hint = Some((address, std::time::Instant::now() + std::time::Duration::from_secs(5)));
+ }
+
+ fn copy_dev_server(&mut self, server: &DevServer) {
+ let Some(port) = server.ports.first() else { return };
+ let here = self.on_this_computer;
+ copy(if here { &port.local } else { port.remote.first().unwrap_or(&port.local) });
+ self.track_dev_server(DevServerAction::Copy);
+ self.flash(if here || !port.remote.is_empty() { "Copied" } else { ONLY_ON_COMPUTER });
+ }
+
+ fn track_dev_server(&self, action: DevServerAction) {
+ self.track(Reported::DevServerAction { action });
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{DevServer, DevServerPort, DevServerSummary, Status, summary};
+
+ fn server(status: Status, port: Option<u16>) -> DevServer {
+ DevServer {
+ name: "watch".into(),
+ status,
+ ports: port.map(|port| DevServerPort { port, ..Default::default() }).into_iter().collect(),
+ managed: true,
+ ..Default::default()
+ }
+ }
+
+ #[test]
+ fn the_header_shows_a_port_and_how_many_more_run() {
+ assert_eq!(summary(&[]), None);
+ assert_eq!(summary(&[server(Status::Stopped, None)]), None);
+ assert_eq!(summary(&[server(Status::Running, Some(5173))]), Some(DevServerSummary::Running(":5173".into())));
+ let many =
+ [server(Status::Running, None), server(Status::Running, Some(5173)), server(Status::Running, Some(8787))];
+ assert_eq!(summary(&many), Some(DevServerSummary::Running(":5173 +2".into())));
+ assert_eq!(summary(&[server(Status::Running, None)]), Some(DevServerSummary::Running("watch".into())));
+ }
+
+ #[test]
+ fn running_outranks_starting_which_outranks_failed() {
+ let failed = server(Status::Failed, None);
+ assert_eq!(summary(&[failed.clone(), server(Status::Starting, None)]), Some(DevServerSummary::Starting));
+ assert_eq!(summary(std::slice::from_ref(&failed)), Some(DevServerSummary::Failed));
+ assert_eq!(summary(&[failed, server(Status::Running, Some(1))]), Some(DevServerSummary::Running(":1".into())));
+ }
+
+ #[test]
+ fn the_footer_offers_only_the_keys_that_apply() {
+ let keys = |server: &DevServer| server.key_hints().join(" · ");
+ assert_eq!(
+ keys(&server(Status::Running, Some(1))),
+ "↑↓ select · enter open · c copy · l logs · r restart · s stop · esc close"
+ );
+ assert_eq!(
+ keys(&server(Status::Running, None)),
+ "↑↓ select · enter logs · l logs · r restart · s stop · esc close"
+ );
+ assert_eq!(keys(&server(Status::Starting, None)), "↑↓ select · enter logs · l logs · s stop · esc close");
+ assert_eq!(
+ keys(&server(Status::Failed, None)),
+ "↑↓ select · enter logs · l logs · r start · x remove · esc close"
+ );
+ let shell = DevServer { managed: false, ..server(Status::Running, Some(1)) };
+ assert_eq!(keys(&shell), "↑↓ select · enter open · c copy · s stop · esc close");
+ }
+
+ #[test]
+ fn a_status_from_a_newer_host_reads_as_stopped() {
+ let server: DevServer = serde_json::from_str(r#"{"status": "sleeping", "managed": true}"#).expect("it decodes");
+ assert_eq!(server.status, Status::Stopped);
+ assert_eq!(server.value(), "Stopped");
+ }
+
+ #[test]
+ fn the_sheet_says_how_it_ended_or_that_it_ends_with_the_bot() {
+ let failed = DevServer { exit_code: Some(3), ..server(Status::Failed, None) };
+ assert_eq!(failed.note(), "Exit code 3");
+ assert_eq!(server(Status::Running, None).note(), "");
+ let shell = DevServer { managed: false, ..server(Status::Running, None) };
+ assert_eq!(shell.note(), "Started through the bot's shell: it stops with the bot");
+ }
+}
diff --git a/host/src/tui/manage/mod.rs b/host/src/tui/manage/mod.rs
index bac7ec8f..ec08b868 100644
--- a/host/src/tui/manage/mod.rs
+++ b/host/src/tui/manage/mod.rs
@@ -8,6 +8,7 @@
mod agent;
mod analytics;
mod bot_chat;
+mod dev_servers;
mod fields;
mod gear;
mod icons;
@@ -24,6 +25,7 @@ mod skill;
mod when;
pub use analytics::AnalyticsSheet;
+pub use dev_servers::{DevServer, DevServerSummary, DevServersSheet, LogsView, summary as dev_server_summary};
pub use fields::{handoff_fields, section_fields};
pub use gear::{Gear, GearRow};
pub use icons::icon_fields;
@@ -49,6 +51,8 @@ pub const REACTIONS: [&str; 6] = ["👍", "❤️", "😂", "🎉", "👀", "✅
/// Replies to the sheets' commands.
#[derive(Clone)]
pub enum Reply {
+ /// A dev server's log, by the server's id.
+ DevServerLogs(String),
Memory(String),
MemorySaved(String),
/// A note the bot's memory sheet has open.
diff --git a/host/src/tui/manage/replies.rs b/host/src/tui/manage/replies.rs
index 1f58ce47..4dd7c4d3 100644
--- a/host/src/tui/manage/replies.rs
+++ b/host/src/tui/manage/replies.rs
@@ -61,6 +61,10 @@ impl App {
Reply::CallEntries(call) => {
self.call_entries.insert(call, entries_of(&v));
}
+ Reply::DevServerLogs(id) => {
+ let text = v["text"].as_str().unwrap_or_default().to_owned();
+ self.dev_server_logs(&id, text);
+ }
Reply::BotChat { bot, peer } => {
let entries = entries_of(&v);
for o in &mut self.overlays {
@@ -301,6 +305,10 @@ impl App {
self.unfolded.retain(|id| !lines.contains(id));
self.flash(&e);
}
+ Reply::DevServerLogs(id) => {
+ self.flash(&e);
+ self.dev_server_logs(id, String::new());
+ }
Reply::BotChat { bot, peer } => {
for o in &mut self.overlays {
if let Overlay::BotChat(c) = o
diff --git a/host/src/tui/mod.rs b/host/src/tui/mod.rs
index 6763ad5b..cafec5f4 100644
--- a/host/src/tui/mod.rs
+++ b/host/src/tui/mod.rs
@@ -48,10 +48,14 @@ fn restore(enhanced: bool) {
let _ = terminal::disable_raw_mode();
}
-pub async fn run(url: String, token: Option<String>) -> Result<()> {
+/// `url`: the host to attach to, when not this computer's on `port`.
+pub async fn run(url: Option<String>, port: u16, token: Option<String>) -> Result<()> {
+ let on_this_computer = url.is_none();
+ let url = url.unwrap_or_else(|| format!("http://127.0.0.1:{port}"));
let client = net::Client::new(&url, token.as_deref());
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let mut app = app::App::new(client.clone(), tx.clone(), url);
+ app.on_this_computer = on_this_computer;
let mut drafts = match drafts::Drafts::load(&app.url).await {
Ok(saved) => {
app.drafts = saved.restore();
diff --git a/host/src/tui/view/chat.rs b/host/src/tui/view/chat.rs
index c7460c0d..17d4ebee 100644
--- a/host/src/tui/view/chat.rs
+++ b/host/src/tui/view/chat.rs
@@ -42,7 +42,8 @@ pub(super) fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {
Mark::Error => ("× error".to_owned(), t.red),
_ => (String::new(), t.dim),
};
- let sx = rput(buf, r.right() - 1, r.y, &status, ss.add_modifier(Modifier::BOLD));
+ let mut sx = rput(buf, r.right() - 1, r.y, &status, ss.add_modifier(Modifier::BOLD));
+ sx = super::dev_servers::in_header(buf, r, sx, app, &b);
let room = sx.saturating_sub(x + 2);
if b.group {
let names: Vec<String> = b.members.iter().map(|m| app.author_name(Some(m))).collect();
diff --git a/host/src/tui/view/dev_servers.rs b/host/src/tui/view/dev_servers.rs
new file mode 100644
index 00000000..8ca94067
--- /dev/null
+++ b/host/src/tui/view/dev_servers.rs
@@ -0,0 +1,98 @@
+//! The dev servers sheet: a line per server, and one server's log; and their summary in the chat's header.
+
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+
+use super::super::app::{App, Bot, Click};
+use super::super::l10n::tr;
+use super::super::manage::{DevServerSummary, DevServersSheet, LogsView, dev_server_summary};
+use super::buffer::{centered, frame_box, hline, put, rput};
+use super::style::theme;
+use crate::dev_servers::Status;
+
+const WIDTH: u16 = 84;
+
+/// The port in quiet text, left of the status; a click opens the servers. Returns where the header's free room ends.
+pub(super) fn in_header(buf: &mut Buffer, r: Rect, end: u16, app: &mut App, b: &Bot) -> u16 {
+ let t = theme();
+ let (text, style) = match dev_server_summary(&b.dev_servers) {
+ None => return end,
+ Some(DevServerSummary::Running(text)) => (text, t.dim),
+ Some(DevServerSummary::Starting) => (tr("Starting").into_owned(), t.dim),
+ Some(DevServerSummary::Failed) => (format!("× {}", tr("Failed to start")), t.red),
+ };
+ let right = if end < r.right() - 1 { end.saturating_sub(2) } else { end };
+ let start = rput(buf, right, r.y, &text, style);
+ app.hits.clicks.push((Rect::new(start, r.y, right.saturating_sub(start), 1), Click::DevServers));
+ start
+}
+
+pub(super) fn dev_servers(buf: &mut Buffer, area: Rect, app: &App, sheet: &DevServersSheet) {
+ match &sheet.logs {
+ Some(logs) => log_view(buf, area, logs),
+ None => list(buf, area, app, sheet),
+ }
+}
+
+fn list(buf: &mut Buffer, area: Rect, app: &App, sheet: &DevServersSheet) {
+ let t = theme();
+ let servers = app.bots.get(&sheet.bot).map(|bot| bot.dev_servers.as_slice()).unwrap_or_default();
+ let height = u16::try_from(servers.len()).unwrap_or(u16::MAX).saturating_add(7);
+ let r = centered(area, WIDTH, height.min(area.height.saturating_sub(2)));
+ let inner = frame_box(buf, r, t.text, t.panel, Some((&tr("Dev servers"), t.text)));
+ if inner.height < 4 {
+ return;
+ }
+ let selected = sheet.selected.min(servers.len().saturating_sub(1));
+ let rows = usize::from(inner.height.saturating_sub(3));
+ for (i, server) in servers.iter().take(rows).enumerate() {
+ let y = inner.y + u16::try_from(i).unwrap_or(0);
+ let chosen = i == selected;
+ let row = if chosen { t.sel.patch(t.panel) } else { t.panel };
+ for x in inner.x..inner.right() {
+ buf[(x, y)].set_style(row);
+ }
+ put(buf, inner.x, y, 2, if chosen { "▸" } else { " " }, t.text.patch(row));
+ put(buf, inner.x + 2, y, 18, &server.name, t.text.patch(row));
+ let style = if server.status == Status::Failed { t.red } else { t.dim };
+ put(buf, inner.x + 21, y, 20, &tr(&server.value()), style.patch(row));
+ put(buf, inner.x + 42, y, inner.width.saturating_sub(42), &server.command, t.dim.patch(row));
+ }
+ let Some(server) = servers.get(selected) else { return };
+ put(buf, inner.x + 2, inner.bottom() - 3, inner.width.saturating_sub(2), &server.note(), t.dim.patch(t.panel));
+ hline(buf, inner.x, inner.bottom() - 2, inner.width, t.dim.patch(t.panel));
+ let keys: Vec<String> = server.key_hints().into_iter().map(|key| tr(key).into_owned()).collect();
+ put(buf, inner.x, inner.bottom() - 1, inner.width, &format!(" {}", keys.join(" · ")), t.dim.patch(t.panel));
+}
+
+fn log_view(buf: &mut Buffer, area: Rect, logs: &LogsView) {
+ let t = theme();
+ let r = centered(area, WIDTH, area.height.saturating_sub(4));
+ let inner = frame_box(buf, r, t.text, t.panel, Some((&logs.name, t.text)));
+ if inner.height < 4 {
+ return;
+ }
+ put(buf, inner.x, inner.y, inner.width, &logs.detail, t.dim.patch(t.panel));
+ hline(buf, inner.x, inner.y + 1, inner.width, t.dim.patch(t.panel));
+ let body = Rect::new(inner.x, inner.y + 2, inner.width, inner.height - 4);
+ match &logs.text {
+ None => {
+ put(buf, body.x, body.y, body.width, &tr("Loading…"), t.dim.patch(t.panel));
+ }
+ Some(text) if text.is_empty() => {
+ put(buf, body.x, body.y, body.width, &tr("No output yet"), t.dim.patch(t.panel));
+ }
+ Some(text) => {
+ let lines: Vec<&str> = text.lines().collect();
+ let height = usize::from(body.height);
+ let end = lines.len().saturating_sub(logs.scroll).max(height.min(lines.len()));
+ let start = end.saturating_sub(height);
+ for (i, line) in lines[start..end].iter().enumerate() {
+ let y = body.y + u16::try_from(i).unwrap_or(0);
+ put(buf, body.x, y, body.width, line, t.text.patch(t.panel));
+ }
+ }
+ }
+ hline(buf, inner.x, inner.bottom() - 2, inner.width, t.dim.patch(t.panel));
+ put(buf, inner.x, inner.bottom() - 1, inner.width, &tr(" ↑↓ scroll · r refresh · esc back"), t.dim.patch(t.panel));
+}
diff --git a/host/src/tui/view/help.rs b/host/src/tui/view/help.rs
index 0d09eba8..986b4848 100644
--- a/host/src/tui/view/help.rs
+++ b/host/src/tui/view/help.rs
@@ -53,7 +53,7 @@ const HELP: [(&str, &str, &str); 75] = [
("TYPE", "alt b / f", "word left / right"),
("TYPE", "^w ^u", "delete word / line"),
("TYPE", "@name", "group: ask just that bot"),
- ("TYPE", "/", "commands: /fast, skills"),
+ ("TYPE", "/", "commands: /fast, /servers, skills"),
("BOTS", "n", "new bot"),
("BOTS", "m", "new group chat"),
("BOTS", "e", "settings, or edit a group"),
diff --git a/host/src/tui/view/mod.rs b/host/src/tui/view/mod.rs
index fba5e14c..5b23044d 100644
--- a/host/src/tui/view/mod.rs
+++ b/host/src/tui/view/mod.rs
@@ -12,6 +12,7 @@ mod bot_chat;
mod buffer;
mod chat;
mod computer_access;
+mod dev_servers;
mod fallbacks;
mod forms;
mod goto;
diff --git a/host/src/tui/view/overlay.rs b/host/src/tui/view/overlay.rs
index ad7178c1..82ed893f 100644
--- a/host/src/tui/view/overlay.rs
+++ b/host/src/tui/view/overlay.rs
@@ -142,6 +142,7 @@ pub(super) fn overlay(buf: &mut Buffer, area: Rect, app: &mut App, top: &Overlay
Overlay::Pair(code) => pair(buf, area, app, code),
Overlay::Memory(m) => super::super::sheets::memory(buf, area, app, m),
Overlay::BotChat(c) => super::bot_chat::bot_chat(buf, area, app, c),
+ Overlay::DevServers(sheet) => super::dev_servers::dev_servers(buf, area, app, sheet),
Overlay::Routines(l) => super::super::sheets::routines(buf, area, app, l),
Overlay::Routine(f) => super::super::sheets::routine(buf, area, f),
Overlay::Library(l) => super::super::sheets::library(buf, area, app, l),
diff --git a/host/src/usage/command.rs b/host/src/usage/command.rs
index a940fa93..a3277d36 100644
--- a/host/src/usage/command.rs
+++ b/host/src/usage/command.rs
@@ -42,7 +42,7 @@ pub(super) async fn output(
/// Drop CSI colour sequences (`ESC [ … m`). Other characters stay, including
/// the cursor-position query a Windows console sends.
-pub(super) fn strip_ansi(text: &str) -> String {
+pub(crate) fn strip_ansi(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
diff --git a/host/src/usage/mod.rs b/host/src/usage/mod.rs
index 48f4dd4c..b73c8bee 100644
--- a/host/src/usage/mod.rs
+++ b/host/src/usage/mod.rs
@@ -24,6 +24,7 @@ mod opencode;
mod vibe;
pub use claude::{ingest_claude_rate_limit, ingest_statusline};
+pub(crate) use command::strip_ansi;
use crate::LockExt;
use crate::hub::Hub;
diff --git a/host/tests/common/host.rs b/host/tests/common/host.rs
index d417a712..a08425c7 100644
--- a/host/tests/common/host.rs
+++ b/host/tests/common/host.rs
@@ -34,6 +34,12 @@ impl Host {
Self { child, home, base, token }
}
+ /// Kills the host outright, as a crash would. `restart` starts it again.
+ pub fn crash(&mut self) {
+ let _ = self.child.kill();
+ let _ = self.child.wait();
+ }
+
/// Stops the host, lets `between` change its files, and starts it again on the same data.
pub async fn restart(&mut self, between: impl FnOnce(&std::path::Path)) {
super::stop(&mut self.child);
diff --git a/host/tests/dev_server_e2e.rs b/host/tests/dev_server_e2e.rs
new file mode 100644
index 00000000..44b51f94
--- /dev/null
+++ b/host/tests/dev_server_e2e.rs
@@ -0,0 +1,512 @@
+//! Dev servers through a real host: it runs them, so they outlive the agent; clients see their ports and can stop them;
+//! what a bot leaves running through its shell only shows.
+
+#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
+
+mod common;
+
+use common::host::Host;
+use serde_json::{Value, json};
+use std::net::{TcpListener, TcpStream};
+use std::path::{Path, PathBuf};
+use std::process::Command;
+use std::time::{Duration, Instant};
+
+fn free_port() -> u16 {
+ TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
+}
+
+/// A free port below where the system hands out its own, the range a server someone opens sits in.
+fn free_low_port() -> u16 {
+ (20_000..32_000).find(|port| TcpListener::bind(("127.0.0.1", *port)).is_ok()).unwrap()
+}
+
+fn serves(port: u16) -> bool {
+ TcpStream::connect(("127.0.0.1", port)).is_ok()
+}
+
+fn server_command(port: u16) -> String {
+ format!("{} -m http.server {port} --bind 127.0.0.1", common::python())
+}
+
+/// A program that keeps running and never listens.
+fn sleeper(seconds: u32) -> String {
+ format!("{} -c \"import time; time.sleep({seconds})\"", common::python())
+}
+
+fn kill(pid: &str) {
+ let mut command = Command::new(if cfg!(windows) { "taskkill" } else { "kill" });
+ if cfg!(windows) {
+ command.args(["/F", "/PID", pid])
+ } else {
+ command.args(["-KILL", pid])
+ };
+ command.status().unwrap();
+}
+
+async fn start(host: &Host, bot: &str, command: &str, name: &str) -> Value {
+ let arguments = json!({"command": command, "name": name});
+ host.call("chatCall", json!({"botId": bot, "name": "start_dev_server", "arguments": arguments})).await
+}
+
+async fn servers(host: &Host, bot: &str) -> Vec<Value> {
+ common::bot(&host.snapshot().await, bot)["devServers"].as_array().unwrap().clone()
+}
+
+async fn workspace(host: &Host, bot: &str) -> PathBuf {
+ PathBuf::from(common::bot(&host.snapshot().await, bot)["cwd"].as_str().unwrap())
+}
+
+async fn wait_for<F: Fn(&[Value]) -> bool>(host: &Host, bot: &str, what: &str, done: F) -> Vec<Value> {
+ let deadline = Instant::now() + Duration::from_secs(20);
+ loop {
+ let list = servers(host, bot).await;
+ if done(&list) {
+ return list;
+ }
+ assert!(Instant::now() < deadline, "{what}: {list:?}");
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+}
+
+/// Waits until the first server runs on `port`.
+async fn wait_running(host: &Host, bot: &str, port: u16) {
+ wait_for(host, bot, "running with its port", |list| {
+ list.first().is_some_and(|s| s["status"] == "running" && s["ports"][0]["port"] == port)
+ })
+ .await;
+}
+
+async fn wait_closed(port: u16) {
+ let deadline = Instant::now() + Duration::from_secs(15);
+ while serves(port) {
+ assert!(Instant::now() < deadline, "port {port} stayed open");
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+}
+
+async fn stop(host: &Host, bot: &str, id: &Value, port: u16) {
+ host.call("devServerStop", json!({"botId": bot, "id": id})).await;
+ wait_closed(port).await;
+}
+
+async fn agent_bot(host: &Host, port: u16) -> String {
+ let script = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/shell_server_agent.py");
+ let command = format!("{} {port}", common::python_agent(&script));
+ let bot = json!({"name": "Builder", "backend": "custom", "command": command, "connectors": [], "permission": "auto", "notify": false});
+ host.call("createBot", bot).await["bot"]["id"].as_str().unwrap().to_owned()
+}
+
+#[tokio::test]
+async fn a_server_outlives_its_agent_and_shows_its_port() {
+ let host = Host::start().await;
+ let bot = agent_bot(&host, 0).await;
+ host.reply(&bot, "hello").await;
+ let port = free_port();
+
+ let started = start(&host, &bot, &server_command(port), "web").await;
+ assert_eq!(started["status"], "running", "{started}");
+ assert_eq!(started["ports"][0]["port"], port);
+ assert_eq!(started["ports"][0]["local"], format!("http://localhost:{port}"));
+ assert_eq!(started["ports"][0]["remote"], json!([]), "it listens on loopback only");
+ assert!(serves(port));
+
+ let listed = servers(&host, &bot).await;
+ assert_eq!(listed.len(), 1);
+ assert_eq!(listed[0]["name"], "web");
+ assert_eq!(listed[0]["managed"], true);
+
+ let agent = std::fs::read_to_string(workspace(&host, &bot).await.join("agent.pid")).unwrap();
+ kill(agent.trim());
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ assert!(serves(port), "the server died with the agent");
+ assert_eq!(servers(&host, &bot).await[0]["status"], "running");
+
+ stop(&host, &bot, &started["id"], port).await;
+}
+
+/// lifecycle.rs stops an agent right after a routine's run with no other session open. Windows can't tell this fixture
+/// from one with a dev server of its own (`background_work`), so its agent stays there.
+#[cfg(unix)]
+#[tokio::test]
+async fn a_server_outlives_the_agent_of_a_routine_run() {
+ let host = Host::start().await;
+ let bot = agent_bot(&host, 0).await;
+ let port = free_port();
+ let started = start(&host, &bot, &server_command(port), "web").await;
+
+ let routine = json!({"botId": bot, "name": "once", "instruction": "go", "triggers": [{"type": "webhook"}], "timeoutSeconds": 30});
+ let routine = host.call("saveRoutine", routine).await["routine"]["id"].clone();
+ host.call("runRoutine", json!({"botId": bot, "id": routine})).await;
+ common::eventually("the run succeeded", Duration::from_secs(25), async || {
+ host.call("routines", json!({"botId": bot})).await["runs"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .any(|run| run["routineId"] == routine && run["status"] == "succeeded")
+ })
+ .await;
+ let agent = std::fs::read_to_string(workspace(&host, &bot).await.join("agent.pid")).unwrap();
+ common::eventually("the run's agent stopped", Duration::from_secs(20), async || {
+ !Command::new("kill").args(["-0", agent.trim()]).status().unwrap().success()
+ })
+ .await;
+
+ assert!(serves(port), "the server died with the agent");
+ assert_eq!(servers(&host, &bot).await[0]["status"], "running");
+ stop(&host, &bot, &started["id"], port).await;
+}
+
+#[tokio::test]
+async fn a_client_stops_restarts_reads_and_removes_a_server() {
+ let host = Host::start().await;
+ let bot = host.bot("Builder", "auto").await;
+ let port = free_port();
+ let started = start(&host, &bot, &server_command(port), "web").await;
+ let id = started["id"].clone();
+
+ stop(&host, &bot, &id, port).await;
+ let list = wait_for(&host, &bot, "stopped", |list| list[0]["status"] == "stopped").await;
+ assert_eq!(list[0]["ports"], json!([]));
+
+ host.call("devServerRestart", json!({"botId": bot, "id": id})).await;
+ wait_running(&host, &bot, port).await;
+ assert!(serves(port));
+
+ let logs = host.call("devServerLogs", json!({"botId": bot, "id": id})).await;
+ assert!(logs["text"].is_string(), "{logs}");
+
+ host.call("devServerRemove", json!({"botId": bot, "id": id})).await;
+ wait_closed(port).await;
+ assert_eq!(servers(&host, &bot).await, Vec::<Value>::new());
+ let error = host.refused("devServerStop", json!({"botId": bot, "id": id})).await;
+ assert!(error.contains("unknown dev server"), "{error}");
+}
+
+#[tokio::test]
+async fn a_bot_only_reaches_its_own_servers() {
+ let host = Host::start().await;
+ let (owner, other) = (host.bot("Owner", "auto").await, host.bot("Other", "auto").await);
+ let port = free_port();
+ let started = start(&host, &owner, &server_command(port), "web").await;
+ let id = started["id"].clone();
+ let stop_other = json!({"botId": other, "name": "stop_dev_server", "arguments": {"id": id}});
+ assert!(host.refused("chatCall", stop_other).await.contains("unknown dev server"));
+ let logs = json!({"botId": other, "name": "dev_server_logs", "arguments": {"id": id}});
+ assert!(host.refused("chatCall", logs).await.contains("unknown dev server"));
+ assert!(serves(port));
+ stop(&host, &owner, &id, port).await;
+}
+
+#[tokio::test]
+async fn the_same_command_is_one_server_and_a_bot_runs_at_most_five() {
+ let host = Host::start().await;
+ let bot = host.bot("Builder", "auto").await;
+ let port = free_port();
+ let first = start(&host, &bot, &server_command(port), "web").await;
+ let again = start(&host, &bot, &server_command(port), "web").await;
+ assert_eq!(first["id"], again["id"]);
+ assert_eq!(again["reused"], true);
+ // The same folder written another way is still the same server.
+ let arguments = json!({"command": server_command(port), "folder": "."});
+ let dotted = host.call("chatCall", json!({"botId": bot, "name": "start_dev_server", "arguments": arguments})).await;
+ assert_eq!(first["id"], dotted["id"], "{dotted}");
+ assert_eq!(servers(&host, &bot).await.len(), 1);
+
+ // Without a port a start waits its whole time, so one of these.
+ start(&host, &bot, &sleeper(300), "watch").await;
+ for n in 0..3 {
+ start(&host, &bot, &server_command(free_port()), &format!("s{n}")).await;
+ }
+ let arguments = json!({"command": sleeper(400)});
+ let refused =
+ host.refused("chatCall", json!({"botId": bot, "name": "start_dev_server", "arguments": arguments})).await;
+ assert!(refused.contains("at most 5"), "{refused}");
+
+ let list = wait_for(&host, &bot, "a server without a port settles", |list| {
+ list.iter().filter(|s| s["status"] == "running").count() == 5
+ })
+ .await;
+ assert_eq!(list.iter().filter(|s| s["ports"] == json!([])).count(), 1);
+
+ // A person starting a stopped one is held to the limit too.
+ stop(&host, &bot, &first["id"], port).await;
+ start(&host, &bot, &server_command(free_port()), "s3").await;
+ let refused = host.refused("devServerRestart", json!({"botId": bot, "id": first["id"]})).await;
+ assert!(refused.contains("at most 5"), "{refused}");
+ assert!(!serves(port));
+}
+
+#[tokio::test]
+async fn a_failed_start_says_why_and_a_bot_can_read_it() {
+ let host = Host::start().await;
+ let bot = host.bot("Builder", "auto").await;
+ let failing = if cfg!(windows) { "echo no such script & exit 3" } else { "echo no such script; exit 3" };
+ let answer = start(&host, &bot, failing, "docs").await;
+ assert_eq!(answer["status"], "failed", "{answer}");
+ assert_eq!(answer["exitCode"], 3);
+ assert!(answer["log"].as_str().unwrap().contains("no such script"), "{answer}");
+
+ let arguments = json!({"id": answer["id"]});
+ let logs = host.call("chatCall", json!({"botId": bot, "name": "dev_server_logs", "arguments": arguments})).await;
+ assert!(logs["log"].as_str().unwrap().contains("no such script"), "{logs}");
+ // A program that ends by itself isn't brought back.
+ assert_eq!(servers(&host, &bot).await[0]["status"], "failed");
+}
+
+#[tokio::test]
+async fn a_host_restart_brings_back_what_was_running_only() {
+ let mut host = Host::start().await;
+ let bot = host.bot("Builder", "auto").await;
+ let (kept, stopped) = (free_port(), free_port());
+ let first = start(&host, &bot, &server_command(kept), "kept").await;
+ let second = start(&host, &bot, &server_command(stopped), "stopped").await;
+ stop(&host, &bot, &second["id"], stopped).await;
+
+ host.restart(|_| {}).await;
+
+ let list = wait_for(&host, &bot, "the running one is back", |list| {
+ list.iter().any(|s| s["id"] == first["id"] && s["status"] == "running" && s["ports"][0]["port"] == kept)
+ })
+ .await;
+ assert!(serves(kept));
+ assert!(!serves(stopped));
+ assert_eq!(list.iter().find(|s| s["id"] == second["id"]).unwrap()["status"], "stopped");
+ stop(&host, &bot, &first["id"], kept).await;
+}
+
+#[tokio::test]
+async fn a_crashed_host_doesnt_leave_its_server_holding_the_port() {
+ let mut host = Host::start().await;
+ let bot = host.bot("Builder", "auto").await;
+ let port = free_port();
+ // A line for each run, to tell the next one from what the crash left. On Windows a job ends with its host.
+ let command =
+ if cfg!(windows) { server_command(port) } else { format!("echo $$ >> runs; exec {}", server_command(port)) };
+ let started = start(&host, &bot, &command, "web").await;
+ assert_eq!(started["status"], "running", "{started}");
+
+ host.crash();
+ host.restart(|_| {}).await;
+
+ wait_running(&host, &bot, port).await;
+ assert!(serves(port));
+ if cfg!(unix) {
+ let runs = std::fs::read_to_string(workspace(&host, &bot).await.join("runs")).unwrap();
+ let runs: Vec<&str> = runs.lines().collect();
+ assert_eq!(runs.len(), 2, "{runs:?}");
+ assert_ne!(runs[0], runs[1]);
+ assert!(!Command::new("kill").args(["-0", runs[0]]).status().unwrap().success(), "the old one still runs");
+ }
+ stop(&host, &bot, &started["id"], port).await;
+}
+
+/// What a computer restart looks like to the host: these servers last ran on an earlier boot.
+fn from_an_earlier_boot(home: &Path) {
+ let db = rusqlite::Connection::open(home.join("codync.db")).unwrap();
+ db.execute("UPDATE kv SET v = json_set(v, '$.bootMs', 1000) WHERE k LIKE 'dev-server:%'", []).unwrap();
+}
+
+#[tokio::test]
+async fn after_a_computer_restart_a_server_stays_stopped_until_someone_starts_it() {
+ let mut host = Host::start().await;
+ let bot = host.bot("Builder", "auto").await;
+ let port = free_port();
+ let started = start(&host, &bot, &server_command(port), "web").await;
+
+ host.restart(from_an_earlier_boot).await;
+ let stopped = |list: &[Value]| list.first().is_some_and(|s| s["status"] == "stopped");
+ wait_for(&host, &bot, "listed as stopped", stopped).await;
+ // Long enough for a start it shouldn't have made.
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ assert!(stopped(&servers(&host, &bot).await));
+ assert!(!serves(port));
+
+ // Nor at the next host start.
+ host.restart(|_| {}).await;
+ wait_for(&host, &bot, "still stopped", stopped).await;
+ tokio::time::sleep(Duration::from_secs(1)).await;
+ assert!(stopped(&servers(&host, &bot).await));
+ assert!(!serves(port));
+
+ host.call("devServerRestart", json!({"botId": bot, "id": started["id"]})).await;
+ wait_running(&host, &bot, port).await;
+ stop(&host, &bot, &started["id"], port).await;
+}
+
+/// Sends a start and hangs up a moment later, as a cancelled tool call or a dying helper does.
+async fn start_and_hang_up(host: &Host, body: &Value) {
+ use tokio::io::AsyncWriteExt as _;
+ let address = host.base.trim_start_matches("http://");
+ let mut socket = tokio::net::TcpStream::connect(address).await.unwrap();
+ let body = body.to_string();
+ let request = format!(
+ "POST /api/chatCall HTTP/1.1\r\nHost: {address}\r\nAuthorization: Bearer {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}",
+ host.token,
+ body.len(),
+ );
+ socket.write_all(request.as_bytes()).await.unwrap();
+ tokio::time::sleep(Duration::from_millis(3)).await;
+}
+
+#[tokio::test]
+async fn a_start_whose_request_goes_away_still_settles() {
+ let host = Host::start().await;
+ let bot = host.bot("Builder", "auto").await;
+ let port = free_port();
+ let arguments = json!({"command": server_command(port), "name": "web"});
+ let body = json!({"botId": bot, "name": "start_dev_server", "arguments": arguments});
+ // A hang-up before the host read the request leaves no row, so try again: that start is what's under test.
+ let deadline = Instant::now() + Duration::from_secs(20);
+ while servers(&host, &bot).await.is_empty() {
+ assert!(Instant::now() < deadline, "the host never read the request");
+ start_and_hang_up(&host, &body).await;
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+ wait_running(&host, &bot, port).await;
+ let id = servers(&host, &bot).await[0]["id"].clone();
+ stop(&host, &bot, &id, port).await;
+ wait_for(&host, &bot, "stopped", |list| list[0]["status"] == "stopped").await;
+}
+
+#[tokio::test]
+async fn deleting_a_bot_ends_its_servers() {
+ let host = Host::start().await;
+ let bot = host.bot("Builder", "auto").await;
+ let port = free_port();
+ start(&host, &bot, &server_command(port), "web").await;
+ assert!(serves(port));
+ host.call("deleteBot", json!({"botId": bot})).await;
+ wait_closed(port).await;
+}
+
+#[tokio::test]
+async fn under_ask_a_start_needs_a_turn_to_ask_in() {
+ let host = Host::start().await;
+ let bot = host.bot("Builder", "ask").await;
+ let arguments = json!({"command": sleeper(300)});
+ let refused =
+ host.refused("chatCall", json!({"botId": bot, "name": "start_dev_server", "arguments": arguments})).await;
+ assert!(refused.contains("didn't allow"), "{refused}");
+ assert_eq!(servers(&host, &bot).await, Vec::<Value>::new());
+}
+
+/// What makes the fixture agent call the tool through its real chat helper, in a turn.
+fn start_through_agent(command: &str) -> String {
+ format!("CHAT start_dev_server {}", json!({"command": command, "name": "web"}))
+}
+
+async fn entry(host: &Host, bot: &str, found: impl Fn(&Value) -> bool) -> Value {
+ let deadline = Instant::now() + Duration::from_secs(40);
+ loop {
+ let history = host.call("history", json!({"botId": bot})).await;
+ if let Some(entry) = history["entries"].as_array().unwrap().iter().find(|e| found(e)) {
+ return entry.clone();
+ }
+ assert!(Instant::now() < deadline, "{bot}: {history}");
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+}
+
+/// Has the agent start `command`, answers its card with `option`, and returns the agent's reply.
+async fn through_card(host: &Host, bot: &str, command: &str, option: &str, check: impl Fn(&str)) -> String {
+ host.call("send", json!({"botId": bot, "text": start_through_agent(command)})).await;
+ let card = entry(host, bot, |e| {
+ e["kind"] == "permission" && e["data"]["status"] == "pending" && e["data"]["title"] == "Start a dev server"
+ })
+ .await;
+ check(card["data"]["detail"].as_str().unwrap());
+ host.call("respondPermission", json!({"entryId": card["id"], "optionId": option})).await;
+ let reply =
+ entry(host, bot, |e| e["kind"] == "agent" && e["data"]["final"] == true && e["turn"] == card["turn"]).await;
+ reply["data"]["text"].as_str().unwrap().to_owned()
+}
+
+async fn cards(host: &Host, bot: &str) -> usize {
+ let history = host.call("history", json!({"botId": bot})).await;
+ history["entries"].as_array().unwrap().iter().filter(|e| e["kind"] == "permission").count()
+}
+
+#[tokio::test]
+async fn under_ask_a_start_waits_for_its_card() {
+ let host = Host::start().await;
+ let bot = host.fixture_bot("Builder", "team_agent.py", "").await;
+ host.call("updateBot", json!({"id": bot, "permission": "ask"})).await;
+
+ let denied = free_port();
+ let reply = through_card(&host, &bot, &server_command(denied), "deny", |_| {}).await;
+ assert!(reply.starts_with("Refused: ") && reply.contains("didn't allow"), "{reply}");
+ assert_eq!(servers(&host, &bot).await, Vec::<Value>::new());
+ assert!(!serves(denied));
+
+ let folder = workspace(&host, &bot).await;
+ let port = free_port();
+ let command = server_command(port);
+ let reply = through_card(&host, &bot, &command, "allow", |detail| {
+ assert!(detail.contains(&command) && detail.contains(folder.to_str().unwrap()), "{detail}");
+ })
+ .await;
+ assert!(reply.starts_with("Done: "), "{reply}");
+ assert!(serves(port));
+
+ // Allowed once, so a stopped one comes back with no second card.
+ let id = servers(&host, &bot).await[0]["id"].clone();
+ stop(&host, &bot, &id, port).await;
+ let before = cards(&host, &bot).await;
+ host.reply(&bot, &start_through_agent(&command)).await;
+ assert!(serves(port));
+ assert_eq!(cards(&host, &bot).await, before);
+ stop(&host, &bot, &id, port).await;
+}
+
+#[tokio::test]
+async fn a_server_nobody_allowed_gets_its_card_once_the_bot_is_under_ask() {
+ let host = Host::start().await;
+ let bot = host.fixture_bot("Builder", "team_agent.py", "").await;
+ host.call("updateBot", json!({"id": bot, "permission": "auto"})).await;
+ let port = free_port();
+ let command = server_command(port);
+ let started = start(&host, &bot, &command, "web").await;
+ stop(&host, &bot, &started["id"], port).await;
+ host.call("updateBot", json!({"id": bot, "permission": "ask"})).await;
+
+ let reply = through_card(&host, &bot, &command, "deny", |_| {}).await;
+ assert!(reply.starts_with("Refused: "), "{reply}");
+ assert!(!serves(port));
+
+ let reply = through_card(&host, &bot, &command, "allow", |_| {}).await;
+ assert!(reply.starts_with("Done: "), "{reply}");
+ assert!(serves(port));
+
+ stop(&host, &bot, &started["id"], port).await;
+ let before = cards(&host, &bot).await;
+ host.reply(&bot, &start_through_agent(&command)).await;
+ assert_eq!(cards(&host, &bot).await, before, "now someone has allowed it");
+ stop(&host, &bot, &started["id"], port).await;
+}
+
+#[tokio::test]
+async fn what_an_agent_leaves_running_shows_and_can_be_stopped() {
+ let host = Host::start().await;
+ let port = free_low_port();
+ let bot = agent_bot(&host, port).await;
+ host.reply(&bot, "run it").await;
+ let list = wait_for(&host, &bot, "the agent's server shows", |list| {
+ list.iter().any(|s| s["managed"] == false && s["ports"][0]["port"] == port)
+ })
+ .await;
+ let found = list.iter().find(|s| s["managed"] == false).unwrap();
+ assert_eq!(found["status"], "running");
+ assert!(found["id"].as_str().unwrap().starts_with("detected:"));
+
+ // It can't start again, so asking leaves it running.
+ let refused = host.refused("devServerRestart", json!({"botId": bot, "id": found["id"]})).await;
+ assert!(refused.contains("unknown dev server"), "{refused}");
+ assert!(serves(port));
+
+ stop(&host, &bot, &found["id"], port).await;
+ wait_for(&host, &bot, "it no longer shows", <[Value]>::is_empty).await;
+ // An id that was never found stops nothing.
+ let error = host.refused("devServerStop", json!({"botId": bot, "id": "detected:1"})).await;
+ assert!(error.contains("unknown dev server"), "{error}");
+}
diff --git a/host/tests/e2e/wire_shape.rs b/host/tests/e2e/wire_shape.rs
index 4f339078..807f0344 100644
--- a/host/tests/e2e/wire_shape.rs
+++ b/host/tests/e2e/wire_shape.rs
@@ -158,6 +158,13 @@ async fn wire_shape_matches_the_snapshot() {
.await;
let made = host.wait_for(&lead, |e| e["kind"] == "agent" && e["data"]["final"] == true).await;
assert!(made["data"]["text"].as_str().unwrap().starts_with("Done: "), "{made}");
+ // A running dev server: its `devServers`.
+ let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
+ let arguments =
+ json!({"command": format!("{} -m http.server {port} --bind 127.0.0.1", common::python()), "name": "web"});
+ let server =
+ host.call("chatCall", json!({"botId": lead, "name": "start_dev_server", "arguments": arguments})).await;
+ assert_eq!(server["ports"][0]["port"], port, "{server}");
// A bot in a roster section: its `section`.
host.call("updateBot", json!({"id": bot, "section": "Work"})).await;
diff --git a/host/tests/fixtures/shell_server_agent.py b/host/tests/fixtures/shell_server_agent.py
new file mode 100644
index 00000000..0f2d6d2b
--- /dev/null
+++ b/host/tests/fixtures/shell_server_agent.py
@@ -0,0 +1,46 @@
+"""ACP agent that, like a coding agent's shell tool, leaves a web server running as its own child. Run as
+`shell_server_agent.py <port>`; port 0 starts none. It writes its PID to agent.pid in its folder and answers each
+prompt "ok"."""
+
+import json
+import os
+import subprocess
+import sys
+
+PORT = int(sys.argv[1])
+server = None
+
+
+def send(value):
+ sys.stdout.write(json.dumps({"jsonrpc": "2.0", **value}) + "\n")
+ sys.stdout.flush()
+
+
+with open("agent.pid", "w", encoding="utf-8") as pid:
+ pid.write(str(os.getpid()))
+
+for line in sys.stdin:
+ message = json.loads(line)
+ method, params = message.get("method"), message.get("params") or {}
+ if "id" not in message or method is None:
+ continue
+ if method == "initialize":
+ send({"id": message["id"], "result": {"protocolVersion": 1, "agentCapabilities": {"loadSession": True}}})
+ elif method == "session/new":
+ send({"id": message["id"], "result": {"sessionId": "s1"}})
+ elif method == "session/load":
+ send({"id": message["id"], "result": {}})
+ elif method == "session/prompt":
+ if PORT and server is None:
+ server = subprocess.Popen(
+ [sys.executable, "-m", "http.server", str(PORT), "--bind", "127.0.0.1"],
+ # On Windows a child starting on this process's stdin hangs while the loop below is reading it.
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ )
+ update = {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "ok"}}
+ send({"method": "session/update", "params": {"sessionId": params["sessionId"], "update": update}})
+ send({"id": message["id"], "result": {"stopReason": "end_turn"}})
+ else:
+ send({"id": message["id"], "result": {}})
diff --git a/host/tests/fixtures/team_agent.py b/host/tests/fixtures/team_agent.py
index f4b829f1..f7c0106c 100644
--- a/host/tests/fixtures/team_agent.py
+++ b/host/tests/fixtures/team_agent.py
@@ -119,9 +119,9 @@ def prompt(request):
update({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": reply}})
send({"id": request["id"], "result": {"stopReason": "end_turn"}})
return
- if text.split("\n\n")[-1].startswith("MANAGE "):
- tool, arguments = text.split("\n\n")[-1].split(" ", 2)[1:]
- response = mcp_call("manage", tool, json.loads(arguments))
+ if text.split("\n\n")[-1].startswith(("MANAGE ", "CHAT ")):
+ helper, tool, arguments = text.split("\n\n")[-1].split(" ", 2)
+ response = mcp_call(helper.lower(), tool, json.loads(arguments))
reply = ("Refused: " if response.get("isError") else "Done: ") + response["content"][0]["text"]
update({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": reply}})
send({"id": request["id"], "result": {"stopReason": "end_turn"}})
diff --git a/host/tests/fixtures/wire-shape.json b/host/tests/fixtures/wire-shape.json
index e2dbdc78..8288eaaf 100644
--- a/host/tests/fixtures/wire-shape.json
+++ b/host/tests/fixtures/wire-shape.json
@@ -17,6 +17,21 @@
"event:bot.bot.cwd": "string",
"event:bot.bot.deleted": "bool",
"event:bot.bot.description": "string",
+ "event:bot.bot.devServers": "array",
+ "event:bot.bot.devServers[]": "object",
+ "event:bot.bot.devServers[].command": "string",
+ "event:bot.bot.devServers[].exitCode": "null",
+ "event:bot.bot.devServers[].folder": "string",
+ "event:bot.bot.devServers[].id": "string",
+ "event:bot.bot.devServers[].managed": "bool",
+ "event:bot.bot.devServers[].name": "string",
+ "event:bot.bot.devServers[].ports": "array",
+ "event:bot.bot.devServers[].ports[]": "object",
+ "event:bot.bot.devServers[].ports[].local": "string",
+ "event:bot.bot.devServers[].ports[].port": "number",
+ "event:bot.bot.devServers[].ports[].remote": "array",
+ "event:bot.bot.devServers[].startedAt": "number",
+ "event:bot.bot.devServers[].status": "string",
"event:bot.bot.fallbacks": "array",
"event:bot.bot.fastMode": "bool",
"event:bot.bot.fastModeIssue": "null",
diff --git a/web/app/docs/pages.ts b/web/app/docs/pages.ts
index f6b7df40..8095cefa 100644
--- a/web/app/docs/pages.ts
+++ b/web/app/docs/pages.ts
@@ -55,6 +55,11 @@ export const docSections: { title: string; pages: DocPage[] }[] = [
{
title: "What bots can do",
pages: [
+ {
+ slug: "dev-servers",
+ title: "Dev servers",
+ description: "Let a bot keep a dev server running on your computer, see its port from any device, and stop it.",
+ },
{
slug: "routines",
title: "Routines",
diff --git a/web/content/docs/bots.mdx b/web/content/docs/bots.mdx
index c50bd12a..f4cc939f 100644
--- a/web/content/docs/bots.mdx
+++ b/web/content/docs/bots.mdx
@@ -22,7 +22,7 @@ The host on your computer runs every bot. A bot's agent starts when you send it
## Where to change a bot's settings
-- **iPhone:** open the bot's chat and tap its name at the top. The tabs are **Details**, **Library**, **Memory** and **Settings**. **Details** shows its instructions, agent, model and routines; **Settings** shows the rest, including the Codync skills and connectors it passes on. Changes save as you edit. You can also touch and hold the bot in the list and choose **Edit profile**.
+- **iPhone:** open the bot's chat and tap its name at the top. The tabs are **Details**, **Library**, **Memory** and **Settings**. **Details** shows its [dev servers](/docs/dev-servers), instructions, agent, model and routines; **Settings** shows the rest, including the Codync skills and connectors it passes on. Changes save as you edit. You can also touch and hold the bot in the list and choose **Edit profile**.
- **Desktop:** click the bot's name at the top of the chat to open the details panel, with the same tabs. Changes save as you edit. You can also right-click the bot in the sidebar and choose **Edit Profile…**
- **Android:** the same sheet and tabs as the iPhone.
- **Terminal UI:** select the bot and press `e` for settings. Shift+Left and Shift+Right move between **Details**, **Library**, **Memory** and **Settings**. Press Ctrl+S to save, or Esc to drop your changes.
@@ -77,7 +77,7 @@ The **Permissions** setting decides how much the agent does on its own before it
Bots made before Codync 2.34 keep the setting they had. With any setting, your agent's own settings still apply: if Claude Code's permission rules block a tool, it stays blocked. In the terminal UI this field is called **Approvals**, and ←/→ goes through the same choices.
-The same setting covers changes a bot makes to other bots with **Manage the team**: unless it's Approve automatically, each change waits for your Allow. The bots it creates get the same setting.
+The same setting covers changes a bot makes to other bots with **Manage the team**: unless it's Approve automatically, each change waits for your Allow. The bots it creates get the same setting. It also covers [starting a dev server](/docs/dev-servers#start-one): unless it's Approve automatically, the start waits for your Allow.
How approval cards work: [Conversations](/docs/conversations#approval-cards).
@@ -132,7 +132,7 @@ You never start a session yourself. Codync starts a fresh one on its own when a
- **Desktop:** right-click the bot in the sidebar, then **Delete**.
- **Terminal UI:** press `x`.
-Confirm with **Delete bot and its conversation**. Deleting your lead bot leaves you without one until you pick another; Open Live Mode then asks which bot. The bot's chat and settings go away and it leaves any group chats it was in. Files it changed on your computer stay as they are, and so does its personal workspace folder.
+Confirm with **Delete bot and its conversation**. Deleting your lead bot leaves you without one until you pick another; Open Live Mode then asks which bot. The bot's chat and settings go away and it leaves any group chats it was in. Its [dev servers](/docs/dev-servers) stop and are removed. Files it changed on your computer stay as they are, and so does its personal workspace folder.
## Copy a bot's setup
diff --git a/web/content/docs/conversations.mdx b/web/content/docs/conversations.mdx
index cd047d32..1bc52eea 100644
--- a/web/content/docs/conversations.mdx
+++ b/web/content/docs/conversations.mdx
@@ -113,9 +113,10 @@ The quick reactions are 👍 ❤️ 😂 🎉 👀 ✅. Tap your reaction again
Type `/` at the start of a message to see the bot's commands:
- `/fast`: turns [Fast mode](/docs/agents#models-and-options) on or off, when the bot's agent offers it.
+- `/servers` (terminal UI): opens the bot's [dev servers](/docs/dev-servers), while it has some.
- `/` followed by a skill's ID: tells the bot to read that skill first and follow it for this message. The bot's skills are listed after the built-in commands.
-Any other `/command` goes to the agent unchanged, so the agent's own commands keep working. There's no command to start a new session: Codync starts one on its own when a conversation needs it. See [Bots](/docs/bots#sessions).
+Any other `/command` goes to the agent unchanged, so the agent's own commands keep working. In the terminal UI that includes `/servers` while the bot has no dev servers. There's no command to start a new session: Codync starts one on its own when a conversation needs it. See [Bots](/docs/bots#sessions).
## Fresh conversations
diff --git a/web/content/docs/dev-servers.mdx b/web/content/docs/dev-servers.mdx
new file mode 100644
index 00000000..f4883454
--- /dev/null
+++ b/web/content/docs/dev-servers.mdx
@@ -0,0 +1,60 @@
+A bot can leave a program running on your computer: a dev server for the site it's building, or a watch build. Codync runs these programs itself, so they keep running when the bot's agent stops or restarts, and you can see them and stop them from any of your devices.
+
+## Start one
+
+Ask the bot, in its chat:
+
+> Run this site so I can look at it.
+
+The bot starts it with Codync's built-in dev server tool. You get an approval card with the command and folder first, unless the bot's **Permissions** are set to **Approve automatically**. The bot's reply has the address.
+
+A dev server runs on your computer, as you, with your files and network. It isn't isolated from anything else on your computer.
+
+## See what's running
+
+A running server's port shows at the top of the bot's chat: `:5173`, or `:5173 +1` when there's another one. A program that doesn't listen on a port, like a watch build, shows its name instead. The same spot says when a server is starting, or when one failed to start.
+
+- **Desktop:** next to the bot's name.
+- **iPhone and Android:** under the bot's name, after the connection (`Connected · :5173`).
+- **Terminal UI:** on the right of the chat's header.
+
+For the list, open the bot's details:
+
+- **iPhone and Android:** tap the bot's name at the top of the chat. **Dev servers** is first on the page.
+- **Desktop:** click the bot's name at the top of the chat. **Dev servers** is first on the **Details** tab.
+- **Terminal UI:** click the port, or type `/servers`.
+
+## Open, stop and restart
+
+- **Desktop:** click a row to open that server in your browser. The **⋯** next to it has the rest: copy its address, read its logs, restart it, stop it. **⋯** shows when you hover over the row.
+- **iPhone and Android:** tap a row to open that server, when your phone can reach it. The **⋯** next to it has the rest.
+- **Terminal UI:** in the list, Enter opens the selected server, `c` copies its address, `l` shows its logs (`r` refreshes them there), `r` restarts it, `s` stops it and `x` removes it. The line at the bottom lists only the keys that apply to it.
+
+A row with no port to open, like a watch build or a server that failed, shows its logs instead. A failed server's logs also show its exit code.
+
+A stopped server stays in the list so you can start it again with the same command, until you remove it. Starting a server from the apps only ever re-runs what a bot started; only a bot can start a new one.
+
+A server's command and logs show in your apps, on all your devices. Keep secrets in your project's env files, not in the command.
+
+## Open one from your phone
+
+Most dev servers listen only on the computer they run on, so a phone can't reach them, and the menu says **Only reachable on the computer**. To open one from your phone, ask the bot to run it on all interfaces (for Vite, `npm run dev -- --host`). Your phone must be able to reach your computer directly, on the same Wi-Fi or over Tailscale.
+
+On all interfaces, anyone who can reach your computer on that network can open the server, and most dev servers have no sign-in. On shared Wi-Fi or a machine with a public address, that means strangers. Stay on Tailscale there, with a firewall that keeps the port closed elsewhere, or keep the default and open the server on the computer.
+
+## When they stop
+
+| What happens | The dev server |
+|---|---|
+| The bot's agent stops when idle, or restarts | Keeps running |
+| You start a new conversation, or a routine finishes | Keeps running |
+| You or the bot stops it | Stops, with everything it started |
+| Codync updates or restarts | Starts again by itself |
+| Your computer restarts | Stays stopped until you start it |
+| You delete the bot | Stops and is removed |
+
+There's no time limit, so a server you forget keeps running until you stop it. A bot can run at most 5 at once.
+
+## Servers a bot started by itself
+
+Sometimes a bot starts a server through its own shell instead. Codync shows it in the list too, but it stops when the bot's agent stops, and while it runs the agent stays running as well. If you want it to last, ask the bot to run it as a dev server.
diff --git a/web/content/docs/linux-servers.mdx b/web/content/docs/linux-servers.mdx
index 8bdd7219..8864ed39 100644
--- a/web/content/docs/linux-servers.mdx
+++ b/web/content/docs/linux-servers.mdx
@@ -89,6 +89,8 @@ The host listens on port 19222 on every interface. Its API (the one apps on the
Keep port 19222 closed in your cloud firewall anyway, unless you deliberately connect over a VPN or private network. Tailscale and the relay don't need it open.
+The firewall is also what protects a [dev server](/docs/dev-servers) a bot runs on all interfaces: on a server with a public address, the app shows that address, and anyone can open the port unless your firewall blocks it.
+
## Approve and manage devices without a desktop app
If the server is in your account, phones ask for access with a 6-digit code. Approve them on the server: