Skip to content

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

feat(apps): several networks, rules and per-bot switches on every client

leepokai88bc5c359777
diff --git a/apps/android/WhatsNew.md b/apps/android/WhatsNew.md
index ace1bdd2..f3515d3a 100644
--- a/apps/android/WhatsNew.md
+++ b/apps/android/WhatsNew.md
@@ -10,10 +10,12 @@ else a generic "Bug fixes and improvements" line. Delete old sections.
## 2.29.0
### zh-Hant
-- 設定裡每台電腦多了網路按鈕:看網路裡的電腦、是否在線、提供哪些 Bot,以及雲端助理是否開啟。
+- 設定裡每台電腦多了網路按鈕(Beta):一台電腦可加入多個網路,列出各網路的電腦、是否在線、提供的 Bot、誰能傳訊息給這裡的 Bot,以及雲端助理是否開啟。
+- Bot 設定多了「提供給網路」與「雲端助理可聯繫」開關。
### en-US
-- A network button on each computer in Settings shows your network's computers, whether each answers, its bots, and whether cloud assistants are on.
+- A network button (beta) on each computer in Settings: a computer can be in several networks; see each one's computers, whether each answers, its bots, who may message the bots here, and cloud assistants.
+- Bot settings have Offered to the network and Reachable by cloud assistants.
## 2.28.0
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/BotSettingsForm.kt b/apps/android/app/src/main/kotlin/com/codync/android/BotSettingsForm.kt
index 0f4467f1..b331efbf 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/BotSettingsForm.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/BotSettingsForm.kt
@@ -57,7 +57,9 @@ internal enum class FormPart { All, Often, Rarely }
fallbackBanner(state, store, bot); computerRow(state, online)
agentRows(state, store, draft, change, bot) { addingFallback = true }; placeRows(draft, change) { folders = true }
}
- CardSection("Activity") { notifyRow(draft, change); computerUseRow(state, draft, change); manageTeamRow(state, draft, change) }
+ CardSection("Activity") {
+ notifyRow(draft, change); computerUseRow(state, draft, change); manageTeamRow(state, draft, change); reachRows(state, draft, change)
+ }
Plugins(state, draft, change) { viewingSkill = it }
draft.id?.let { MemoryCard(it, store) }
state.error?.let { Text(it, style = Type.footnote, color = Palette.danger) }
@@ -77,7 +79,7 @@ internal enum class FormPart { All, Often, Rarely }
}
// The agent and its model are on the Details page; what's left is where it works.
CardSection("Workspace") { computerRow(state, online); placeRows(draft, change) { folders = true } }
- CardSection("Activity") { notifyRow(draft, change); manageTeamRow(state, draft, change) }
+ CardSection("Activity") { notifyRow(draft, change); manageTeamRow(state, draft, change); reachRows(state, draft, change) }
Plugins(state, draft, change) { viewingSkill = it }
}
}
@@ -205,6 +207,20 @@ private fun CardRows.manageTeamRow(state: AppState, draft: BotDraft, change: (Bo
}
}
+// Who else reaches this bot: shown only where it applies (in a network, cloud assistants on) and the host has the switch.
+private fun CardRows.reachRows(state: AppState, draft: BotDraft, change: (BotDraft) -> Unit) {
+ val network = state.network ?: return
+ draft.offeredToNetwork?.takeIf { network.joined }?.let { on ->
+ row { SwitchRow("Offered to the network", "Bots on your other computers can see and message this bot.", on, { change(draft.copy(offeredToNetwork = it)) }) }
+ }
+ draft.reachableByAssistants?.takeIf { network.assistants }?.let { on ->
+ row {
+ SwitchRow("Reachable by cloud assistants", "ChatGPT or Claude in your Codync account can see and message this bot.", on,
+ { change(draft.copy(reachableByAssistants = it)) })
+ }
+ }
+}
+
@Composable private fun Plugins(state: AppState, draft: BotDraft, change: (BotDraft) -> Unit, viewSkill: (SkillRef) -> Unit) {
val plugins = state.plugins
PluginToggles("Connectors", "No connectors yet. Add GitHub, Linear, Notion and more from Extensions.",
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/NetworkSheet.kt b/apps/android/app/src/main/kotlin/com/codync/android/NetworkSheet.kt
index 2660ec2f..6ad0a3c3 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/NetworkSheet.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/NetworkSheet.kt
@@ -19,13 +19,15 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.codync.android.core.NetworkComputer
+import com.codync.android.core.NetworkInfo
+import com.codync.android.core.NetworkRule
import com.codync.android.core.NetworkView
import com.codync.android.design.*
import com.kyant.shapes.Capsule
/**
- * The paired computer's network, read-only (iOS `NetworkSheet`): the computers in it with the bots each offers, and
- * whether cloud assistants may reach its bots. Who is in is changed on a computer.
+ * The paired computer's networks, read-only (iOS `NetworkSheet`): in each, the computers with the bots each offers
+ * and who may message the bots here; and whether cloud assistants may reach its bots. Changes are made on a computer.
*/
@Composable internal fun NetworkSheet(view: NetworkView, refresh: () -> Unit) {
AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Network))
@@ -42,8 +44,15 @@ import com.kyant.shapes.Capsule
modifier = Modifier.clip(Capsule()).background(Palette.bubbleAgent).padding(horizontal = 7.dp, vertical = 2.dp))
})
CardForm {
- if (view.joined) CardSection("Computers", "Changes are made on a computer: in Codync's settings there, or with codync-host network.") {
- for (computer in view.computers) row { NetworkComputerRow(computer) }
+ // One section per network; who may message the bots here only where it has rules.
+ view.networks.forEachIndexed { i, network ->
+ val last = i == view.networks.lastIndex
+ CardSection(network.name, if (last) "Changes are made on a computer: in Codync's settings there, or with codync-host network." else null) {
+ for (computer in network.computers) row { NetworkComputerRow(computer) }
+ }
+ if (network.rules.isNotEmpty()) CardSection("Who may message bots here", RULES_FOOTER) {
+ for (rule in network.rules) row { RuleRow(network, rule) }
+ }
}
if (view.assistantsAvailable) CardSection(footer = "ChatGPT or Claude in your Codync account can message this computer's bots when it's on. Codync's cloud can read these calls.") {
row { ValueRow("Cloud assistants", if (view.assistants) "On" else "Off") }
@@ -52,6 +61,15 @@ import com.kyant.shapes.Capsule
}
}
+private const val RULES_FOOTER = "The first rule that matches decides. Without rules, every computer in the network may message every bot here. Answers to this computer's own messages always get in."
+
+/** One rule, read-only: rules are changed on the computer. */
+@Composable private fun RuleRow(network: NetworkInfo, rule: NetworkRule) {
+ val language = LocalAppLanguage.current.resolved(LocalSystemTag.current)
+ val (chinese, phrases) = LocalSystemChinese.current to LocalPhrases.current
+ Text(network.describe(rule) { translate(it, language, chinese, phrases) }, style = Type.body, color = Palette.text)
+}
+
/** One computer: its name and role, whether it answers, and the bots it offers. */
@Composable private fun NetworkComputerRow(computer: NetworkComputer) {
val bots = computer.agents.joinToString(", ") { it.name }.ifEmpty { tr("No bots") }
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/BotDraft.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/BotDraft.kt
index a1421c4b..47b8b791 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/BotDraft.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/BotDraft.kt
@@ -33,6 +33,9 @@ data class BotDraft(
/** Null where the host has none (an older one), so it isn't sent. */
val fallbacks: List<Fallback>? = null,
val selfFallbacks: Boolean? = null,
+ /** Null where the host has none, or on a new bot, so it isn't sent. */
+ val offeredToNetwork: Boolean? = null,
+ val reachableByAssistants: Boolean? = null,
) {
/** A saved bot keeps a name; only a new one goes without (the host names it after its first conversations). */
val isValid: Boolean get() = name.isNotBlank()
@@ -47,7 +50,7 @@ data class BotDraft(
}
/** A template carries the bot's setup, not its fallbacks (they name this computer's agents): readable JSON, keys sorted as on iOS. */
fun template(): String = TemplateJson.encodeToString(JsonObject.serializer(),
- JsonObject(body().filterKeys { it !in setOf("id", "pinned", "hidden", "fallbacks", "selfFallbacks") }.toSortedMap()))
+ JsonObject(body().filterKeys { it !in TEMPLATE_SKIPS }.toSortedMap()))
/**
* This draft with each field it hasn't changed from [base] (the bot as the form loaded it) taken from [fresh] (the
@@ -62,12 +65,16 @@ data class BotDraft(
companion object {
/** A new bot starts with a random face, like iOS. */
val AVATAR_COLORS = listOf("black", "brown", "red", "orange", "yellow", "green", "cyan", "blue", "violet", "magenta", "gray")
- private val UNSET = setOf("fastMode", "notify", "fallbacks", "selfFallbacks")
+ private val UNSET = setOf("fastMode", "notify", "fallbacks", "selfFallbacks", "offeredToNetwork", "reachableByAssistants")
+ /** Who reaches a bot belongs to its computer, not its setup. */
+ private val TEMPLATE_SKIPS =
+ setOf("id", "pinned", "hidden", "fallbacks", "selfFallbacks", "offeredToNetwork", "reachableByAssistants")
private val TemplateJson = Json { prettyPrint = true; prettyPrintIndent = " " }
val AVATAR_SHAPES = listOf("blob", "pebble", "squircle", "tablet", "wedge", "hex", "cloud", "teardrop")
fun from(bot: Bot): BotDraft = BotDraft(bot.id, bot.name, bot.description, bot.avatarColor, bot.avatarShape,
bot.backend, bot.command, if (bot.managedWorkspace) "" else bot.cwd, bot.permission, bot.model,
- bot.modelOptions, bot.fastMode, bot.pinned, bot.hidden, bot.notify, bot.connectors, bot.skills, bot.computer, bot.manageTeam ?: false, bot.fallbacks, bot.selfFallbacks)
+ bot.modelOptions, bot.fastMode, bot.pinned, bot.hidden, bot.notify, bot.connectors, bot.skills, bot.computer, bot.manageTeam ?: false, bot.fallbacks, bot.selfFallbacks,
+ bot.offeredToNetwork, bot.reachableByAssistants)
}
}
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 535ee668..4512dcbf 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
@@ -35,6 +35,10 @@ data class Bot(
val computer: Boolean = false,
/** The bot can create bots (which can too) and change any bot's setup (the built-in `manage` tools); null from an older host. */
val manageTeam: Boolean? = null,
+ /** The user's other computers list this bot and may message it; null from an older host. */
+ val offeredToNetwork: Boolean? = null,
+ /** The user's cloud assistant lists this bot and may message it; null from an older host. */
+ val reachableByAssistants: Boolean? = null,
/** The bot that created this one; null when the user did. */
val createdBy: String? = null,
val autoName: Boolean = false,
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Network.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Network.kt
index 479fd9a3..b62f0105 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Network.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Network.kt
@@ -5,20 +5,19 @@ import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.decodeFromJsonElement
/**
- * The computer's network of the user's computers as phones see it (`networkView`, the `network` event): read-only,
+ * The computer's networks of the user's computers as phones see them (`networkView`, the `network` event): read-only,
* since who is in is decided at a computer (CodyncKit `NetworkView`).
*/
@Serializable
data class NetworkView(
val joined: Boolean = false,
- /** This computer's name in the network. */
- val computer: String? = null,
+ /** Every network the computer is in, the default first. */
+ val networks: List<NetworkInfo> = emptyList(),
val assistants: Boolean = false,
/** Cloud assistants can reach this computer at all: it's in a Codync account. */
val assistantsAvailable: Boolean = false,
- val computers: List<NetworkComputer> = emptyList(),
) {
- /** Something to show: the network, or cloud assistants that can reach this computer's bots. */
+ /** Something to show: a network, or cloud assistants that can reach this computer's bots. */
val shown: Boolean get() = joined || (assistantsAvailable && assistants)
companion object {
@@ -26,6 +25,47 @@ data class NetworkView(
}
}
+/** One network the computer is in. */
+@Serializable
+data class NetworkInfo(
+ val id: String,
+ /** What the user calls it (`home`). */
+ val name: String,
+ /** This computer's name in it. */
+ val computer: String? = null,
+ val role: String = "member",
+ val computers: List<NetworkComputer> = emptyList(),
+ /** Who on its other computers may message this computer's bots, the first match deciding. */
+ val rules: List<NetworkRule> = emptyList(),
+) {
+ /**
+ * How [rule] reads: "Allow: {from} → {to}", with the bots' names where this network knows them. [tr] translates
+ * each template before its names go in.
+ */
+ fun describe(rule: NetworkRule, tr: (String) -> String): String {
+ val from = when {
+ rule.fromComputer == ANY && rule.fromAgent == ANY -> tr("any bot on any computer")
+ // `lead@*` (only from the command line) reads "lead on any computer": never wider than it is.
+ rule.fromComputer == ANY -> tr("{bot} on any computer").replace("{bot}", rule.fromAgent)
+ rule.fromAgent == ANY -> tr("any bot on {computer}").replace("{computer}", rule.fromComputer)
+ else -> tr("{bot} on {computer}").replace("{bot}", agentName(rule.fromComputer, rule.fromAgent))
+ .replace("{computer}", rule.fromComputer)
+ }
+ val to = if (rule.toAgent == ANY) tr("any bot here") else computers.firstOrNull { it.me }?.let { me ->
+ me.agents.firstOrNull { it.id == rule.toAgent }?.name
+ } ?: rule.toAgent
+ val access = if (rule.access == "deny") "Deny: {from} → {to}" else "Allow: {from} → {to}"
+ return tr(access).replace("{from}", from).replace("{to}", to)
+ }
+
+ private fun agentName(computer: String, agent: String): String =
+ computers.firstOrNull { it.name.equals(computer, ignoreCase = true) }?.agents?.firstOrNull { it.id == agent }?.name ?: agent
+
+ private companion object {
+ const val ANY = "*"
+ }
+}
+
@Serializable
data class NetworkComputer(
val name: String,
@@ -43,3 +83,7 @@ data class NetworkComputer(
@Serializable
data class NetworkAgent(val id: String, val name: String = id)
+
+/** `{fromComputer, fromAgent, toAgent, access}`, `*` meaning any. */
+@Serializable
+data class NetworkRule(val fromComputer: String = "*", val fromAgent: String = "*", val toAgent: String = "*", val access: String = "allow")
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/NetworkTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/NetworkTest.kt
index 4d3d5265..e248e407 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/NetworkTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/NetworkTest.kt
@@ -6,21 +6,45 @@ import org.junit.Test
class NetworkTest {
private val view = WireJson.parseToJsonElement("""
- {"joined": true, "computer": "desk", "role": "owner", "connector": "public", "assistants": false, "assistantsAvailable": true,
- "computers": [
- {"name": "desk", "role": "owner", "me": true, "online": true,
- "agents": [{"id": "reviewer", "name": "Reviewer"}], "canRemove": false, "canPromote": false},
- {"name": "laptop", "role": "admin", "me": false, "online": false, "agents": [],
- "canRemove": true, "canPromote": false, "later": 1}]}
+ {"joined": true, "assistants": false, "assistantsAvailable": true, "networks": [
+ {"id": "network", "name": "home", "computer": "desk", "role": "owner", "canInvite": true, "canRecover": false,
+ "connector": "public",
+ "computers": [
+ {"name": "desk", "role": "owner", "me": true, "online": true,
+ "agents": [{"id": "reviewer", "name": "Reviewer"}], "canRemove": false, "canPromote": false},
+ {"name": "laptop", "role": "admin", "me": false, "online": false, "agents": [{"id": "lead", "name": "Lead"}],
+ "canRemove": true, "canPromote": false, "later": 1}],
+ "rules": [{"fromComputer": "laptop", "fromAgent": "lead", "toAgent": "reviewer", "access": "allow"},
+ {"fromComputer": "laptop", "fromAgent": "*", "toAgent": "*", "access": "deny"},
+ {"fromComputer": "*", "fromAgent": "*", "toAgent": "coder", "access": "deny"}]},
+ {"id": "network-1a2b", "name": "work", "computer": "desk", "role": "member", "computers": [], "rules": []}]}
""")
- @Test fun `a network view reads the computers, their roles and what they offer`() {
+ @Test fun `a network view reads every network, its computers, their roles and what they offer`() {
val read = NetworkView.decode(view)
assertTrue(read.joined && read.shown && !read.assistants)
- assertEquals(listOf("desk", "laptop"), read.computers.map { it.name })
- assertEquals(listOf("Owner", "Admin"), read.computers.map { it.roleTitle })
- assertEquals(listOf("This computer", "Away"), read.computers.map { it.presence })
- assertEquals(listOf(NetworkAgent("reviewer", "Reviewer")), read.computers[0].agents)
+ assertEquals(listOf("home", "work"), read.networks.map { it.name })
+ val home = read.networks[0]
+ assertEquals(listOf("desk", "laptop"), home.computers.map { it.name })
+ assertEquals(listOf("Owner", "Admin"), home.computers.map { it.roleTitle })
+ assertEquals(listOf("This computer", "Away"), home.computers.map { it.presence })
+ assertEquals(listOf(NetworkAgent("reviewer", "Reviewer")), home.computers[0].agents)
+ }
+
+ @Test fun `rules read with the bots' names where the network knows them`() {
+ val home = NetworkView.decode(view).networks[0]
+ val read = home.rules.map { home.describe(it) { template -> template } }
+ assertEquals(listOf(
+ "Allow: Lead on laptop → Reviewer",
+ "Deny: any bot on laptop → any bot here",
+ "Deny: any bot on any computer → coder",
+ ), read)
+ // Each template is translated before the names go in.
+ val phrases = mapOf("Deny: {from} → {to}" to "拒絕:{from} → {to}", "any bot on {computer}" to "{computer} 上的任何 Bot",
+ "any bot here" to "這裡的任何 Bot")
+ assertEquals("拒絕:laptop 上的任何 Bot → 這裡的任何 Bot", home.describe(home.rules[1]) { phrases[it] ?: it })
+ // A rule from the command line for one bot on any computer never reads wider than it is.
+ assertEquals("Deny: lead on any computer → any bot here", home.describe(NetworkRule("*", "lead", "*", "deny")) { it })
}
@Test fun `a computer in no network shows only when cloud assistants can reach it and are on`() {
@@ -35,15 +59,27 @@ class NetworkTest {
fun hello(network: JsonElement?) = MirrorEvent.decode(buildJsonObject {
put("type", "hello"); put("hostId", "h"); put("rev", 1); network?.let { put("network", it) }
}) as MirrorEvent.Hello
- assertEquals("desk", hello(view).network?.computer)
+ assertEquals("desk", hello(view).network?.networks?.first()?.computer)
assertNull(hello(null).network)
}
@Test fun `the network event is live state, and one this app can't read is passed over`() {
val event = MirrorEvent.decode(buildJsonObject { put("type", "network"); put("network", view) })
- assertEquals("laptop", (event as MirrorEvent.Network).view.computers[1].name)
- val broken = buildJsonObject { put("type", "network"); putJsonObject("network") { put("computers", "many") } }
+ assertEquals("laptop", (event as MirrorEvent.Network).view.networks[0].computers[1].name)
+ val broken = buildJsonObject { put("type", "network"); putJsonObject("network") { put("networks", "many") } }
assertEquals(MirrorEvent.Ignored, MirrorEvent.decode(broken))
assertEquals(MirrorEvent.Ignored, MirrorEvent.decode(buildJsonObject { put("type", "network") }))
}
+
+ @Test fun `the per-bot switches go out only when the host has them`() {
+ val old = WireJson.decodeFromJsonElement<Bot>(buildJsonObject { put("id", "a"); put("name", "Old") })
+ val new = WireJson.decodeFromJsonElement<Bot>(buildJsonObject {
+ put("id", "b"); put("name", "New"); put("offeredToNetwork", true); put("reachableByAssistants", false)
+ })
+ assertFalse("offeredToNetwork" in BotDraft.from(old).body())
+ val body = BotDraft.from(new).copy(offeredToNetwork = false).body()
+ assertEquals(JsonPrimitive(false), body["offeredToNetwork"])
+ assertEquals(JsonPrimitive(false), body["reachableByAssistants"])
+ assertFalse("not part of a template", "offeredToNetwork" in BotDraft.from(new).template())
+ }
}
diff --git a/apps/desktop/src/renderer/lib/network-copy.test.ts b/apps/desktop/src/renderer/lib/network-copy.test.ts
index 8c479fc1..1d1b8f75 100644
--- a/apps/desktop/src/renderer/lib/network-copy.test.ts
+++ b/apps/desktop/src/renderer/lib/network-copy.test.ts
@@ -1,12 +1,14 @@
import assert from 'node:assert/strict'
import test from 'node:test'
-import type { NetworkComputer } from '@shared/network'
-import { botsTemplate, connectorFor, presenceTitle } from './network-copy.ts'
+import type { Network, NetworkComputer, NetworkRule } from '@shared/network'
+import { botsTemplate, connectorFor, moved, presenceTitle, ruleLine } from './network-copy.ts'
const computer = (c: Partial<NetworkComputer>): NetworkComputer => ({
name: 'laptop', role: 'member', me: false, online: false, agents: [], canRemove: false, canPromote: false, ...c,
})
+const rule = (r: Partial<NetworkRule>): NetworkRule => ({ fromComputer: '*', fromAgent: '*', toAgent: '*', access: 'deny', ...r })
+
test('a relay connector needs an address; an empty one would quietly mean public', () => {
assert.deepEqual(connectorFor('public', 'ignored'), { connector: 'public' })
assert.deepEqual(connectorFor('private', ''), { connector: 'private' })
@@ -21,3 +23,21 @@ test('rows say where each computer is and how many bots it offers', () => {
assert.equal(botsTemplate(computer({ agents: [{ id: 'a', name: 'A' }] })), '1 bot')
assert.equal(botsTemplate(computer({})), '{count} bots')
})
+
+test('rules read with the bots by name, and move within the list', () => {
+ const net: Network = {
+ id: 'network', name: 'home', computer: 'desk', role: 'owner', canInvite: true, canRecover: false, connector: 'public', rules: [],
+ computers: [
+ computer({ name: 'desk', me: true, agents: [{ id: 'reviewer', name: 'Reviewer' }] }),
+ computer({ name: 'laptop', agents: [{ id: 'lead', name: 'Lead' }] }),
+ ],
+ }
+ const tr = (s: string) => s
+ assert.equal(ruleLine(rule({}), net, tr), 'Deny: any bot on any computer → any bot here')
+ assert.equal(ruleLine(rule({ fromComputer: 'Laptop', access: 'allow', toAgent: 'reviewer' }), net, tr), 'Allow: any bot on Laptop → Reviewer')
+ assert.equal(ruleLine(rule({ fromComputer: 'laptop', fromAgent: 'lead' }), net, tr), 'Deny: Lead on laptop → any bot here')
+ assert.equal(ruleLine(rule({ fromComputer: 'server', fromAgent: 'ci', toAgent: 'gone' }), net, tr), 'Deny: ci on server → gone')
+ const rules = [rule({ toAgent: 'a' }), rule({ toAgent: 'b' })]
+ assert.deepEqual(moved(rules, 1, -1).map((r) => r.toAgent), ['b', 'a'])
+ assert.equal(moved(rules, 0, -1), rules)
+})
diff --git a/apps/desktop/src/renderer/lib/network-copy.ts b/apps/desktop/src/renderer/lib/network-copy.ts
index cc3dbd9a..fccbbc5d 100644
--- a/apps/desktop/src/renderer/lib/network-copy.ts
+++ b/apps/desktop/src/renderer/lib/network-copy.ts
@@ -1,6 +1,6 @@
-/** What the Network section says about this computer's network (codync-network). */
+/** What the Network section says about this computer's networks (codync-network). */
-import type { NetworkComputer, NetworkRole } from '@shared/network'
+import type { Network, NetworkComputer, NetworkRole, NetworkRule } from '@shared/network'
/** How computers reach each other without a direct path. */
export type ConnectorChoice = 'public' | 'private' | 'relay'
@@ -27,3 +27,38 @@ export const botsTemplate = (c: NetworkComputer) => (c.agents.length === 1 ? '1
/** "3:27 PM" for an invite's expiry (Unix ms). */
export const expiryTime = (expiresAt: number) => new Date(expiresAt).toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' })
+
+export const ANY = '*'
+
+/** A computer of the network by name (names ignore case, like the host's). */
+const computerNamed = (net: Network, name: string) => net.computers.find((c) => c.name.toLowerCase() === name.toLowerCase())
+
+/** An agent's display name on a computer, else its address name. */
+const agentName = (computer: NetworkComputer | undefined, id: string) => computer?.agents.find((a) => a.id === id)?.name ?? id
+
+/** "Deny: any bot on laptop → Reviewer", through `tr` (templates translated before names go in). */
+export function ruleLine(rule: NetworkRule, net: Network, tr: (s: string) => string): string {
+ const computer = computerNamed(net, rule.fromComputer)
+ const bot = agentName(computer, rule.fromAgent)
+ const from =
+ rule.fromComputer === ANY
+ ? rule.fromAgent === ANY
+ ? tr('any bot on any computer')
+ : tr('{bot} on any computer').replaceAll('{bot}', bot)
+ : rule.fromAgent === ANY
+ ? tr('any bot on {computer}').replaceAll('{computer}', rule.fromComputer)
+ : tr('{bot} on {computer}').replaceAll('{bot}', bot).replaceAll('{computer}', rule.fromComputer)
+ const me = net.computers.find((c) => c.me)
+ const to = rule.toAgent === ANY ? tr('any bot here') : agentName(me, rule.toAgent)
+ const template = rule.access === 'allow' ? 'Allow: {from} → {to}' : 'Deny: {from} → {to}'
+ return tr(template).replaceAll('{from}', from).replaceAll('{to}', to)
+}
+
+/** The rules with `i` moved by `by` (−1 up, +1 down); unchanged at either end. */
+export function moved(rules: NetworkRule[], i: number, by: -1 | 1): NetworkRule[] {
+ const j = i + by
+ if (j < 0 || j >= rules.length) return rules
+ const out = [...rules]
+ ;[out[i], out[j]] = [out[j]!, out[i]!]
+ return out
+}
diff --git a/apps/desktop/src/renderer/store/bot-mirror.ts b/apps/desktop/src/renderer/store/bot-mirror.ts
index 8a79e509..6c417202 100644
--- a/apps/desktop/src/renderer/store/bot-mirror.ts
+++ b/apps/desktop/src/renderer/store/bot-mirror.ts
@@ -9,7 +9,7 @@ import {
type ScreenState,
type Usage,
} from '@shared/models'
-import type { NetworkView } from '@shared/network'
+import type { NetworkView, RecoveryCode } from '@shared/network'
import type { HostClient, HostRoute, HostTransport } from '../client/host-client'
import { rosterOrder } from '../lib/computer-roster'
import { offerHostUpdate, type HostUpdate, type HostUpdateOffer } from '../lib/host-update'
@@ -47,7 +47,7 @@ export class BotMirror extends Observable {
/** This computer's network; null until known, and on hosts without `networkView`. */
network: NetworkView | null = null
/** A new network's recovery code until the user says they saved it: the host keeps it nowhere. */
- recoveryCode: string | null = null
+ recoveryCode: RecoveryCode | null = null
historyComplete = new Set<string>()
routineDrafts = new Map<string, string>()
readonly composerDrafts: ComposerDrafts
@@ -210,7 +210,7 @@ export class BotMirror extends Observable {
this.changed()
}
- setRecoveryCode(code: string | null) {
+ setRecoveryCode(code: RecoveryCode | null) {
this.recoveryCode = code
this.changed()
}
diff --git a/apps/desktop/src/renderer/store/network.ts b/apps/desktop/src/renderer/store/network.ts
index 995416d6..9f79fa51 100644
--- a/apps/desktop/src/renderer/store/network.ts
+++ b/apps/desktop/src/renderer/store/network.ts
@@ -1,11 +1,11 @@
-import type { NetworkView } from '@shared/network'
+import type { NetworkRule, NetworkView } from '@shared/network'
import type { BotStore } from './bot-store'
/**
- * A managed computer's network (codync-network) through its host's loopback API: the calls
+ * A managed computer's networks (codync-network) through its host's loopback API: the calls
* behind the Network section. Membership is decided at a computer, so only loopback works; the
* `network` event keeps `store.network` current, and each change reads it again in case the
- * event is still on its way.
+ * event is still on its way. `network` is a network's id.
*/
/** Joining asks the inviting computer; asking every computer waits for the ones that are away. */
@@ -30,19 +30,29 @@ async function changing<T>(store: BotStore, work: () => Promise<T>): Promise<T>
return result
}
+/** An empty field is the host's default. */
+const orNull = (text: string) => text.trim() || null
+
export const network = {
- /** Asks every computer now. */
+ /** Asks every computer in every network now. */
peers: (store: BotStore) => changing(store, () => call(store, 'networkPeers', {}, SLOW)),
/** Keeps the recovery code on the store until the user says they saved it, wherever they went meanwhile. */
- create: (store: BotStore, name: string, connector: string) =>
- changing(store, async () => {
- const { recoveryCode } = await call<{ recoveryCode: string }>(store, 'networkCreate', { name: name.trim() || null, connector }, SLOW)
- store.setRecoveryCode(recoveryCode)
- }),
- join: (store: BotStore, invite: string, name: string, connector: string) =>
- changing(store, () => call(store, 'networkJoin', { invite: invite.trim(), name: name.trim() || null, connector }, SLOW)),
- invite: (store: BotStore) => call<{ invite: string; expiresAt: number }>(store, 'networkInvite'),
- promote: (store: BotStore, computer: string) => changing(store, () => call(store, 'networkPromote', { computer })),
- remove: (store: BotStore, computer: string, cascade: boolean) => changing(store, () => call(store, 'networkRemove', { computer, cascade })),
- recover: (store: BotStore, code: string) => changing(store, () => call(store, 'networkRecover', { code: code.trim() })),
+ create: async (store: BotStore, networkName: string, name: string, connector: string) => {
+ const made = await call<{ recoveryCode: string; computer: string; network: string }>(
+ store, 'networkCreate', { network: orNull(networkName), name: orNull(name), connector }, SLOW,
+ )
+ await refreshNetwork(store)
+ // The host may have numbered the name (`home-2`).
+ const named = store.network?.networks.find((n) => n.id === made.network)?.name ?? made.network
+ store.setRecoveryCode({ code: made.recoveryCode, network: named, computer: made.computer })
+ },
+ join: (store: BotStore, invite: string, networkName: string, name: string, connector: string) =>
+ changing(store, () => call(store, 'networkJoin', { invite: invite.trim(), network: orNull(networkName), name: orNull(name), connector }, SLOW)),
+ leave: (store: BotStore, network: string) => changing(store, () => call(store, 'networkLeave', { network })),
+ invite: (store: BotStore, network: string) => call<{ invite: string; expiresAt: number }>(store, 'networkInvite', { network }),
+ promote: (store: BotStore, network: string, computer: string) => changing(store, () => call(store, 'networkPromote', { network, computer })),
+ remove: (store: BotStore, network: string, computer: string, cascade: boolean) =>
+ changing(store, () => call(store, 'networkRemove', { network, computer, cascade })),
+ recover: (store: BotStore, network: string, code: string) => changing(store, () => call(store, 'networkRecover', { network, code: code.trim() })),
+ setRules: (store: BotStore, network: string, rules: NetworkRule[]) => changing(store, () => call(store, 'setNetworkRules', { network, rules })),
}
diff --git a/apps/desktop/src/renderer/views/bots/BotEditorView.tsx b/apps/desktop/src/renderer/views/bots/BotEditorView.tsx
index 7039153f..6d45cb7c 100644
--- a/apps/desktop/src/renderer/views/bots/BotEditorView.tsx
+++ b/apps/desktop/src/renderer/views/bots/BotEditorView.tsx
@@ -17,6 +17,7 @@ import { errorText, isValid, lastPathComponent, normalized, useFollowSaved, useP
import { FormSheet } from '../marketplace/pieces'
import { SkillSheet, type SkillRef } from '../marketplace/SkillSheet'
import { AnchoredPanel, AutoTextArea, AvatarPicker, Field, SwitchRow } from './parts'
+import { NetworkSwitches } from './NetworkSwitches'
import './bots.css'
import { useTr } from '../../lib/use-language'
@@ -303,6 +304,7 @@ function BotSettingsForm({ draft, onChange, error, plugins, part = 'all' }: {
onChange={(on) => set('manageTeam', on)}
/>
) : null}
+ <NetworkSwitches draft={draft} set={set} />
</CardSection>
<PluginToggles
diff --git a/apps/desktop/src/renderer/views/bots/NetworkSwitches.tsx b/apps/desktop/src/renderer/views/bots/NetworkSwitches.tsx
new file mode 100644
index 00000000..ae14987f
--- /dev/null
+++ b/apps/desktop/src/renderer/views/bots/NetworkSwitches.tsx
@@ -0,0 +1,31 @@
+import type { BotDraft } from '@shared/models'
+import { useStore } from '../../store/context'
+import { SwitchRow } from './parts'
+
+/**
+ * Who beyond this computer reaches the bot: the user's other computers (while this one is in a
+ * network) and the cloud assistant (while it's on). Each shows only from a host that has it.
+ */
+export function NetworkSwitches({ draft, set }: { draft: BotDraft; set: <K extends keyof BotDraft>(key: K, value: BotDraft[K]) => void }) {
+ const network = useStore().network
+ return (
+ <>
+ {draft.offeredToNetwork !== undefined && network?.joined ? (
+ <SwitchRow
+ title="Offered to the network"
+ detail="Bots on your other computers can see and message this bot."
+ on={draft.offeredToNetwork}
+ onChange={(on) => set('offeredToNetwork', on)}
+ />
+ ) : null}
+ {draft.reachableByAssistants !== undefined && network?.assistants ? (
+ <SwitchRow
+ title="Reachable by cloud assistants"
+ detail="ChatGPT or Claude in your Codync account can see and message this bot."
+ on={draft.reachableByAssistants}
+ onChange={(on) => set('reachableByAssistants', on)}
+ />
+ ) : null}
+ </>
+ )
+}
diff --git a/apps/desktop/src/renderer/views/settings/NetworkCard.tsx b/apps/desktop/src/renderer/views/settings/NetworkCard.tsx
new file mode 100644
index 00000000..9ef52977
--- /dev/null
+++ b/apps/desktop/src/renderer/views/settings/NetworkCard.tsx
@@ -0,0 +1,80 @@
+import type { Network, NetworkComputer, NetworkRule } from '@shared/network'
+import { Button, CardSection, IconButton } from '../../components/Controls'
+import { HStack, VStack } from '../../components/Stack'
+import { Text } from '../../components/Text'
+import { botsTemplate, moved, presenceTitle, roleTitle, ruleLine } from '../../lib/network-copy'
+import { useTr } from '../../lib/use-language'
+
+/** What a network card asks its section to do. */
+export interface NetworkActions {
+ invite: () => void
+ recover: () => void
+ refresh: () => void
+ leave: () => void
+ promote: (computer: NetworkComputer) => void
+ remove: (computer: NetworkComputer) => void
+ addRule: () => void
+ setRules: (rules: NetworkRule[]) => void
+}
+
+/** One of this computer's networks: who is in it, and who may message the bots here. */
+export function NetworkCard({ net, several, disabled, act }: { net: Network; several: boolean; disabled: boolean; act: NetworkActions }) {
+ const tr = useTr()
+ const title = (
+ <HStack as="span" gap={8}>
+ {net.name}
+ <Text as="span" size="caption" tone="secondary">{`${net.computer} · ${tr(roleTitle(net.role))}`}</Text>
+ </HStack>
+ )
+ const accessory = (
+ <HStack gap={2}>
+ {net.canInvite ? <IconButton title="Invite a computer" icon="person.crop.circle.badge.plus" disabled={disabled} onClick={act.invite} /> : null}
+ {net.canRecover ? <IconButton title="Recover ownership" icon="key" disabled={disabled} onClick={act.recover} /> : null}
+ <IconButton title="Refresh" icon="arrow.clockwise" disabled={disabled} onClick={act.refresh} />
+ <IconButton title="Leave network" icon="rectangle.portrait.and.arrow.right" disabled={disabled} onClick={act.leave} />
+ </HStack>
+ )
+ const footer = several
+ ? tr('Bots message the bots on these computers as bot@computer.{network}.').replaceAll('{network}', net.name)
+ : 'Bots message the bots on these computers as bot@computer.'
+ return (
+ <VStack gap={14}>
+ <CardSection title={title} accessory={accessory} footer={footer}>
+ {net.computers.map((c) => (
+ <ComputerRow key={c.name} computer={c} disabled={disabled} promote={() => act.promote(c)} remove={() => act.remove(c)} />
+ ))}
+ </CardSection>
+ <CardSection
+ title="Who may message bots here"
+ accessory={<IconButton title="Add rule" icon="plus" disabled={disabled} onClick={act.addRule} />}
+ footer="The first rule that matches decides. Without rules, every computer in the network may message every bot here. Answers to this computer's own messages always get in."
+ >
+ {net.rules.map((rule, i) => (
+ <HStack key={i} gap={4} className="settings-row settings-appear">
+ <Text grow>{ruleLine(rule, net, tr)}</Text>
+ <IconButton title="Move up" icon="chevron.up" disabled={disabled || i === 0} onClick={() => act.setRules(moved(net.rules, i, -1))} />
+ <IconButton title="Move down" icon="chevron.down" disabled={disabled || i === net.rules.length - 1} onClick={() => act.setRules(moved(net.rules, i, 1))} />
+ <IconButton title="Delete rule" icon="trash" disabled={disabled} onClick={() => act.setRules(net.rules.filter((_, j) => j !== i))} />
+ </HStack>
+ ))}
+ </CardSection>
+ </VStack>
+ )
+}
+
+function ComputerRow({ computer: c, disabled, promote, remove }: { computer: NetworkComputer; disabled: boolean; promote: () => void; remove: () => void }) {
+ const tr = useTr()
+ const bots = tr(botsTemplate(c)).replaceAll('{count}', String(c.agents.length))
+ const detail = [tr(roleTitle(c.role)), tr(presenceTitle(c)), bots].join(' · ')
+ return (
+ <HStack gap={8} className="settings-row settings-appear">
+ <span className={`network-dot${c.me || c.online ? ' online' : ''}`} aria-hidden />
+ <VStack grow className="settings-stack">
+ <Text>{c.name}</Text>
+ <Text size="caption" tone="secondary" truncate title={c.agents.map((a) => a.name).join(', ') || undefined}>{detail}</Text>
+ </VStack>
+ {c.canPromote ? <Button kind="secondary" disabled={disabled} onClick={promote}>Make admin</Button> : null}
+ {c.canRemove ? <IconButton title="Remove from the network" icon="trash" disabled={disabled} onClick={remove} /> : null}
+ </HStack>
+ )
+}
diff --git a/apps/desktop/src/renderer/views/settings/NetworkSection.tsx b/apps/desktop/src/renderer/views/settings/NetworkSection.tsx
index f171a2cb..b46d7fcc 100644
--- a/apps/desktop/src/renderer/views/settings/NetworkSection.tsx
+++ b/apps/desktop/src/renderer/views/settings/NetworkSection.tsx
@@ -1,30 +1,35 @@
import { useEffect, useState } from 'react'
-import type { NetworkComputer } from '@shared/network'
-import { Button, CardSection, IconButton } from '../../components/Controls'
+import type { Network, NetworkComputer } from '@shared/network'
+import { Button } from '../../components/Controls'
import { Dialog, Sheet } from '../../components/Overlay'
import { HStack, VStack } from '../../components/Stack'
import { Text } from '../../components/Text'
import { useModel } from '../../lib/observable'
-import { botsTemplate, presenceTitle, roleTitle } from '../../lib/network-copy'
import { useTr } from '../../lib/use-language'
import type { BotStore } from '../../store/bot-store'
import { network, refreshNetwork } from '../../store/network'
+import { NetworkCard } from './NetworkCard'
import { InviteSheet, NetworkSetupSheet, RecoverSheet, RecoveryCodeSheet } from './NetworkSheets'
import { errorText } from './parts'
+import { RuleSheet } from './RuleSheet'
import './network.css'
-type Open = 'create' | 'join' | 'invite' | 'recover'
+/** A sheet or dialog open for one network. */
+type Open =
+ | { kind: 'create' | 'join' }
+ | { kind: 'invite' | 'recover' | 'rule' | 'leave'; net: Network }
+ | { kind: 'remove'; net: Network; computer: NetworkComputer }
/**
- * A managed computer's network of the user's computers (codync-network): set it up, invite,
- * and who is in. Hidden on hosts without `networkView`. Membership is decided here, at the
- * computer; phones only see it.
+ * A managed computer's networks of the user's computers (codync-network): one card per
+ * network, with who is in it and who may message the bots here, and making or joining another.
+ * Hidden on hosts without `networkView`. Membership is decided here, at the computer; phones
+ * only see it.
*/
export function NetworkSection({ store }: { store: BotStore }) {
const tr = useTr()
useModel(store)
const [open, setOpen] = useState<Open | null>(null)
- const [removing, setRemoving] = useState<NetworkComputer | null>(null)
const [busy, setBusy] = useState(false)
const view = store.network
const manageable = store.connection.kind === 'online' && !store.mismatch
@@ -42,90 +47,85 @@ export function NetworkSection({ store }: { store: BotStore }) {
.catch((e: unknown) => store.setError(errorText(e)))
.finally(() => setBusy(false))
}
-
- const accessory = view.joined ? (
- <HStack gap={2}>
- {view.canInvite ? <IconButton title="Invite a computer" icon="person.crop.circle.badge.plus" disabled={!manageable} onClick={() => setOpen('invite')} /> : null}
- {view.canRecover ? <IconButton title="Recover ownership" icon="key" disabled={!manageable} onClick={() => setOpen('recover')} /> : null}
- <IconButton title="Refresh" icon="arrow.clockwise" disabled={busy || !manageable} onClick={() => run(() => network.peers(store))} />
- </HStack>
- ) : null
+ const close = () => setOpen(null)
+ const several = view.networks.length > 1
+ const sheetFor = (kind: 'invite' | 'recover' | 'rule') => (open && open.kind === kind ? open.net : null)
+ const invite = sheetFor('invite')
+ const recover = sheetFor('recover')
+ const rule = sheetFor('rule')
return (
- <>
- <CardSection
- title={
- <HStack as="span" gap={6}>
- {tr('Network')}
- <Text as="span" size="caption" weight="semibold" className="beta-tag">{tr('Beta')}</Text>
- </HStack>
- }
- accessory={accessory} footer={view.joined ? 'Bots message the bots on these computers as bot@computer.' : null}>
- {view.joined
- ? (view.computers ?? []).map((c) => (
- <ComputerRow
- key={c.name}
- computer={c}
- disabled={busy || !manageable}
- promote={() => run(() => network.promote(store, c.name))}
- remove={() => setRemoving(c)}
- />
- ))
- : [
- <VStack key="setup" gap={10} className="settings-appear">
- <Text size="callout" tone="secondary">{tr('Connect your computers so bots on one can message bots on another.')}</Text>
- <HStack gap={8}>
- <Button kind="secondary" disabled={!manageable} onClick={() => setOpen('create')}>Create network</Button>
- <Button kind="secondary" disabled={!manageable} onClick={() => setOpen('join')}>Join with invite</Button>
- </HStack>
- </VStack>,
- ]}
- </CardSection>
+ <VStack gap={14}>
+ <HStack gap={6} className="settings-section-header">
+ <Text as="h3" size="body" weight="semibold" tone="text">{tr('Network')}</Text>
+ <Text as="span" size="caption" weight="semibold" className="beta-tag">{tr('Beta')}</Text>
+ </HStack>
+ {view.networks.map((net) => (
+ <NetworkCard
+ key={net.id}
+ net={net}
+ several={several}
+ disabled={busy || !manageable}
+ act={{
+ invite: () => setOpen({ kind: 'invite', net }),
+ recover: () => setOpen({ kind: 'recover', net }),
+ refresh: () => run(() => network.peers(store)),
+ leave: () => setOpen({ kind: 'leave', net }),
+ promote: (c) => run(() => network.promote(store, net.id, c.name)),
+ remove: (computer) => setOpen({ kind: 'remove', net, computer }),
+ addRule: () => setOpen({ kind: 'rule', net }),
+ setRules: (rules) => run(() => network.setRules(store, net.id, rules)),
+ }}
+ />
+ ))}
+ <VStack gap={10} className="settings-appear">
+ {view.joined ? null : <Text size="callout" tone="secondary">{tr('Connect your computers so bots on one can message bots on another.')}</Text>}
+ <HStack gap={8}>
+ <Button kind="secondary" disabled={!manageable} onClick={() => setOpen({ kind: 'create' })}>Create network</Button>
+ <Button kind="secondary" disabled={!manageable} onClick={() => setOpen({ kind: 'join' })}>Join with invite</Button>
+ </HStack>
+ </VStack>
- <Sheet open={open === 'create' || open === 'join'} onClose={() => setOpen(null)}>
- <NetworkSetupSheet key={open} store={store} joining={open === 'join'} />
+ <Sheet open={open?.kind === 'create' || open?.kind === 'join'} onClose={close}>
+ <NetworkSetupSheet key={open?.kind} store={store} joining={open?.kind === 'join'} />
</Sheet>
- <Sheet open={open === 'invite'} onClose={() => setOpen(null)}>
- <InviteSheet store={store} />
+ <Sheet open={invite !== null} onClose={close}>
+ {invite ? <InviteSheet key={invite.id} store={store} net={invite} /> : null}
</Sheet>
- <Sheet open={open === 'recover'} onClose={() => setOpen(null)}>
- <RecoverSheet store={store} />
+ <Sheet open={recover !== null} onClose={close}>
+ {recover ? <RecoverSheet key={recover.id} store={store} net={recover} /> : null}
+ </Sheet>
+ <Sheet open={rule !== null} onClose={close}>
+ {rule ? <RuleSheet key={rule.id} store={store} net={rule} /> : null}
</Sheet>
{/* Escape and the dim don't close it: only "I saved it" does. */}
<Sheet open={store.recoveryCode !== null} onClose={() => {}}>
- {store.recoveryCode ? <RecoveryCodeSheet code={store.recoveryCode} name={store.network?.computer ?? store.hostName} done={() => store.setRecoveryCode(null)} /> : null}
+ {store.recoveryCode ? <RecoveryCodeSheet recovery={store.recoveryCode} done={() => store.setRecoveryCode(null)} /> : null}
</Sheet>
<Dialog
- open={removing !== null}
- title={tr('Remove {name} from the network?').replaceAll('{name}', removing?.name ?? '')}
+ open={open?.kind === 'remove'}
+ title={tr('Remove {name} from the network?').replaceAll('{name}', open?.kind === 'remove' ? open.computer.name : '')}
message={tr("It can't come back with its current key. For a stolen computer, also remove the computers it invited.")}
actions={
- removing
+ open?.kind === 'remove'
? [
- { title: 'Remove', destructive: true, action: () => run(() => network.remove(store, removing.name, false)) },
- { title: 'Remove with its invites', destructive: true, action: () => run(() => network.remove(store, removing.name, true)) },
+ { title: 'Remove', destructive: true, action: () => run(() => network.remove(store, open.net.id, open.computer.name, false)) },
+ { title: 'Remove with its invites', destructive: true, action: () => run(() => network.remove(store, open.net.id, open.computer.name, true)) },
]
: []
}
- onClose={() => setRemoving(null)}
+ onClose={close}
/>
- </>
- )
-}
-
-function ComputerRow({ computer: c, disabled, promote, remove }: { computer: NetworkComputer; disabled: boolean; promote: () => void; remove: () => void }) {
- const tr = useTr()
- const bots = tr(botsTemplate(c)).replaceAll('{count}', String(c.agents.length))
- const detail = [tr(roleTitle(c.role)), tr(presenceTitle(c)), bots].join(' · ')
- return (
- <HStack gap={8} className="settings-row settings-appear">
- <span className={`network-dot${c.me || c.online ? ' online' : ''}`} aria-hidden />
- <VStack grow className="settings-stack">
- <Text>{c.name}</Text>
- <Text size="caption" tone="secondary" truncate title={c.agents.map((a) => a.name).join(', ') || undefined}>{detail}</Text>
- </VStack>
- {c.canPromote ? <Button kind="secondary" disabled={disabled} onClick={promote}>Make admin</Button> : null}
- {c.canRemove ? <IconButton title="Remove from the network" icon="trash" disabled={disabled} onClick={remove} /> : null}
- </HStack>
+ <Dialog
+ open={open?.kind === 'leave'}
+ title={tr('Leave {network}?').replaceAll('{network}', open?.kind === 'leave' ? open.net.name : '')}
+ message={tr('This computer stops being in {network}. The others keep listing it until the owner or an admin removes it there; rejoining needs a new invite.').replaceAll(
+ '{network}',
+ open?.kind === 'leave' ? open.net.name : '',
+ )}
+ actions={open?.kind === 'leave' ? [{ title: 'Leave', destructive: true, action: () => run(() => network.leave(store, open.net.id)) }] : []}
+ onClose={close}
+ />
+ </VStack>
)
}
diff --git a/apps/desktop/src/renderer/views/settings/NetworkSheets.tsx b/apps/desktop/src/renderer/views/settings/NetworkSheets.tsx
index bc4f722d..28cdc631 100644
--- a/apps/desktop/src/renderer/views/settings/NetworkSheets.tsx
+++ b/apps/desktop/src/renderer/views/settings/NetworkSheets.tsx
@@ -5,13 +5,14 @@ import { HStack, VStack } from '../../components/Stack'
import { Text } from '../../components/Text'
import { connectorChoices, connectorFor, expiryTime, type ConnectorChoice } from '../../lib/network-copy'
import { useTr } from '../../lib/use-language'
+import type { Network, RecoveryCode } from '@shared/network'
import type { BotStore } from '../../store/bot-store'
import { network } from '../../store/network'
import { errorText } from './parts'
-const NETWORK_ICON = 'point.3.connected.trianglepath.dotted'
+export const NETWORK_ICON = 'point.3.connected.trianglepath.dotted'
-function Field({ label, value, set, placeholder, mono = false }: { label: string; value: string; set: (v: string) => void; placeholder: string; mono?: boolean }) {
+export function Field({ label, value, set, placeholder, mono = false }: { label: string; value: string; set: (v: string) => void; placeholder: string; mono?: boolean }) {
const tr = useTr()
return (
<HStack gap={12} className="settings-row">
@@ -28,11 +29,12 @@ function Field({ label, value, set, placeholder, mono = false }: { label: string
)
}
-/** Create a network (this computer its owner) or join one with an invite. */
+/** Create a network (this computer its owner) or join one with an invite: one more, a computer can be in several. */
export function NetworkSetupSheet({ store, joining }: { store: BotStore; joining: boolean }) {
const tr = useTr()
const dismiss = useDismiss()
const [invite, setInvite] = useState('')
+ const [networkName, setNetworkName] = useState('')
const [name, setName] = useState('')
const [choice, setChoice] = useState<ConnectorChoice>('public')
const [url, setUrl] = useState('')
@@ -47,8 +49,8 @@ export function NetworkSetupSheet({ store, joining }: { store: BotStore; joining
setBusy(true)
setProblem(null)
try {
- if (joining) await network.join(store, invite, name, connector.connector)
- else await network.create(store, name, connector.connector)
+ if (joining) await network.join(store, invite, networkName, name, connector.connector)
+ else await network.create(store, networkName, name, connector.connector)
dismiss()
} catch (e) {
setProblem(errorText(e))
@@ -68,6 +70,7 @@ export function NetworkSetupSheet({ store, joining }: { store: BotStore; joining
<CardSection footer={joining ? null : 'This computer becomes the owner: it invites the others.'}>
{[
...(joining ? [<Field key="invite" label="Invite" value={invite} set={setInvite} placeholder="codync-network:…" mono />] : []),
+ <Field key="network" label="Network name" value={networkName} set={setNetworkName} placeholder={joining ? 'From the invite' : 'home'} />,
<Field key="name" label="Computer name" value={name} set={setName} placeholder="Host name" />,
]}
</CardSection>
@@ -84,7 +87,7 @@ export function NetworkSetupSheet({ store, joining }: { store: BotStore; joining
}
/** The recovery code, once: closing it is confirming it was saved. The host keeps it nowhere. */
-export function RecoveryCodeSheet({ code, name, done }: { code: string; name: string; done: () => void }) {
+export function RecoveryCodeSheet({ recovery: { code, network: networkName, computer }, done }: { recovery: RecoveryCode; done: () => void }) {
const tr = useTr()
return (
<VStack className="network-sheet">
@@ -95,7 +98,9 @@ export function RecoveryCodeSheet({ code, name, done }: { code: string; name: st
<IconButton title="Copy recovery code" icon="doc.on.doc" onClick={() => window.codync.app.copy(code)} />
</HStack>
<Text size="callout" tone="secondary">
- {tr("It makes another computer the owner if {name} is lost. It's shown only once and kept on no computer.").replaceAll('{name}', name)}
+ {tr("It makes another computer the owner of {network} if {name} is lost. It's shown only once and kept on no computer.")
+ .replaceAll('{network}', networkName)
+ .replaceAll('{name}', computer)}
</Text>
<HStack justify="end">
<Button onClick={done}>I saved it</Button>
@@ -105,23 +110,23 @@ export function RecoveryCodeSheet({ code, name, done }: { code: string; name: st
)
}
-/** A one-time invite for another computer, good for an hour while this one stays on. */
-export function InviteSheet({ store }: { store: BotStore }) {
+/** A one-time invite to `net` for another computer, good for an hour while this one stays on. */
+export function InviteSheet({ store, net }: { store: BotStore; net: Network }) {
const tr = useTr()
const [invite, setInvite] = useState<{ invite: string; expiresAt: number } | { error: string } | null>(null)
const make = useCallback(async () => {
setInvite(null)
try {
- setInvite(await network.invite(store))
+ setInvite(await network.invite(store, net.id))
} catch (e) {
setInvite({ error: errorText(e) })
}
- }, [store])
+ }, [store, net.id])
useEffect(() => void make(), [make])
return (
<VStack className="network-sheet">
- <ModalHeader icon="person.crop.circle.badge.plus" title="Invite a computer" trailing={<IconButton title="New invite" icon="arrow.clockwise" onClick={() => void make()} />} />
+ <ModalHeader icon="person.crop.circle.badge.plus" title="Invite a computer" subtitle={net.name} trailing={<IconButton title="New invite" icon="arrow.clockwise" onClick={() => void make()} />} />
<VStack gap={14} className="network-sheet-body">
{invite === null ? (
<Spinner />
@@ -134,7 +139,7 @@ export function InviteSheet({ store }: { store: BotStore }) {
<IconButton title="Copy invite" icon="doc.on.doc" onClick={() => window.codync.app.copy(invite.invite)} />
</HStack>
<Text size="callout" tone="secondary">
- {tr('One use. Works until {time} while {name} stays on.').replaceAll('{time}', expiryTime(invite.expiresAt)).replaceAll('{name}', store.network?.computer ?? store.hostName)}
+ {tr('One use. Works until {time} while {name} stays on.').replaceAll('{time}', expiryTime(invite.expiresAt)).replaceAll('{name}', net.computer)}
</Text>
<Text size="callout" tone="secondary">{tr('On the other computer, choose Join with invite under Network.')}</Text>
</>
@@ -144,8 +149,8 @@ export function InviteSheet({ store }: { store: BotStore }) {
)
}
-/** Takes ownership with the recovery code, for when the owner was lost. */
-export function RecoverSheet({ store }: { store: BotStore }) {
+/** Takes ownership of `net` with its recovery code, for when the owner was lost. */
+export function RecoverSheet({ store, net }: { store: BotStore; net: Network }) {
const tr = useTr()
const [code, setCode] = useState('')
const [busy, setBusy] = useState(false)
@@ -154,8 +159,8 @@ export function RecoverSheet({ store }: { store: BotStore }) {
if (busy || !code.trim()) return
setBusy(true)
try {
- await network.recover(store, code)
- setResult({ ok: true, text: tr('{name} is the owner now. Remove the lost computer from the list.').replaceAll('{name}', store.network?.computer ?? store.hostName) })
+ await network.recover(store, net.id, code)
+ setResult({ ok: true, text: tr('{name} is the owner now. Remove the lost computer from the list.').replaceAll('{name}', net.computer) })
} catch (e) {
setResult({ ok: false, text: errorText(e) })
} finally {
@@ -168,6 +173,7 @@ export function RecoverSheet({ store }: { store: BotStore }) {
<ModalHeader
icon="key"
title="Recover ownership"
+ subtitle={net.name}
trailing={busy ? <Spinner /> : result?.ok ? null : <IconButton title="Recover" icon="checkmark" onClick={() => void recover()} />}
/>
<VStack gap={16} className="network-sheet-body">
diff --git a/apps/desktop/src/renderer/views/settings/RuleSheet.tsx b/apps/desktop/src/renderer/views/settings/RuleSheet.tsx
new file mode 100644
index 00000000..d6be13cb
--- /dev/null
+++ b/apps/desktop/src/renderer/views/settings/RuleSheet.tsx
@@ -0,0 +1,82 @@
+import { useState } from 'react'
+import type { Network, NetworkRule } from '@shared/network'
+import { CardSection, ChoiceList, ChoicePicker, IconButton, Reveal, Spinner, Switch, ValueRow } from '../../components/Controls'
+import { ModalHeader, useDismiss } from '../../components/Overlay'
+import { VStack } from '../../components/Stack'
+import { Text } from '../../components/Text'
+import { ANY } from '../../lib/network-copy'
+import type { BotStore } from '../../store/bot-store'
+import { network } from '../../store/network'
+import { errorText } from './parts'
+
+const ACCESS: { id: NetworkRule['access']; label: string }[] = [
+ { id: 'allow', label: 'Allow' },
+ { id: 'deny', label: 'Deny' },
+]
+
+/** A new rule for `net`: who on its other computers may message which bot here. Saves the whole list. */
+export function RuleSheet({ store, net }: { store: BotStore; net: Network }) {
+ const dismiss = useDismiss()
+ const [access, setAccess] = useState<NetworkRule['access']>('deny')
+ const [fromComputer, setFromComputer] = useState(ANY)
+ const [fromAgent, setFromAgent] = useState(ANY)
+ const [toAgent, setToAgent] = useState(ANY)
+ const [first, setFirst] = useState(false)
+ const [busy, setBusy] = useState(false)
+ const [problem, setProblem] = useState<string | null>(null)
+ const others = net.computers.filter((c) => !c.me)
+ const me = net.computers.find((c) => c.me)
+ const from = others.find((c) => c.name === fromComputer)
+
+ const pickComputer = (name: string) => {
+ setFromComputer(name)
+ // A bot belongs to its computer: another computer starts from any of its bots.
+ setFromAgent(ANY)
+ }
+
+ const save = async () => {
+ if (busy) return
+ setBusy(true)
+ setProblem(null)
+ const rule: NetworkRule = { fromComputer, fromAgent, toAgent, access }
+ try {
+ await network.setRules(store, net.id, first ? [rule, ...net.rules] : [...net.rules, rule])
+ dismiss()
+ } catch (e) {
+ setProblem(errorText(e))
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ return (
+ <VStack className="network-sheet">
+ <ModalHeader
+ icon="list.bullet"
+ title="Add rule"
+ subtitle={net.name}
+ trailing={busy ? <Spinner /> : <IconButton title="Add rule" icon="checkmark" onClick={() => void save()} />}
+ />
+ <VStack gap={16} className="network-sheet-body">
+ <CardSection>
+ <ChoiceList selection={access} options={ACCESS} onChange={setAccess} />
+ </CardSection>
+ <CardSection footer="The first rule that matches decides.">
+ <ValueRow label="From computer">
+ <ChoicePicker selection={fromComputer} options={[{ id: ANY, label: 'Any computer' }, ...others.map((c) => ({ id: c.name, label: c.name }))]} onChange={pickComputer} />
+ </ValueRow>
+ <ValueRow label="From bot">
+ <ChoicePicker selection={fromAgent} options={[{ id: ANY, label: 'Any bot' }, ...(from?.agents ?? []).map((a) => ({ id: a.id, label: a.name }))]} onChange={setFromAgent} />
+ </ValueRow>
+ <ValueRow label="To bot">
+ <ChoicePicker selection={toAgent} options={[{ id: ANY, label: 'Any bot here' }, ...(me?.agents ?? []).map((a) => ({ id: a.id, label: a.name }))]} onChange={setToAgent} />
+ </ValueRow>
+ <Switch on={first} onChange={setFirst}>Put it first</Switch>
+ </CardSection>
+ <Reveal show={problem !== null}>
+ <Text size="caption" tone="danger">{problem}</Text>
+ </Reveal>
+ </VStack>
+ </VStack>
+ )
+}
diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.ts
index d718ae62..95f45d27 100644
--- a/apps/desktop/src/shared/models.ts
+++ b/apps/desktop/src/shared/models.ts
@@ -52,6 +52,10 @@ export interface Bot {
computer: boolean
/** The bot can create bots (which can too) and change any bot's setup (the built-in `manage` tools); null from an older host. */
manageTeam: boolean | null
+ /** Other computers in the user's networks list this bot and may message it; null from an older host. */
+ offeredToNetwork: boolean | null
+ /** The user's cloud assistant lists this bot and may message it; null from an older host. */
+ reachableByAssistants: boolean | null
/** The bot that created this one; null when the user did. */
createdBy: string | null
/** Uses the memory all the user's bots share ("About you"). */
@@ -108,6 +112,8 @@ export function normalizeBot(raw: Partial<Bot> & { id: string }): Bot {
skills: raw.skills ?? [],
computer: raw.computer ?? false,
manageTeam: raw.manageTeam ?? null,
+ offeredToNetwork: raw.offeredToNetwork ?? null,
+ reachableByAssistants: raw.reachableByAssistants ?? null,
createdBy: raw.createdBy ?? null,
sharedMemory: raw.sharedMemory ?? raw.managedWorkspace ?? false,
harnessMemory: raw.harnessMemory ?? null,
@@ -590,6 +596,8 @@ export interface BotDraft {
skills?: string[]
computer?: boolean
manageTeam?: boolean
+ offeredToNetwork?: boolean
+ reachableByAssistants?: boolean
sharedMemory?: boolean
harnessMemory?: boolean
}
@@ -617,6 +625,8 @@ export function draftOf(bot: Bot): BotDraft {
skills: bot.skills,
computer: bot.computer,
manageTeam: bot.manageTeam ?? undefined,
+ offeredToNetwork: bot.offeredToNetwork ?? undefined,
+ reachableByAssistants: bot.reachableByAssistants ?? undefined,
}
}
diff --git a/apps/desktop/src/shared/network.ts b/apps/desktop/src/shared/network.ts
index 1ce43348..2dbdbb59 100644
--- a/apps/desktop/src/shared/network.ts
+++ b/apps/desktop/src/shared/network.ts
@@ -1,8 +1,8 @@
-/** This computer's network of the user's computers (codync-network), as the host describes it. */
+/** This computer's networks of the user's computers (codync-network), as the host describes them. */
export type NetworkRole = 'owner' | 'admin' | 'member'
-/** A computer in this computer's network, as last heard. */
+/** A computer in one of this computer's networks, as last heard. */
export interface NetworkComputer {
name: string
role: NetworkRole
@@ -16,18 +16,45 @@ export interface NetworkComputer {
canPromote: boolean
}
-/** `networkView`, the `network` event and the stream's hello: this computer's network, and cloud assistants. */
+/** Who on a network's other computers may message this computer's bots; `*` matches any. The first match decides. */
+export interface NetworkRule {
+ fromComputer: string
+ fromAgent: string
+ toAgent: string
+ access: 'allow' | 'deny'
+}
+
+/** One network this computer is in. */
+export interface Network {
+ /** What the host calls it in `network` arguments. */
+ id: string
+ /** What the user calls it (`home`). */
+ name: string
+ /** This computer's name and role there. */
+ computer: string
+ role: NetworkRole
+ /** What this computer may do there; the host decides. */
+ canInvite: boolean
+ canRecover: boolean
+ /** `public`, `private` or a relay URL. */
+ connector: string
+ computers: NetworkComputer[]
+ rules: NetworkRule[]
+}
+
+/** `networkView`, the `network` event and the stream's hello: this computer's networks, the default first, and cloud assistants. */
export interface NetworkView {
joined: boolean
- computer?: string | null
- role?: NetworkRole | null
- /** What this computer may do; the host decides. */
- canInvite?: boolean
- canRecover?: boolean
- /** `public`, `private` or a relay URL. */
- connector?: string | null
- computers?: NetworkComputer[]
+ networks: Network[]
assistants: boolean
/** Cloud assistants can reach this computer at all: it's in a Codync account. */
assistantsAvailable: boolean
}
+
+/** The recovery code of a network just made, kept until the user says they saved it. */
+export interface RecoveryCode {
+ code: string
+ /** The network's name, and this computer's name in it. */
+ network: string
+ computer: string
+}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Bot.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Bot.swift
index 761cd6ec..63dc7ba5 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/Bot.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Bot.swift
@@ -47,6 +47,10 @@ public struct Bot: Codable, Identifiable, Hashable, Sendable {
public var computer: Bool
/// The bot can create bots (which can too) and change any bot's setup (the built-in `manage` tools). Nil from an older host.
public var manageTeam: Bool?
+ /// Other computers in the user's networks list this bot and may message it. Nil from an older host.
+ public var offeredToNetwork: Bool?
+ /// The user's cloud assistant lists this bot and may message it. Nil from an older host.
+ public var reachableByAssistants: Bool?
/// The bot that created this one; nil when the user did.
public var createdBy: String?
/// Uses the memory all the user's bots share ("About you"). Nil from an older host.
@@ -123,6 +127,8 @@ extension Bot {
skills = try c.decodeIfPresent([String].self, forKey: .skills) ?? []
computer = try c.decodeIfPresent(Bool.self, forKey: .computer) ?? false
manageTeam = try c.decodeIfPresent(Bool.self, forKey: .manageTeam)
+ offeredToNetwork = try c.decodeIfPresent(Bool.self, forKey: .offeredToNetwork)
+ reachableByAssistants = try c.decodeIfPresent(Bool.self, forKey: .reachableByAssistants)
createdBy = try c.decodeIfPresent(String.self, forKey: .createdBy)
sharedMemory = try c.decodeIfPresent(Bool.self, forKey: .sharedMemory)
harnessMemory = try c.decodeIfPresent(Bool.self, forKey: .harnessMemory)
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift
index a6db2232..90b3f0f0 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift
@@ -304,6 +304,9 @@ public struct BotDraft: Codable, Hashable, Sendable {
public var skills: [String]?
public var computer: Bool?
public var manageTeam: Bool?
+ /// Nil from a host without the switch, so it isn't sent.
+ public var offeredToNetwork: Bool?
+ public var reachableByAssistants: Bool?
/// Only sent when the user changes it: unset, the host picks by the bot's folder.
public var sharedMemory: Bool?
/// Only sent when the user changes it.
@@ -343,6 +346,8 @@ public struct BotDraft: Codable, Hashable, Sendable {
skills = bot.skills
computer = bot.computer
manageTeam = bot.manageTeam
+ offeredToNetwork = bot.offeredToNetwork
+ reachableByAssistants = bot.reachableByAssistants
}
/// This draft with each field it hasn't changed from `base` (the bot as the form loaded it) taken from `fresh`
@@ -357,7 +362,7 @@ public struct BotDraft: Codable, Hashable, Sendable {
follow(\.command); follow(\.cwd); follow(\.permission); follow(\.model); follow(\.modelOptions)
follow(\.fastMode); follow(\.fallbacks); follow(\.selfFallbacks); follow(\.pinned); follow(\.hidden)
follow(\.notify); follow(\.connectors); follow(\.skills); follow(\.computer); follow(\.manageTeam)
- follow(\.sharedMemory); follow(\.harnessMemory)
+ follow(\.sharedMemory); follow(\.harnessMemory); follow(\.offeredToNetwork); follow(\.reachableByAssistants)
return draft
}
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Network.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Network.swift
index 03d160cd..52d00c5d 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/Network.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Network.swift
@@ -1,17 +1,64 @@
import Foundation
-/// The computer's network of the user's computers (`networkView`, and the `network` event): read-only
+/// The computer's networks of the user's computers (`networkView`, and the `network` event): read-only
/// on phones, since who is in is decided at a computer. Hosts before it answer "unknown method".
public struct NetworkView: Codable, Hashable, Sendable {
public var joined: Bool
- /// This computer's name in the network.
- public var computer: String?
- public var role: Role?
+ /// Every network the computer is in, the default first.
+ public var networks: [Network]?
/// The user's cloud assistant may message this computer's bots.
public var assistants: Bool?
/// Cloud assistants can reach this computer at all: it's in a Codync account.
public var assistantsAvailable: Bool?
- public var computers: [Computer]?
+
+ public struct Network: Codable, Hashable, Sendable, Identifiable {
+ public var id: String
+ /// What the user calls it (`home`).
+ public var name: String
+ /// This computer's name in it.
+ public var computer: String?
+ public var role: Role?
+ public var computers: [Computer]?
+ /// Who on its other computers may message this computer's bots, the first match deciding.
+ public var rules: [Rule]?
+
+ /// "Deny: any bot on laptop → Reviewer", names from what each computer offers.
+ public func text(of rule: Rule) -> String {
+ let agents = { (me: Bool, computer: String?) in
+ (computers ?? []).first { $0.me == me && (me || $0.name.caseInsensitiveCompare(computer ?? "") == .orderedSame) }?.agents ?? []
+ }
+ let named = { (id: String, among: [Agent]) in among.first { $0.id == id }?.name ?? id }
+ // `lead@*` (only from the command line) reads "lead on any computer": never wider than it is.
+ let from = rule.fromComputer == Rule.any && rule.fromAgent == Rule.any
+ ? L10n.tr("any bot on any computer")
+ : rule.fromComputer == Rule.any
+ ? L10n.tr("{bot} on any computer").replacingOccurrences(of: "{bot}", with: rule.fromAgent)
+ : rule.fromAgent == Rule.any
+ ? L10n.tr("any bot on {computer}").replacingOccurrences(of: "{computer}", with: rule.fromComputer)
+ : L10n.tr("{bot} on {computer}")
+ .replacingOccurrences(of: "{bot}", with: named(rule.fromAgent, agents(false, rule.fromComputer)))
+ .replacingOccurrences(of: "{computer}", with: rule.fromComputer)
+ let to = rule.toAgent == Rule.any ? L10n.tr("any bot here") : named(rule.toAgent, agents(true, nil))
+ let template = rule.access == .allow ? "Allow: {from} → {to}" : "Deny: {from} → {to}"
+ return L10n.tr(template).replacingOccurrences(of: "{from}", with: from).replacingOccurrences(of: "{to}", with: to)
+ }
+ }
+
+ public struct Rule: Codable, Hashable, Sendable {
+ public static let any = "*"
+ public var fromComputer: String
+ public var fromAgent: String
+ public var toAgent: String
+ public var access: Access
+
+ public enum Access: String, Codable, Hashable, Sendable {
+ case allow, deny
+ /// Anything a newer host adds reads as a refusal: showing more access than there is would mislead.
+ public init(from decoder: any Decoder) throws {
+ self = Access(rawValue: try decoder.singleValueContainer().decode(String.self)) ?? .deny
+ }
+ }
+ }
public enum Role: String, Codable, Hashable, Sendable {
case owner, admin, member
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
index fad31403..5032c19c 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
@@ -1315,5 +1315,52 @@
"Only the owner removes admins; admins remove members": "Nur der Eigentümer entfernt Admins; Admins entfernen Mitglieder",
"Network: your other computers…": "Netzwerk: deine anderen Computer…",
"a switches": "a umschalten",
- "Beta": "Beta"
+ "Beta": "Beta",
+ "Leave network": "Netzwerk verlassen",
+ "Leave {network}?": "{network} verlassen?",
+ "This computer stops being in {network}. The others keep listing it until the owner or an admin removes it there; rejoining needs a new invite.": "Dieser Computer ist dann nicht mehr in {network}. Die anderen führen ihn weiter, bis der Eigentümer oder ein Admin ihn dort entfernt; zum Wiederbeitreten braucht es eine neue Einladung.",
+ "Leave": "Verlassen",
+ "Network name": "Netzwerkname",
+ "From the invite": "Aus der Einladung",
+ "It makes another computer the owner of {network} if {name} is lost. It's shown only once and kept on no computer.": "Damit wird ein anderer Computer Eigentümer von {network}, falls {name} verloren geht. Er wird nur einmal angezeigt und auf keinem Computer gespeichert.",
+ "Bots message the bots on these computers as bot@computer.{network}.": "Bots schreiben den Bots auf diesen Computern als bot@computer.{network}.",
+ "Who may message bots here": "Wer den Bots hier schreiben darf",
+ "The first rule that matches decides. Without rules, every computer in the network may message every bot here. Answers to this computer's own messages always get in.": "Die erste passende Regel entscheidet. Ohne Regeln darf jeder Computer im Netzwerk jedem Bot hier schreiben. Antworten auf eigene Nachrichten dieses Computers kommen immer an.",
+ "Add rule": "Regel hinzufügen",
+ "Delete rule": "Regel löschen",
+ "Allow: {from} → {to}": "Erlauben: {from} → {to}",
+ "Deny: {from} → {to}": "Verbieten: {from} → {to}",
+ "any bot on any computer": "jeder Bot auf jedem Computer",
+ "any bot on {computer}": "jeder Bot auf {computer}",
+ "{bot} on {computer}": "{bot} auf {computer}",
+ "{bot} on any computer": "{bot} auf jedem Computer",
+ "any bot here": "jeder Bot hier",
+ "Deny": "Verbieten",
+ "From computer": "Von Computer",
+ "From bot": "Von Bot",
+ "To bot": "An Bot",
+ "Any computer": "Jeder Computer",
+ "Any bot": "Jeder Bot",
+ "Any bot here": "Jeder Bot hier",
+ "Put it first": "Ganz nach vorn",
+ "The first rule that matches decides.": "Die erste passende Regel entscheidet.",
+ "Offered to the network": "Im Netzwerk angeboten",
+ "Bots on your other computers can see and message this bot.": "Bots auf deinen anderen Computern sehen diesen Bot und können ihm schreiben.",
+ "Reachable by cloud assistants": "Für Cloud-Assistenten erreichbar",
+ "ChatGPT or Claude in your Codync account can see and message this bot.": "ChatGPT oder Claude in deinem Codync-Konto sehen diesen Bot und können ihm schreiben.",
+ "w shows them all": "w zeigt alle",
+ "←→ network": "←→ Netzwerk",
+ "↵ leave · esc cancel": "↵ verlassen · esc abbrechen",
+ "No rules: every computer in the network may message every bot here.": "Keine Regeln: Jeder Computer im Netzwerk darf jedem Bot hier schreiben.",
+ "n add rule · esc back": "n Regel hinzufügen · esc zurück",
+ "n add rule · x delete · K J move · esc back": "n Regel hinzufügen · x löschen · K J verschieben · esc zurück",
+ "↵ add · tab next field · ←→ change · esc back": "↵ hinzufügen · tab nächstes Feld · ←→ ändern · esc zurück",
+ "i invite · p make admin · x remove · w rules · c new · J join · L leave · esc": "i einladen · p zum Admin · x entfernen · w Regeln · c neu · J beitreten · L verlassen · esc",
+ "i invite · x remove · o recover · w rules · c new · J join · L leave · esc": "i einladen · x entfernen · o wiederherstellen · w Regeln · c neu · J beitreten · L verlassen · esc",
+ "o recover ownership · w rules · c new · J join · L leave · esc": "o Eigentum wiederherstellen · w Regeln · c neu · J beitreten · L verlassen · esc",
+ "Assistants": "Assistenten",
+ "this computer isn't in a network": "dieser Computer ist in keinem Netzwerk",
+ "cloud assistants are off here": "Cloud-Assistenten sind hier aus",
+ "Offered to the network: bots on your other computers can see and message this bot.": "Im Netzwerk angeboten: Bots auf deinen anderen Computern sehen diesen Bot und können ihm schreiben.",
+ "Reachable by cloud assistants: ChatGPT or Claude in your Codync account can see and message this bot.": "Für Cloud-Assistenten erreichbar: ChatGPT oder Claude in deinem Codync-Konto sehen diesen Bot und können ihm schreiben."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
index dfef534a..895b9829 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
@@ -1315,5 +1315,52 @@
"Only the owner removes admins; admins remove members": "Solo la propietaria quita administradores; los administradores quitan miembros",
"Network: your other computers…": "Red: tus otras computadoras…",
"a switches": "a cambiar",
- "Beta": "Beta"
+ "Beta": "Beta",
+ "Leave network": "Salir de la red",
+ "Leave {network}?": "¿Salir de {network}?",
+ "This computer stops being in {network}. The others keep listing it until the owner or an admin removes it there; rejoining needs a new invite.": "Esta computadora deja de estar en {network}. Las demás la siguen mostrando hasta que la propietaria o un administrador la quite; para volver hace falta una invitación nueva.",
+ "Leave": "Salir",
+ "Network name": "Nombre de la red",
+ "From the invite": "El de la invitación",
+ "It makes another computer the owner of {network} if {name} is lost. It's shown only once and kept on no computer.": "Hace propietaria de {network} a otra computadora si pierdes {name}. Solo se muestra una vez y no se guarda en ninguna computadora.",
+ "Bots message the bots on these computers as bot@computer.{network}.": "Los bots escriben a los bots de estas computadoras como bot@computadora.{network}.",
+ "Who may message bots here": "Quién puede escribir a los bots de aquí",
+ "The first rule that matches decides. Without rules, every computer in the network may message every bot here. Answers to this computer's own messages always get in.": "Decide la primera regla que coincida. Sin reglas, cada computadora de la red puede escribir a cada bot de aquí. Las respuestas a los mensajes de esta computadora siempre llegan.",
+ "Add rule": "Añadir regla",
+ "Delete rule": "Eliminar regla",
+ "Allow: {from} → {to}": "Permitir: {from} → {to}",
+ "Deny: {from} → {to}": "Denegar: {from} → {to}",
+ "any bot on any computer": "cualquier bot en cualquier computadora",
+ "any bot on {computer}": "cualquier bot en {computer}",
+ "{bot} on {computer}": "{bot} en {computer}",
+ "{bot} on any computer": "{bot} en cualquier computadora",
+ "any bot here": "cualquier bot de aquí",
+ "Deny": "Denegar",
+ "From computer": "Desde la computadora",
+ "From bot": "Desde el bot",
+ "To bot": "Al bot",
+ "Any computer": "Cualquier computadora",
+ "Any bot": "Cualquier bot",
+ "Any bot here": "Cualquier bot de aquí",
+ "Put it first": "Ponerla primero",
+ "The first rule that matches decides.": "Decide la primera regla que coincida.",
+ "Offered to the network": "Ofrecido a la red",
+ "Bots on your other computers can see and message this bot.": "Los bots de tus otras computadoras pueden ver este bot y escribirle.",
+ "Reachable by cloud assistants": "Accesible para asistentes en la nube",
+ "ChatGPT or Claude in your Codync account can see and message this bot.": "ChatGPT o Claude en tu cuenta de Codync pueden ver este bot y escribirle.",
+ "w shows them all": "w las muestra todas",
+ "←→ network": "←→ red",
+ "↵ leave · esc cancel": "↵ salir · esc cancelar",
+ "No rules: every computer in the network may message every bot here.": "Sin reglas: cada computadora de la red puede escribir a cada bot de aquí.",
+ "n add rule · esc back": "n añadir regla · esc volver",
+ "n add rule · x delete · K J move · esc back": "n añadir regla · x eliminar · K J mover · esc volver",
+ "↵ add · tab next field · ←→ change · esc back": "↵ añadir · tab siguiente campo · ←→ cambiar · esc volver",
+ "i invite · p make admin · x remove · w rules · c new · J join · L leave · esc": "i invitar · p hacer admin · x quitar · w reglas · c nueva · J unirse · L salir · esc",
+ "i invite · x remove · o recover · w rules · c new · J join · L leave · esc": "i invitar · x quitar · o recuperar · w reglas · c nueva · J unirse · L salir · esc",
+ "o recover ownership · w rules · c new · J join · L leave · esc": "o recuperar la propiedad · w reglas · c nueva · J unirse · L salir · esc",
+ "Assistants": "Asistentes",
+ "this computer isn't in a network": "esta computadora no está en ninguna red",
+ "cloud assistants are off here": "los asistentes en la nube están desactivados aquí",
+ "Offered to the network: bots on your other computers can see and message this bot.": "Ofrecido a la red: los bots de tus otras computadoras pueden ver este bot y escribirle.",
+ "Reachable by cloud assistants: ChatGPT or Claude in your Codync account can see and message this bot.": "Accesible para asistentes en la nube: ChatGPT o Claude en tu cuenta de Codync pueden ver este bot y escribirle."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
index 6100f3cb..e9eff243 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
@@ -1315,5 +1315,52 @@
"Only the owner removes admins; admins remove members": "Seul le propriétaire retire des admins ; les admins retirent des membres",
"Network: your other computers…": "Réseau : vos autres ordinateurs…",
"a switches": "a basculer",
- "Beta": "Bêta"
+ "Beta": "Bêta",
+ "Leave network": "Quitter le réseau",
+ "Leave {network}?": "Quitter {network} ?",
+ "This computer stops being in {network}. The others keep listing it until the owner or an admin removes it there; rejoining needs a new invite.": "Cet ordinateur ne fera plus partie de {network}. Les autres continuent de l'afficher jusqu'à ce que le propriétaire ou un admin le retire ; pour revenir, il faut une nouvelle invitation.",
+ "Leave": "Quitter",
+ "Network name": "Nom du réseau",
+ "From the invite": "Celui de l'invitation",
+ "It makes another computer the owner of {network} if {name} is lost. It's shown only once and kept on no computer.": "Il fait d'un autre ordinateur le propriétaire de {network} si {name} est perdu. Il n'est affiché qu'une fois et n'est gardé sur aucun ordinateur.",
+ "Bots message the bots on these computers as bot@computer.{network}.": "Les bots écrivent aux bots de ces ordinateurs avec bot@ordinateur.{network}.",
+ "Who may message bots here": "Qui peut écrire aux bots d'ici",
+ "The first rule that matches decides. Without rules, every computer in the network may message every bot here. Answers to this computer's own messages always get in.": "La première règle qui correspond décide. Sans règles, chaque ordinateur du réseau peut écrire à chaque bot d'ici. Les réponses aux messages de cet ordinateur arrivent toujours.",
+ "Add rule": "Ajouter une règle",
+ "Delete rule": "Supprimer la règle",
+ "Allow: {from} → {to}": "Autoriser : {from} → {to}",
+ "Deny: {from} → {to}": "Refuser : {from} → {to}",
+ "any bot on any computer": "tout bot sur tout ordinateur",
+ "any bot on {computer}": "tout bot sur {computer}",
+ "{bot} on {computer}": "{bot} sur {computer}",
+ "{bot} on any computer": "{bot} sur tout ordinateur",
+ "any bot here": "tout bot d'ici",
+ "Deny": "Refuser",
+ "From computer": "Depuis l'ordinateur",
+ "From bot": "Depuis le bot",
+ "To bot": "Vers le bot",
+ "Any computer": "Tout ordinateur",
+ "Any bot": "Tout bot",
+ "Any bot here": "Tout bot d'ici",
+ "Put it first": "La mettre en premier",
+ "The first rule that matches decides.": "La première règle qui correspond décide.",
+ "Offered to the network": "Proposé au réseau",
+ "Bots on your other computers can see and message this bot.": "Les bots de vos autres ordinateurs voient ce bot et peuvent lui écrire.",
+ "Reachable by cloud assistants": "Joignable par les assistants cloud",
+ "ChatGPT or Claude in your Codync account can see and message this bot.": "ChatGPT ou Claude dans votre compte Codync voit ce bot et peut lui écrire.",
+ "w shows them all": "w les affiche toutes",
+ "←→ network": "←→ réseau",
+ "↵ leave · esc cancel": "↵ quitter · esc annuler",
+ "No rules: every computer in the network may message every bot here.": "Aucune règle : chaque ordinateur du réseau peut écrire à chaque bot d'ici.",
+ "n add rule · esc back": "n ajouter une règle · esc retour",
+ "n add rule · x delete · K J move · esc back": "n ajouter une règle · x supprimer · K J déplacer · esc retour",
+ "↵ add · tab next field · ←→ change · esc back": "↵ ajouter · tab champ suivant · ←→ changer · esc retour",
+ "i invite · p make admin · x remove · w rules · c new · J join · L leave · esc": "i inviter · p nommer admin · x retirer · w règles · c nouveau · J rejoindre · L quitter · esc",
+ "i invite · x remove · o recover · w rules · c new · J join · L leave · esc": "i inviter · x retirer · o récupérer · w règles · c nouveau · J rejoindre · L quitter · esc",
+ "o recover ownership · w rules · c new · J join · L leave · esc": "o récupérer la propriété · w règles · c nouveau · J rejoindre · L quitter · esc",
+ "Assistants": "Assistants",
+ "this computer isn't in a network": "cet ordinateur n'est dans aucun réseau",
+ "cloud assistants are off here": "les assistants cloud sont désactivés ici",
+ "Offered to the network: bots on your other computers can see and message this bot.": "Proposé au réseau : les bots de vos autres ordinateurs voient ce bot et peuvent lui écrire.",
+ "Reachable by cloud assistants: ChatGPT or Claude in your Codync account can see and message this bot.": "Joignable par les assistants cloud : ChatGPT ou Claude dans votre compte Codync voit ce bot et peut lui écrire."
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
index e35d3424..a093e422 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
@@ -1315,5 +1315,52 @@
"Only the owner removes admins; admins remove members": "管理者を削除できるのはオーナーだけで、管理者はメンバーを削除できます",
"Network: your other computers…": "ネットワーク:ほかのコンピューター…",
"a switches": "a 切り替え",
- "Beta": "ベータ"
+ "Beta": "ベータ",
+ "Leave network": "ネットワークから抜ける",
+ "Leave {network}?": "{network} から抜けますか?",
+ "This computer stops being in {network}. The others keep listing it until the owner or an admin removes it there; rejoining needs a new invite.": "このコンピューターは {network} から抜けます。オーナーか管理者が削除するまで、ほかのコンピューターには表示され続けます。戻るには新しい招待が必要です。",
+ "Leave": "抜ける",
+ "Network name": "ネットワーク名",
+ "From the invite": "招待のとおり",
+ "It makes another computer the owner of {network} if {name} is lost. It's shown only once and kept on no computer.": "{name} をなくしたとき、ほかのコンピューターを {network} のオーナーにできます。表示されるのは今回だけで、どのコンピューターにも保存されません。",
+ "Bots message the bots on these computers as bot@computer.{network}.": "ボットは bot@コンピューター.{network} でこれらのコンピューターのボットにメッセージを送ります。",
+ "Who may message bots here": "ここのボットにメッセージを送れる相手",
+ "The first rule that matches decides. Without rules, every computer in the network may message every bot here. Answers to this computer's own messages always get in.": "最初に一致したルールで決まります。ルールがなければ、ネットワーク内のすべてのコンピューターがここのすべてのボットにメッセージを送れます。このコンピューターが送ったメッセージへの返信は常に届きます。",
+ "Add rule": "ルールを追加",
+ "Delete rule": "ルールを削除",
+ "Allow: {from} → {to}": "許可:{from} → {to}",
+ "Deny: {from} → {to}": "拒否:{from} → {to}",
+ "any bot on any computer": "どのコンピューターのどのボットも",
+ "any bot on {computer}": "{computer} のどのボットも",
+ "{bot} on {computer}": "{computer} の {bot}",
+ "{bot} on any computer": "どのコンピューターの {bot} も",
+ "any bot here": "ここのどのボットも",
+ "Deny": "拒否",
+ "From computer": "送信元のコンピューター",
+ "From bot": "送信元のボット",
+ "To bot": "宛先のボット",
+ "Any computer": "すべてのコンピューター",
+ "Any bot": "すべてのボット",
+ "Any bot here": "ここのすべてのボット",
+ "Put it first": "先頭に置く",
+ "The first rule that matches decides.": "最初に一致したルールで決まります。",
+ "Offered to the network": "ネットワークに公開",
+ "Bots on your other computers can see and message this bot.": "ほかのコンピューターのボットがこのボットを見つけてメッセージを送れます。",
+ "Reachable by cloud assistants": "クラウドアシスタントから利用可能",
+ "ChatGPT or Claude in your Codync account can see and message this bot.": "Codync アカウントの ChatGPT や Claude がこのボットを見つけてメッセージを送れます。",
+ "w shows them all": "w ですべて表示",
+ "←→ network": "←→ ネットワーク",
+ "↵ leave · esc cancel": "↵ 抜ける · esc キャンセル",
+ "No rules: every computer in the network may message every bot here.": "ルールなし:ネットワーク内のすべてのコンピューターがここのすべてのボットにメッセージを送れます。",
+ "n add rule · esc back": "n ルールを追加 · esc 戻る",
+ "n add rule · x delete · K J move · esc back": "n ルールを追加 · x 削除 · K J 移動 · esc 戻る",
+ "↵ add · tab next field · ←→ change · esc back": "↵ 追加 · tab 次の項目 · ←→ 変更 · esc 戻る",
+ "i invite · p make admin · x remove · w rules · c new · J join · L leave · esc": "i 招待 · p 管理者にする · x 削除 · w ルール · c 新規 · J 参加 · L 抜ける · esc",
+ "i invite · x remove · o recover · w rules · c new · J join · L leave · esc": "i 招待 · x 削除 · o 取り戻す · w ルール · c 新規 · J 参加 · L 抜ける · esc",
+ "o recover ownership · w rules · c new · J join · L leave · esc": "o オーナー権を取り戻す · w ルール · c 新規 · J 参加 · L 抜ける · esc",
+ "Assistants": "アシスタント",
+ "this computer isn't in a network": "このコンピューターはネットワークに入っていません",
+ "cloud assistants are off here": "ここではクラウドアシスタントがオフです",
+ "Offered to the network: bots on your other computers can see and message this bot.": "ネットワークに公開:ほかのコンピューターのボットがこのボットを見つけてメッセージを送れます。",
+ "Reachable by cloud assistants: ChatGPT or Claude in your Codync account can see and message this bot.": "クラウドアシスタントから利用可能:Codync アカウントの ChatGPT や Claude がこのボットを見つけてメッセージを送れます。"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
index 1ff91ecf..109ac784 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
@@ -1315,5 +1315,52 @@
"Only the owner removes admins; admins remove members": "관리자는 소유자만 제거할 수 있고, 관리자는 멤버를 제거할 수 있습니다",
"Network: your other computers…": "네트워크: 내 다른 컴퓨터…",
"a switches": "a 전환",
- "Beta": "베타"
+ "Beta": "베타",
+ "Leave network": "네트워크 나가기",
+ "Leave {network}?": "{network}에서 나갈까요?",
+ "This computer stops being in {network}. The others keep listing it until the owner or an admin removes it there; rejoining needs a new invite.": "이 컴퓨터는 {network}에서 빠집니다. 소유자나 관리자가 제거할 때까지 다른 컴퓨터에는 계속 표시되며, 다시 참여하려면 새 초대가 필요합니다.",
+ "Leave": "나가기",
+ "Network name": "네트워크 이름",
+ "From the invite": "초대에 있는 이름",
+ "It makes another computer the owner of {network} if {name} is lost. It's shown only once and kept on no computer.": "{name}을(를) 잃어버리면 다른 컴퓨터를 {network}의 소유자로 만들 수 있습니다. 이번 한 번만 표시되며 어떤 컴퓨터에도 저장되지 않습니다.",
+ "Bots message the bots on these computers as bot@computer.{network}.": "봇은 bot@컴퓨터.{network} 형식으로 이 컴퓨터들의 봇에게 메시지를 보냅니다.",
+ "Who may message bots here": "여기 봇에게 메시지를 보낼 수 있는 대상",
+ "The first rule that matches decides. Without rules, every computer in the network may message every bot here. Answers to this computer's own messages always get in.": "처음 일치하는 규칙이 결정합니다. 규칙이 없으면 네트워크의 모든 컴퓨터가 여기 모든 봇에게 메시지를 보낼 수 있습니다. 이 컴퓨터가 보낸 메시지에 대한 답장은 항상 들어옵니다.",
+ "Add rule": "규칙 추가",
+ "Delete rule": "규칙 삭제",
+ "Allow: {from} → {to}": "허용: {from} → {to}",
+ "Deny: {from} → {to}": "거부: {from} → {to}",
+ "any bot on any computer": "모든 컴퓨터의 모든 봇",
+ "any bot on {computer}": "{computer}의 모든 봇",
+ "{bot} on {computer}": "{computer}의 {bot}",
+ "{bot} on any computer": "모든 컴퓨터의 {bot}",
+ "any bot here": "여기 모든 봇",
+ "Deny": "거부",
+ "From computer": "보내는 컴퓨터",
+ "From bot": "보내는 봇",
+ "To bot": "받는 봇",
+ "Any computer": "모든 컴퓨터",
+ "Any bot": "모든 봇",
+ "Any bot here": "여기 모든 봇",
+ "Put it first": "맨 앞에 두기",
+ "The first rule that matches decides.": "처음 일치하는 규칙이 결정합니다.",
+ "Offered to the network": "네트워크에 공개",
+ "Bots on your other computers can see and message this bot.": "다른 컴퓨터의 봇이 이 봇을 보고 메시지를 보낼 수 있습니다.",
+ "Reachable by cloud assistants": "클라우드 어시스턴트가 연락 가능",
+ "ChatGPT or Claude in your Codync account can see and message this bot.": "Codync 계정의 ChatGPT나 Claude가 이 봇을 보고 메시지를 보낼 수 있습니다.",
+ "w shows them all": "w 전체 보기",
+ "←→ network": "←→ 네트워크",
+ "↵ leave · esc cancel": "↵ 나가기 · esc 취소",
+ "No rules: every computer in the network may message every bot here.": "규칙 없음: 네트워크의 모든 컴퓨터가 여기 모든 봇에게 메시지를 보낼 수 있습니다.",
+ "n add rule · esc back": "n 규칙 추가 · esc 뒤로",
+ "n add rule · x delete · K J move · esc back": "n 규칙 추가 · x 삭제 · K J 이동 · esc 뒤로",
+ "↵ add · tab next field · ←→ change · esc back": "↵ 추가 · tab 다음 항목 · ←→ 변경 · esc 뒤로",
+ "i invite · p make admin · x remove · w rules · c new · J join · L leave · esc": "i 초대 · p 관리자로 지정 · x 제거 · w 규칙 · c 새로 · J 참여 · L 나가기 · esc",
+ "i invite · x remove · o recover · w rules · c new · J join · L leave · esc": "i 초대 · x 제거 · o 복구 · w 규칙 · c 새로 · J 참여 · L 나가기 · esc",
+ "o recover ownership · w rules · c new · J join · L leave · esc": "o 소유권 복구 · w 규칙 · c 새로 · J 참여 · L 나가기 · esc",
+ "Assistants": "어시스턴트",
+ "this computer isn't in a network": "이 컴퓨터는 네트워크에 속해 있지 않습니다",
+ "cloud assistants are off here": "여기서는 클라우드 어시스턴트가 꺼져 있습니다",
+ "Offered to the network: bots on your other computers can see and message this bot.": "네트워크에 공개: 다른 컴퓨터의 봇이 이 봇을 보고 메시지를 보낼 수 있습니다.",
+ "Reachable by cloud assistants: ChatGPT or Claude in your Codync account can see and message this bot.": "클라우드 어시스턴트가 연락 가능: Codync 계정의 ChatGPT나 Claude가 이 봇을 보고 메시지를 보낼 수 있습니다."
}
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 1455f452..8a1e178d 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
@@ -1315,5 +1315,52 @@
"Only the owner removes admins; admins remove members": "只有所有者能移除管理员;管理员能移除成员",
"Network: your other computers…": "网络:你的其他电脑…",
"a switches": "a 切换",
- "Beta": "测试版"
+ "Beta": "测试版",
+ "Leave network": "离开网络",
+ "Leave {network}?": "要离开 {network} 吗?",
+ "This computer stops being in {network}. The others keep listing it until the owner or an admin removes it there; rejoining needs a new invite.": "这台电脑将不再属于 {network}。在所有者或管理员把它移除之前,其他电脑仍会列出它;要再加入需要新的邀请。",
+ "Leave": "离开",
+ "Network name": "网络名称",
+ "From the invite": "使用邀请里的名称",
+ "It makes another computer the owner of {network} if {name} is lost. It's shown only once and kept on no computer.": "{name} 丢失时,它能让另一台电脑成为 {network} 的所有者。只会显示这一次,也不会存在任何电脑上。",
+ "Bots message the bots on these computers as bot@computer.{network}.": "Bot 用 bot@电脑.{network} 给这些电脑上的 Bot 发消息。",
+ "Who may message bots here": "谁可以给这里的 Bot 发消息",
+ "The first rule that matches decides. Without rules, every computer in the network may message every bot here. Answers to this computer's own messages always get in.": "由第一条匹配的规则决定。没有规则时,网络里的每台电脑都能给这里的每个 Bot 发消息。回复这台电脑自己发出的消息一律可以进来。",
+ "Add rule": "添加规则",
+ "Delete rule": "删除规则",
+ "Allow: {from} → {to}": "允许:{from} → {to}",
+ "Deny: {from} → {to}": "拒绝:{from} → {to}",
+ "any bot on any computer": "任何电脑上的任何 Bot",
+ "any bot on {computer}": "{computer} 上的任何 Bot",
+ "{bot} on {computer}": "{computer} 上的 {bot}",
+ "{bot} on any computer": "任何电脑上的 {bot}",
+ "any bot here": "这里的任何 Bot",
+ "Deny": "拒绝",
+ "From computer": "来自电脑",
+ "From bot": "来自 Bot",
+ "To bot": "发给 Bot",
+ "Any computer": "任何电脑",
+ "Any bot": "任何 Bot",
+ "Any bot here": "这里的任何 Bot",
+ "Put it first": "放在最前面",
+ "The first rule that matches decides.": "由第一条匹配的规则决定。",
+ "Offered to the network": "提供给网络",
+ "Bots on your other computers can see and message this bot.": "你其他电脑上的 Bot 能看到这个 Bot 并给它发消息。",
+ "Reachable by cloud assistants": "云端助手可联系",
+ "ChatGPT or Claude in your Codync account can see and message this bot.": "你 Codync 账户里的 ChatGPT 或 Claude 能看到这个 Bot 并给它发消息。",
+ "w shows them all": "w 显示全部",
+ "←→ network": "←→ 网络",
+ "↵ leave · esc cancel": "↵ 离开 · esc 取消",
+ "No rules: every computer in the network may message every bot here.": "没有规则:网络里的每台电脑都能给这里的每个 Bot 发消息。",
+ "n add rule · esc back": "n 添加规则 · esc 返回",
+ "n add rule · x delete · K J move · esc back": "n 添加规则 · x 删除 · K J 移动 · esc 返回",
+ "↵ add · tab next field · ←→ change · esc back": "↵ 添加 · tab 下一栏 · ←→ 更改 · esc 返回",
+ "i invite · p make admin · x remove · w rules · c new · J join · L leave · esc": "i 邀请 · p 设为管理员 · x 移除 · w 规则 · c 新建 · J 加入 · L 离开 · esc",
+ "i invite · x remove · o recover · w rules · c new · J join · L leave · esc": "i 邀请 · x 移除 · o 取回 · w 规则 · c 新建 · J 加入 · L 离开 · esc",
+ "o recover ownership · w rules · c new · J join · L leave · esc": "o 取回所有权 · w 规则 · c 新建 · J 加入 · L 离开 · esc",
+ "Assistants": "助手",
+ "this computer isn't in a network": "这台电脑不在任何网络里",
+ "cloud assistants are off here": "这里的云端助手已关闭",
+ "Offered to the network: bots on your other computers can see and message this bot.": "提供给网络:你其他电脑上的 Bot 能看到这个 Bot 并给它发消息。",
+ "Reachable by cloud assistants: ChatGPT or Claude in your Codync account can see and message this bot.": "云端助手可联系:你 Codync 账户里的 ChatGPT 或 Claude 能看到这个 Bot 并给它发消息。"
}
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 88435c26..21d89af2 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
@@ -1315,5 +1315,52 @@
"Only the owner removes admins; admins remove members": "只有擁有者能移除管理員;管理員能移除成員",
"Network: your other computers…": "網路:你的其他電腦…",
"a switches": "a 切換",
- "Beta": "測試版"
+ "Beta": "測試版",
+ "Leave network": "離開網路",
+ "Leave {network}?": "要離開 {network} 嗎?",
+ "This computer stops being in {network}. The others keep listing it until the owner or an admin removes it there; rejoining needs a new invite.": "這臺電腦將不再屬於 {network}。在擁有者或管理員把它移除之前,其他電腦仍會列出它;要再加入需要新的邀請。",
+ "Leave": "離開",
+ "Network name": "網路名稱",
+ "From the invite": "使用邀請裡的名稱",
+ "It makes another computer the owner of {network} if {name} is lost. It's shown only once and kept on no computer.": "{name} 遺失時,它能讓另一臺電腦成為 {network} 的擁有者。只會顯示這一次,也不會存在任何電腦上。",
+ "Bots message the bots on these computers as bot@computer.{network}.": "Bot 用 bot@電腦.{network} 傳訊息給這些電腦上的 Bot。",
+ "Who may message bots here": "誰可以傳訊息給這裡的 Bot",
+ "The first rule that matches decides. Without rules, every computer in the network may message every bot here. Answers to this computer's own messages always get in.": "由第一條符合的規則決定。沒有規則時,網路裡的每臺電腦都能傳訊息給這裡的每個 Bot。回覆這臺電腦自己送出的訊息一律可以進來。",
+ "Add rule": "新增規則",
+ "Delete rule": "刪除規則",
+ "Allow: {from} → {to}": "允許:{from} → {to}",
+ "Deny: {from} → {to}": "拒絕:{from} → {to}",
+ "any bot on any computer": "任何電腦上的任何 Bot",
+ "any bot on {computer}": "{computer} 上的任何 Bot",
+ "{bot} on {computer}": "{computer} 上的 {bot}",
+ "{bot} on any computer": "任何電腦上的 {bot}",
+ "any bot here": "這裡的任何 Bot",
+ "Deny": "拒絕",
+ "From computer": "來自電腦",
+ "From bot": "來自 Bot",
+ "To bot": "傳給 Bot",
+ "Any computer": "任何電腦",
+ "Any bot": "任何 Bot",
+ "Any bot here": "這裡的任何 Bot",
+ "Put it first": "放在最前面",
+ "The first rule that matches decides.": "由第一條符合的規則決定。",
+ "Offered to the network": "提供給網路",
+ "Bots on your other computers can see and message this bot.": "你其他電腦上的 Bot 能看到這個 Bot 並傳訊息給它。",
+ "Reachable by cloud assistants": "雲端助理可聯繫",
+ "ChatGPT or Claude in your Codync account can see and message this bot.": "你 Codync 賬戶裡的 ChatGPT 或 Claude 能看到這個 Bot 並傳訊息給它。",
+ "w shows them all": "w 顯示全部",
+ "←→ network": "←→ 網路",
+ "↵ leave · esc cancel": "↵ 離開 · esc 取消",
+ "No rules: every computer in the network may message every bot here.": "沒有規則:網路裡的每臺電腦都能傳訊息給這裡的每個 Bot。",
+ "n add rule · esc back": "n 新增規則 · esc 返回",
+ "n add rule · x delete · K J move · esc back": "n 新增規則 · x 刪除 · K J 移動 · esc 返回",
+ "↵ add · tab next field · ←→ change · esc back": "↵ 新增 · tab 下一欄 · ←→ 變更 · esc 返回",
+ "i invite · p make admin · x remove · w rules · c new · J join · L leave · esc": "i 邀請 · p 設為管理員 · x 移除 · w 規則 · c 新增 · J 加入 · L 離開 · esc",
+ "i invite · x remove · o recover · w rules · c new · J join · L leave · esc": "i 邀請 · x 移除 · o 取回 · w 規則 · c 新增 · J 加入 · L 離開 · esc",
+ "o recover ownership · w rules · c new · J join · L leave · esc": "o 取回擁有權 · w 規則 · c 新增 · J 加入 · L 離開 · esc",
+ "Assistants": "助理",
+ "this computer isn't in a network": "這臺電腦不在任何網路裡",
+ "cloud assistants are off here": "這裡的雲端助理已關閉",
+ "Offered to the network: bots on your other computers can see and message this bot.": "提供給網路:你其他電腦上的 Bot 能看到這個 Bot 並傳訊息給它。",
+ "Reachable by cloud assistants: ChatGPT or Claude in your Codync account can see and message this bot.": "雲端助理可聯繫:你 Codync 賬戶裡的 ChatGPT 或 Claude 能看到這個 Bot 並傳訊息給它。"
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swift
index a4dad3b4..4ee5f151 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swift
@@ -255,6 +255,15 @@ struct BotSettingsForm: View {
SwitchRow("Manage the team", detail: "Let this bot create bots and change any bot's setup, its own included. The bots it creates can too.",
isOn: Binding(get: { draft.manageTeam ?? false }, set: { draft.manageTeam = $0 }))
}
+ // Each only where it applies: the computer is in a network, cloud assistants are on.
+ if draft.offeredToNetwork != nil, model.network?.joined == true {
+ SwitchRow("Offered to the network", detail: "Bots on your other computers can see and message this bot.",
+ isOn: Binding(get: { draft.offeredToNetwork ?? true }, set: { draft.offeredToNetwork = $0 }))
+ }
+ if draft.reachableByAssistants != nil, model.network?.assistants == true {
+ SwitchRow("Reachable by cloud assistants", detail: "ChatGPT or Claude in your Codync account can see and message this bot.",
+ isOn: Binding(get: { draft.reachableByAssistants ?? true }, set: { draft.reachableByAssistants = $0 }))
+ }
}
PluginToggles(
diff --git a/apps/ios/Kit/Sources/CodyncUI/NetworkSheet.swift b/apps/ios/Kit/Sources/CodyncUI/NetworkSheet.swift
index ece305ca..2ab6d97b 100644
--- a/apps/ios/Kit/Sources/CodyncUI/NetworkSheet.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/NetworkSheet.swift
@@ -1,8 +1,9 @@
import CodyncKit
import SwiftUI
-/// A computer's network of the user's other computers, read-only: who is in it, whether each one
-/// answers and which bots it offers, and whether cloud assistants may reach this computer's bots.
+/// A computer's networks of the user's other computers, read-only: who is in each, whether each one
+/// answers and which bots it offers, who may message this computer's bots there, and whether cloud
+/// assistants may reach them.
/// Changes are made at a computer. The computer is the `BotStore` in the environment.
public struct NetworkSheet: View {
@Environment(BotStore.self) private var store
@@ -25,9 +26,21 @@ public struct NetworkSheet: View {
}
}
CardForm {
- if let view = store.network, view.joined {
- CardSection("Computers", footer: "Changes are made on a computer: in Codync's settings there, or with codync-host network.") {
- ForEach(view.computers ?? []) { NetworkComputerRow(computer: $0) }
+ let networks = store.network?.networks ?? []
+ ForEach(networks) { network in
+ // One section per network; the note that changes happen at a computer closes the last.
+ CardSection(network.name, footer: network.id == networks.last?.id
+ ? "Changes are made on a computer: in Codync's settings there, or with codync-host network." : nil) {
+ ForEach(network.computers ?? []) { NetworkComputerRow(computer: $0) }
+ }
+ if let rules = network.rules, !rules.isEmpty {
+ CardSection("Who may message bots here", footer: "The first rule that matches decides. Without rules, every computer in the network may message every bot here. Answers to this computer's own messages always get in.") {
+ ForEach(Array(rules.enumerated()), id: \.offset) { _, rule in
+ Text(network.text(of: rule)).font(.subheadline).foregroundStyle(Palette.text)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.vertical, 4)
+ }
+ }
}
}
if store.network?.assistantsAvailable == true {
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/NetworkTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/NetworkTests.swift
index c894bfe6..8b8b8ff7 100644
--- a/apps/ios/Kit/Tests/CodyncKitTests/NetworkTests.swift
+++ b/apps/ios/Kit/Tests/CodyncKitTests/NetworkTests.swift
@@ -2,13 +2,19 @@ import Foundation
import Testing
@testable import CodyncKit
-@Test func decodesTheNetworkViewAndItsEvent() throws {
- let view = #"{"joined":true,"computer":"desk","role":"owner","connector":"public","assistants":true,"assistantsAvailable":true,"computers":[{"name":"desk","role":"owner","me":true,"online":true,"agents":[{"id":"reviewer","name":"Reviewer"}],"canRemove":false,"canPromote":false},{"name":"laptop","role":"overlord","me":false,"online":false,"agents":[],"canRemove":true,"canPromote":true}]}"#
+private let home = #"{"id":"network","name":"home","computer":"desk","role":"owner","canInvite":true,"canRecover":false,"connector":"public","computers":[{"name":"desk","role":"owner","me":true,"online":true,"agents":[{"id":"reviewer","name":"Reviewer"}],"canRemove":false,"canPromote":false},{"name":"laptop","role":"overlord","me":false,"online":false,"agents":[{"id":"lead","name":"Lead"}],"canRemove":true,"canPromote":true}],"rules":[{"fromComputer":"laptop","fromAgent":"lead","toAgent":"reviewer","access":"allow"},{"fromComputer":"laptop","fromAgent":"*","toAgent":"*","access":"deny"},{"fromComputer":"*","fromAgent":"*","toAgent":"coder","access":"later"}]}"#
+private let work = #"{"id":"network-1a2b","name":"work","computer":"desk","role":"member","computers":[],"rules":[]}"#
+
+@Test func decodesEveryNetworkAndItsEvent() throws {
+ let view = #"{"joined":true,"networks":[\#(home),\#(work)],"assistants":true,"assistantsAvailable":true}"#
let decoded = try JSONDecoder().decode(NetworkView.self, from: Data(view.utf8))
- #expect(decoded.joined && decoded.hasContent && decoded.role == .owner)
- #expect(decoded.computers?.map(\.name) == ["desk", "laptop"])
- #expect(decoded.computers?.first?.agents?.first?.name == "Reviewer")
- #expect(decoded.computers?.last?.role == .member, "an unknown role reads as a member")
+ #expect(decoded.joined && decoded.hasContent)
+ #expect(decoded.networks?.map(\.name) == ["home", "work"])
+ let first = try #require(decoded.networks?.first)
+ #expect(first.role == .owner && first.computer == "desk")
+ #expect(first.computers?.map(\.name) == ["desk", "laptop"])
+ #expect(first.computers?.last?.role == .member, "an unknown role reads as a member")
+ #expect(first.rules?.last?.access == .deny, "an unknown access reads as a refusal")
guard case let .network(event) = HostClient.parseEvent(Data(#"{"type":"network","network":\#(view)}"#.utf8)) else {
Issue.record("network event"); return
@@ -16,9 +22,34 @@ import Testing
#expect(event == decoded)
// Outside a network: shown only while cloud assistants can reach this computer and are on.
let alone = { (json: String) in try JSONDecoder().decode(NetworkView.self, from: Data(json.utf8)) }
- #expect(try !alone(#"{"joined":false,"assistants":false,"assistantsAvailable":true}"#).hasContent)
+ #expect(try !alone(#"{"joined":false,"networks":[],"assistants":false,"assistantsAvailable":true}"#).hasContent)
#expect(try !alone(#"{"joined":false,"assistants":true,"assistantsAvailable":false}"#).hasContent, "not in an account")
#expect(try alone(#"{"joined":false,"assistants":true,"assistantsAvailable":true}"#).hasContent)
// A network event this app can't read is skipped, never a rewind.
#expect(HostClient.parseEvent(Data(#"{"type":"network","network":{"joined":"yes"}}"#.utf8)) == nil)
}
+
+@Test func rulesReadWithTheBotsNames() throws {
+ let network = try JSONDecoder().decode(NetworkView.Network.self, from: Data(home.utf8))
+ let texts = (network.rules ?? []).map { network.text(of: $0) }
+ #expect(texts == [
+ "Allow: Lead on laptop → Reviewer",
+ "Deny: any bot on laptop → any bot here",
+ "Deny: any bot on any computer → coder",
+ ])
+ let only = NetworkView.Rule(fromComputer: "*", fromAgent: "lead", toAgent: "*", access: .deny)
+ #expect(network.text(of: only) == "Deny: lead on any computer → any bot here", "never wider than it is")
+}
+
+@Test func botsSayWhetherTheNetworkAndCloudAssistantsReachThem() throws {
+ let bot = { (extra: String) in
+ try JSONDecoder().decode(Bot.self, from: Data(#"{"id":"b","name":"Reviewer","backend":"claude","cwd":"/tmp"\#(extra)}"#.utf8))
+ }
+ let old = try bot("")
+ #expect(old.offeredToNetwork == nil && old.reachableByAssistants == nil, "an older host has no switches")
+ let new = try bot(#","offeredToNetwork":false,"reachableByAssistants":true"#)
+ let draft = BotDraft(new)
+ #expect(draft.offeredToNetwork == false && draft.reachableByAssistants == true)
+ let sent = try JSONSerialization.jsonObject(with: JSONEncoder().encode(BotDraft(old))) as? [String: Any]
+ #expect(sent?["offeredToNetwork"] == nil, "nothing to send to a host without it")
+}
diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.md
index 76a352b0..7c2e4735 100644
--- a/apps/ios/WhatsNew.md
+++ b/apps/ios/WhatsNew.md
@@ -10,8 +10,10 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o
### zh-Hant
- 評分邀請只會在你使用一段時間、看完 Bot 的成果並回到列表後出現,不會在開啟 App 時打擾你。也可以隨時從設定前往 App Store 評分。
-- 設定裡每台電腦多了網路按鈕:看你的電腦網路裡有哪些電腦、是否在線、各自提供哪些 Bot,以及雲端助理是否開啟。網路的建立與邀請要在電腦上的 Codync 進行。
+- 設定裡每台電腦多了網路按鈕(Beta):一台電腦可以加入多個網路,這裡列出每個網路裡有哪些電腦、是否在線、各自提供哪些 Bot、誰可以傳訊息給這裡的 Bot,以及雲端助理是否開啟。網路的建立與邀請要在電腦上的 Codync 進行。
+- Bot 設定多了「提供給網路」與「雲端助理可聯繫」兩個開關,決定其他電腦上的 Bot 與 ChatGPT、Claude 能不能找到它。
### en-US
- Rating invitations wait until you have used Codync for a while, viewed a bot's result, and returned to the list. You can also rate Codync anytime from Settings.
-- A network button on each computer in Settings shows the computers in your network, whether each one answers, the bots it offers, and whether cloud assistants are on. You set up and invite computers in Codync on a computer.
+- A network button (beta) on each computer in Settings: a computer can be in several networks, and it shows each one's computers, whether each answers, the bots it offers, who may message the bots here, and whether cloud assistants are on. You set up and invite computers in Codync on a computer.
+- Bot settings have Offered to the network and Reachable by cloud assistants, so you choose whether bots on your other computers, ChatGPT or Claude can find a bot.
diff --git a/docs/design/codync-network.md b/docs/design/codync-network.md
index 7c3324ce..46ec712c 100644
--- a/docs/design/codync-network.md
+++ b/docs/design/codync-network.md
@@ -97,8 +97,21 @@ optional.
- `agent@computer`, like an email or SSH address. A bare name finds the nearest bot (this computer first); a taken
computer name gets a number (`desk-2`); a bot's address name is never reused for another bot.
-- Several networks per computer come later with a `.network` suffix (`[email protected]`), the way a DNS search
- domain resolves short names; until then a computer is in one network.
+- A computer can be in several networks; the `.network` suffix names one (`[email protected]`), the way a DNS
+ search domain resolves short names: a short address is taken where only one network has it.
+
+## Several networks: one node each
+
+A computer in several networks runs one node per network, each with its own key, roster, connector and rules
+(chosen over one node holding several rosters, which the plan first described):
+
+| | One node per network (chosen) | One node, several rosters |
+|---|---|---|
+| Privacy | a different key in each: one network's members can't tell the computer is also in another | one key everywhere links them |
+| Isolation | a stolen key or bad roster stays in its network | one endpoint and key shared by all |
+| Connectors | per network (private at home, relays for work) | one per computer |
+| Wire | unchanged: old peers keep working | every request names its network |
+| Cost | one endpoint (a socket, a relay connection) per network | one endpoint |
- `list_bots` takes `query`, `computer` (`this` for this one), `online`, `limit` and `cursor`, and an unnarrowed
long list says how many bots each computer has, so a computer with many bots doesn't flood the agent. On one
computer without a network it lists that computer's bots.
@@ -149,10 +162,9 @@ Done: the network screens and the cloud assistants switch in every client (2.29.
terminal UI manage the network, phones show it, and a `network` event keeps them current. Per-bot offering, the
cloud assistant scope and inbound rules, checked by the receiving computer. A computer that moves re-signs where it
is. Cloud assistants and agents that aren't Codync bots (`codync-host mcp network`) reach the bots across the
-network.
+network. A computer can be in several networks.
1. Codync-run iroh relays as the default connector.
-2. Several networks per computer.
-3. Hellos that carry only what changed, lifting the roster's per-computer cap.
-4. Account networks.
-5. A control channel for the standalone daemon on Windows (named pipe).
+2. Hellos that carry only what changed, lifting the roster's per-computer cap.
+3. Account networks; per-network lists of offered bots, for networks shared with other people.
+4. A control channel for the standalone daemon on Windows (named pipe).
diff --git a/docs/features/codync-network.md b/docs/features/codync-network.md
index f4c49560..4ef18628 100644
--- a/docs/features/codync-network.md
+++ b/docs/features/codync-network.md
@@ -1,7 +1,8 @@
# codync-network
-The user's computers join one private network, and a bot on one messages a bot on another the way bots on one
-computer already do ([bot collaboration](bot-collaboration.md)). The network is the `codync-network` crate
+The user's computers join private networks, and a bot on one messages a bot on another the way bots on one
+computer already do ([bot collaboration](bot-collaboration.md)). A computer can be in several networks (`home`,
+`work`), each kept apart ([several networks](#several-networks)). The apps mark it **Beta**. The network is the `codync-network` crate
(`host/crates/network`, its own [README](../../host/crates/network/README.md)): peer to peer over QUIC
([iroh](https://iroh.computer)), with no Codync server involved. It is off until the user creates or joins a network.
Why it is built this way, the options weighed and what comes next: [design](../design/codync-network.md).
@@ -13,13 +14,16 @@ On each computer, in the desktop app (Settings → Computers, the **Network** se
clients that change membership: the `network*` API methods are loopback-only, like pairing a device.
```sh
-codync-host network create [name] [--connector public|private|https://relay] # the first computer: the owner
-codync-host network invite # prints a one-time invite (1 h)
-codync-host network join '<invite>' [name] [--connector …] # on the other computer
-codync-host network # who is around (status)
-codync-host network peers | promote <computer> | remove <computer> [--cascade] | recover <code>
+codync-host network create [name] [--network home] [--connector public|private|https://relay] # this computer owns it
+codync-host network invite [--network home] # prints a one-time invite (1 h)
+codync-host network join '<invite>' [name] [--network …] [--connector …] # on the other computer
+codync-host network # every network and who is around
+codync-host network peers | promote <computer> | remove <computer> [--cascade] | recover <code> | leave
```
+`--network` names the network (by name or id) and may be left out while the computer is in only one; for `create`
+it is the new network's name (default `home`), for `join` it replaces the name the invite carries.
+
The apps show the recovery code once, in a sheet that only "I saved it" closes; the host keeps it nowhere and the
apps never fetch it again. An invite shows when it stops working (`networkInvite` → `expiresAt`). Each computer row
offers only what this computer may do to it: the host says so per row (`canRemove`, `canPromote`, from
@@ -48,6 +52,31 @@ name; a taken name gets a number (`laptop-2`), also when two admins admit the sa
(the later admission gets the number, on every copy). No computer's name changes when another is removed; one
admitted after a removal can take the freed name.
+## Several networks
+
+Each network this computer is in has its **own node**: its own key, roster, connector and rules, in its own folder
+of the data directory (`network` for the first, `network-<id>` after), listed in kv `networks`
+(`host/src/network/saved.rs`). One node per network, rather than one node with several rosters, keeps networks
+apart: members of one can't tell the computer is in another (different keys), a stolen key or a bad roster in one
+reaches no other, connectors differ per network (a private home network, a work one on relays), and nothing on the
+wire changed. The cost is one endpoint per network.
+
+- The view (`networkView`, the `network` event, the hello) lists `networks`, the first being the default, each with
+ its `id`, `name`, this computer's name and role there, `canInvite`/`canRecover`, `connector`, `computers` and
+ `rules`. Methods take `network` (`networkInvite`, `networkRemove`, `setNetworkRules`, …); `networkLeave` stops
+ this computer's node for one and deletes its folder (the others list the computer until they remove it).
+- An invite carries the network's name (`Node::set_network_name`, read with `codync_network::read_invite`), so a
+ computer that joins calls it the same; a name already used here gets a number (`home-2`). Joining a network this
+ computer is already in is refused.
+- **Addresses** name the network when they need to: `[email protected]`. While the computer is in several,
+ `list_bots` ids carry the network (`computer` reads `desk.home`, and the `computer` filter `desk` finds it); a
+ bare name or `name@computer` is taken where exactly one network has it, and two candidates are refused with both
+ full addresses. With one network, ids stay `reviewer@desk`.
+- This computer's bots are offered in every network under the same address name; the per-bot offered switch applies
+ to all of them. Each network's letters come in through its own node and their answers go back through it.
+- A computer that was in one network before keeps it, under the name `home` (its folder and its old kv connector
+ and rules are taken over once).
+
## Who may do what
The roster is a log of signed changes every member keeps a copy of; copies merge, and every computer works out the
@@ -99,6 +128,11 @@ that was off learns of a removal.
8 handoffs per chain, a burst of 5 messages per pair of agents then one every 2 minutes, the same words twice in
10 minutes refused. A letter that isn't a request (a notice, or a reply nobody waits for after a restart) shows as
a "Note from …" notice in the bot's chat.
+- Agents on this computer that aren't Codync bots (a Claude Code or Codex session) get `list_bots`, `message_bot`
+ and `read_replies` from `codync-host mcp network --name "Claude Code"` (stdio MCP, local API `agentCall`, loopback
+ only): the cloud assistant's tools (`chat/team/assistant.rs`), under the agent's own name ("Message from Claude Code
+ (this computer)"), its own replies, no cloud switch and no per-bot cloud scope, and letters elsewhere sent as
+ `agent-<name>@<computer>`. Add it with `claude mcp add codync -- codync-host mcp network --name "Claude Code"`.
- Agents that aren't Codync bots use the same letters: the standalone `codync-network` daemon offers Claude Code
sessions (their inbox socket) and Codex threads (`codex queue`), see the crate README. It keeps its own key in
`~/.codync-network` (the host's is `~/.codync/network`), so beside a host it is a computer of its own.
@@ -128,10 +162,10 @@ and nothing new crosses the wire beyond a refusal's reason.
Planned in order, with what each step touches: [what's left](../plans/codync-network-next.md).
-- One network per computer; the `.network` address suffix comes with several.
-- Shared networks (other people's computers): the offered switch and the rules exist, but per network (with
- several networks per computer) they don't yet.
-- Bots can't reach Claude Code or Codex sessions on another computer through the host (the standalone daemon can).
+- Shared networks (other people's computers): rules are per network, but which bots are offered is one switch per
+ bot for all networks; a per-network list of offered bots comes with networks shared with other people.
+- Bots can't reach Claude Code or Codex sessions on another computer through the host (the standalone daemon can);
+ those sessions reach the bots with `codync-host mcp network`, and the replies wait for `read_replies`.
- Each computer's share of the roster is capped (256 entries) and keeps its oldest: an owner or admin that has
made 256 admissions, promotions and removals can't make more. Hellos sending changes since the last one, instead
of the whole roster, would lift the cap.
@@ -140,12 +174,13 @@ Planned in order, with what each step touches: [what's left](../plans/codync-net
- `host/crates/network`: the crate (`node/`, `roster.rs`, `guard.rs`, `reach.rs`, `wire.rs`); `cargo test -p codync-network`
runs computers on one machine over direct connections, without a relay or internet.
-- `host/src/network/`: the host's node, published bots and address names, the `network*` API methods, `networkView`
- and the `network` event.
+- `host/src/network/`: the host's nodes (one per network, `mod.rs`), the saved networks (`saved.rs`), published bots
+ and address names (`handles.rs`), the `network*` API methods, `networkView` and the `network` event (`api.rs`).
- Clients: desktop `apps/desktop/src/renderer/views/settings/NetworkSection.tsx` (+ `NetworkSheets.tsx`,
`store/network.ts`), terminal `host/src/tui/manage/network.rs` + `view/network.rs`, iPhone
`apps/ios/Kit/Sources/CodyncUI/NetworkSheet.swift`, Android `apps/android/app/.../NetworkSheet.kt`.
-- `host/src/chat/team/remote.rs`, `directory.rs`: requests and replies across computers, `list_bots`.
+- `host/src/chat/team/remote.rs`, `directory.rs`: requests and replies across computers, `list_bots`;
+ `assistant.rs`: the cloud assistant and agents that aren't bots (`codync-host mcp network`, `agentCall`).
- `host/src/network_cli.rs`: `codync-host network`.
- `host/tests/network_e2e.rs`: two real hosts in one network, a bot messaging a bot on the other computer through
approval and back, a request its recipient's user stops and one that fails, and the view with its per-row
diff --git a/docs/plans/codync-network-next.md b/docs/plans/codync-network-next.md
index 68b470a0..affab673 100644
--- a/docs/plans/codync-network-next.md
+++ b/docs/plans/codync-network-next.md
@@ -1,7 +1,9 @@
# codync-network and cloud assistants: what's left
-Status (2026-10-26): package 1 (network screens, cloud assistants switch) is built for 2.29.0; the rest is
-planned. 2.28.0 shipped the network (`host/crates/network`, crate
+Status (2026-10-26): built for 2.29.0: packages 1 (network screens, cloud assistants switch), 2 (access rules), 4
+(a computer's address after it moves), 5 (cloud assistants across the network), 6 (a local MCP server) and several
+networks per computer from 8. Still open: 3 (Codync-run relays: renting servers waits for the user), 7, the account
+networks of 8, 9 and 10. 2.28.0 shipped the network (`host/crates/network`, crate
`codync-network` 0.1.1 on crates.io) and the cloud assistant connector (`mcp.codync.dev`). Read first:
[design](../design/codync-network.md) (why, and the decisions already made), [feature](../features/codync-network.md)
(how it behaves today), [cloud assistants](../features/cloud-assistants.md), [relay §7.9](../reference/remote-relay.md).
@@ -189,7 +191,13 @@ assistant as an agent of that computer (or let the host send letters for it unde
`message_bot` to `name@computer` through `chat::team::remote`, and keep replies in the assistant's reply store. Mind
the ACL from package 2: the assistant is a sender like any other.
-## 6. A local MCP server for agents that aren't Codync bots
+## 6. A local MCP server for agents that aren't Codync bots (built)
+
+Built as `codync-host mcp network --name <agent>`: the cloud assistant's three tools, backed by the host
+(`agentCall`), each agent its own replies; no registration as a network agent, so its answers wait for
+`read_replies` instead of knocking into the session. [Feature](../features/codync-network.md#bots-across-computers).
+
+Before:
Claude Code or Codex sessions on the same computer use the standalone daemon's CLI today. Give them an MCP server:
`codync-host mcp network` over stdio, or the daemon's own. It offers `list_bots`, `message_bot` and `read_replies`,
@@ -206,6 +214,11 @@ frame as the reason. This is a wire change: keep old peers working by falling ba
## 8. Account networks and several networks per computer
+Several networks per computer is built (2.29.0), with one node per network instead of one node with several
+rosters: [design](../design/codync-network.md#several-networks-one-node-each). Account networks and per-network
+lists of offered bots are still to do.
+
+
- **Account networks**: the account vouches for its computers, so a computer signed into the account is admitted
without an invite. It's still signed by a member computer, never by the cloud.
- **Several networks per computer**: addresses get a network suffix (`[email protected]`), bare names resolve
diff --git a/host/src/tui/manage/mod.rs b/host/src/tui/manage/mod.rs
index 788eecc0..b5012eff 100644
--- a/host/src/tui/manage/mod.rs
+++ b/host/src/tui/manage/mod.rs
@@ -13,6 +13,7 @@ mod library;
mod market;
mod memory;
mod network;
+mod network_rules;
mod pages;
mod replies;
mod routines;
@@ -24,6 +25,7 @@ pub use fields::handoff_fields;
pub use library::{ArtifactTitles, LibraryItem};
pub use memory::{MemoryMode, MemorySheet, Scroll, Section};
pub use network::{CONNECTORS, NetReply, NetworkSheet, Setup, SetupField, Step};
+pub use network_rules::{RuleField, RuleForm};
pub use pages::Page;
pub use skill::SkillSheet;
pub use when::complete_zone;
diff --git a/host/src/tui/manage/network.rs b/host/src/tui/manage/network.rs
index 434ec638..d1d55ab2 100644
--- a/host/src/tui/manage/network.rs
+++ b/host/src/tui/manage/network.rs
@@ -1,5 +1,6 @@
-//! The network of the user's computers (codync-network): who is in, inviting, joining, roles,
-//! removal and recovery, and the cloud assistants switch. The TUI runs on the computer, so it
+//! The networks of the user's computers (codync-network) this computer is in: who is in each,
+//! inviting, joining another, leaving, roles, removal, recovery, each network's rules
+//! (`network_rules.rs`), and the cloud assistants switch. The TUI runs on the computer, so it
//! gets everything the desktop app does.
use crossterm::event::{KeyCode, KeyEvent};
@@ -8,6 +9,7 @@ use std::borrow::Cow;
use super::super::app::{After, App, Editor, Overlay, copy};
use super::super::l10n::tr;
+use super::network_rules::RuleForm;
/// How computers reach each other without a direct path: what's shown, what the host takes
/// (empty: the relay address typed under it) and what it means. The desktop app's words.
@@ -21,6 +23,9 @@ pub const CONNECTORS: [(&str, &str, &str); 3] = [
pub struct NetworkSheet {
/// `networkView`'s answer; `None` until it comes.
pub view: Option<Value>,
+ /// The network shown, in `view.networks`.
+ pub net: usize,
+ /// The computer picked in it.
pub cursor: usize,
pub step: Step,
pub error: Option<String>,
@@ -42,12 +47,18 @@ pub enum Step {
computer: String,
cascade: bool,
},
+ Leave,
+ /// The network's rules, and the one picked.
+ Rules(usize),
+ NewRule(RuleForm),
}
/// Creating a network, or joining one with an invite.
#[derive(Default)]
pub struct Setup {
pub invite: Editor,
+ /// The network's name: the new one's, or (joining) instead of the invite's.
+ pub network: Editor,
pub name: Editor,
pub connector: usize,
pub relay: Editor,
@@ -58,6 +69,7 @@ pub struct Setup {
pub enum SetupField {
Invite,
#[default]
+ Network,
Name,
Connector,
Relay,
@@ -70,7 +82,7 @@ impl Setup {
/// The fields in order: joining starts with the invite, a relay URL only for your own relay.
pub fn fields(&self, join: bool) -> Vec<SetupField> {
- let mut fields = vec![SetupField::Name, SetupField::Connector];
+ let mut fields = vec![SetupField::Network, SetupField::Name, SetupField::Connector];
if join {
fields.insert(0, SetupField::Invite);
}
@@ -94,15 +106,18 @@ impl Setup {
}
fn body(&self) -> Value {
- let name = self.name.text.trim();
- json!({"invite": self.invite.text.trim(), "name": (!name.is_empty()).then_some(name), "connector": self.connector()})
+ let given = |e: &Editor| Some(e.text.trim()).filter(|t| !t.is_empty()).map(str::to_owned);
+ json!({
+ "invite": self.invite.text.trim(), "network": given(&self.network), "name": given(&self.name),
+ "connector": self.connector(),
+ })
}
}
/// What a network call's answer is for.
#[derive(Clone, Copy)]
pub enum NetReply {
- /// A view or status to show (`networkView`, `networkPeers`, `networkJoin`).
+ /// A view or status to show (`networkView`, `networkPeers`, `networkJoin`, …).
View,
Created,
Invite,
@@ -111,37 +126,63 @@ pub enum NetReply {
Assistants,
}
-fn rows(view: &Value) -> &[Value] {
- view["computers"].as_array().map_or(&[], Vec::as_slice)
-}
-
impl NetworkSheet {
+ pub fn networks(&self) -> &[Value] {
+ self.view.as_ref().and_then(|v| v["networks"].as_array()).map_or(&[], Vec::as_slice)
+ }
+
+ /// The network shown.
+ pub fn current(&self) -> Option<&Value> {
+ self.networks().get(self.net)
+ }
+
+ /// The shown network's id, for the host's `network`.
+ pub fn id(&self) -> Value {
+ self.current().map_or(Value::Null, |n| n["id"].clone())
+ }
+
pub fn joined(&self) -> bool {
- self.view.as_ref().is_some_and(|v| v["joined"] == true)
+ !self.networks().is_empty()
}
pub fn role(&self) -> &str {
- self.view.as_ref().and_then(|v| v["role"].as_str()).unwrap_or_default()
+ self.current().and_then(|n| n["role"].as_str()).unwrap_or_default()
}
- /// This computer's name in the network.
+ /// This computer's name in the shown network.
pub fn computer(&self) -> Cow<'_, str> {
- self.view.as_ref().and_then(|v| v["computer"].as_str()).map_or_else(|| tr("this computer"), Cow::Borrowed)
+ self.current().and_then(|n| n["computer"].as_str()).map_or_else(|| tr("this computer"), Cow::Borrowed)
}
- /// What the host says this computer may do or has (`canInvite`, `canRecover`,
- /// `assistantsAvailable`, `assistants`).
+ /// What the host says this computer may do in the shown network (`canInvite`, `canRecover`).
+ pub fn may(&self, flag: &str) -> bool {
+ self.current().is_some_and(|n| n[flag] == true)
+ }
+
+ /// What the host says of this computer as a whole (`assistantsAvailable`, `assistants`).
pub fn says(&self, flag: &str) -> bool {
self.view.as_ref().is_some_and(|v| v[flag] == true)
}
pub fn computers(&self) -> &[Value] {
- self.view.as_ref().map_or(&[], rows)
+ self.current().and_then(|n| n["computers"].as_array()).map_or(&[], Vec::as_slice)
+ }
+
+ pub fn rules(&self) -> &[Value] {
+ self.current().and_then(|n| n["rules"].as_array()).map_or(&[], Vec::as_slice)
}
fn selected(&self) -> Option<&Value> {
self.computers().get(self.cursor)
}
+
+ /// Takes a new view, keeping the network shown when it's still there.
+ fn show(&mut self, view: Value) {
+ let shown = self.id();
+ self.view = Some(view);
+ self.net = self.networks().iter().position(|n| n["id"] == shown).unwrap_or(0);
+ self.cursor = self.cursor.min(self.computers().len().saturating_sub(1));
+ }
}
impl App {
@@ -150,7 +191,7 @@ impl App {
self.overlays.push(Overlay::Network(Box::default()));
}
- fn net(&self, method: &'static str, body: Value, r: NetReply) {
+ pub(super) fn net(&self, method: &'static str, body: Value, r: NetReply) {
self.call(method, body, After::Network(r));
}
@@ -159,8 +200,7 @@ impl App {
self.network = view.clone();
for o in &mut self.overlays {
if let Overlay::Network(n) = o {
- n.cursor = n.cursor.min(rows(view).len().saturating_sub(1));
- n.view = Some(view.clone());
+ n.show(view.clone());
}
}
}
@@ -187,13 +227,15 @@ impl App {
let mut flash = None;
match r {
NetReply::View => {
- n.cursor = n.cursor.min(rows(&v).len().saturating_sub(1));
- n.view = Some(v);
- if matches!(n.step, Step::Join(_)) {
+ n.show(v);
+ if matches!(n.step, Step::Join(_) | Step::Leave | Step::NewRule(_)) {
n.step = Step::List;
}
}
NetReply::Created => {
+ if let Some(at) = n.networks().iter().position(|x| x["id"] == v["network"]) {
+ n.net = at;
+ }
n.step = Step::Recovery(v["recoveryCode"].as_str().unwrap_or_default().to_owned());
}
NetReply::Invite => {
@@ -223,9 +265,12 @@ impl App {
Step::Create(s) => self.setup_key(&mut n, s, false, k),
Step::Join(s) => self.setup_key(&mut n, s, true, k),
Step::Recovery(code) => self.recovery_key(code, k),
- Step::Invite(invite) => self.invite_key(invite, k),
+ Step::Invite(invite) => self.invite_key(&n, invite, k),
Step::Recover(code) => self.recover_key(&mut n, code, k),
Step::Remove { computer, cascade } => self.remove_key(&mut n, computer, cascade, k),
+ Step::Leave => self.leave_key(&mut n, k),
+ Step::Rules(at) => self.rules_key(&mut n, at, k),
+ Step::NewRule(form) => self.rule_form_key(&mut n, form, k),
};
Some(Overlay::Network(n))
}
@@ -243,7 +288,7 @@ impl App {
}
}
- fn invite_key(&mut self, invite: Option<(String, i64)>, k: KeyEvent) -> Step {
+ fn invite_key(&mut self, n: &NetworkSheet, invite: Option<(String, i64)>, k: KeyEvent) -> Step {
match (k.code, invite) {
(KeyCode::Esc | KeyCode::Char('q'), _) => Step::List,
(KeyCode::Char('y'), Some((code, until))) => {
@@ -252,7 +297,7 @@ impl App {
Step::Invite(Some((code, until)))
}
(KeyCode::Char('n'), _) => {
- self.net("networkInvite", json!({}), NetReply::Invite);
+ self.net("networkInvite", json!({"network": n.id()}), NetReply::Invite);
Step::Invite(None)
}
(_, invite) => Step::Invite(invite),
@@ -265,7 +310,7 @@ impl App {
KeyCode::Enter if !code.text.trim().is_empty() => {
n.busy = true;
let done = NetReply::Done("This computer is the owner now. Remove the lost computer from the list.");
- self.net("networkRecover", json!({"code": code.text.trim()}), done);
+ self.net("networkRecover", json!({"network": n.id(), "code": code.text.trim()}), done);
Step::Recover(code)
}
_ => {
@@ -281,7 +326,7 @@ impl App {
KeyCode::Char('c' | ' ') => Step::Remove { computer, cascade: !cascade },
KeyCode::Enter => {
n.busy = true;
- let body = json!({"computer": computer, "cascade": cascade});
+ let body = json!({"network": n.id(), "computer": computer, "cascade": cascade});
self.net("networkRemove", body, NetReply::Done("Removed from the network"));
Step::Remove { computer, cascade }
}
@@ -289,31 +334,53 @@ impl App {
}
}
+ fn leave_key(&mut self, n: &mut NetworkSheet, k: KeyEvent) -> Step {
+ match k.code {
+ KeyCode::Esc | KeyCode::Char('q') => Step::List,
+ KeyCode::Enter if !n.busy => {
+ n.busy = true;
+ self.net("networkLeave", json!({"network": n.id()}), NetReply::View);
+ Step::Leave
+ }
+ _ => Step::Leave,
+ }
+ }
+
fn network_list_key(&mut self, mut n: Box<NetworkSheet>, k: KeyEvent) -> Option<Overlay> {
let last = n.computers().len().saturating_sub(1);
let selected = n.selected().cloned();
let name = |c: &Value| c["name"].as_str().unwrap_or_default().to_owned();
+ let count = n.networks().len();
match k.code {
KeyCode::Esc | KeyCode::Char('q' | 'N') => return None,
KeyCode::Down | KeyCode::Char('j') => n.cursor = (n.cursor + 1).min(last),
KeyCode::Up | KeyCode::Char('k') => n.cursor = n.cursor.saturating_sub(1),
+ KeyCode::Left | KeyCode::Right | KeyCode::Char('[' | ']') if count > 1 => {
+ let by = if matches!(k.code, KeyCode::Left | KeyCode::Char('[')) { -1 } else { 1 };
+ n.net = super::super::app::cycle(n.net, by, count);
+ n.cursor = 0;
+ }
KeyCode::Char('a') if n.says("assistantsAvailable") => {
self.net("setAssistants", json!({"enabled": !n.says("assistants")}), NetReply::Assistants);
}
- KeyCode::Char('c') if n.view.is_some() && !n.joined() => n.step = Step::Create(Setup::default()),
- KeyCode::Char('J') if n.view.is_some() && !n.joined() => n.step = Step::Join(Setup::join()),
+ // A computer can be in several networks: these work whether it's in one or not.
+ KeyCode::Char('c') if n.view.is_some() => n.step = Step::Create(Setup::default()),
+ KeyCode::Char('J') if n.view.is_some() => n.step = Step::Join(Setup::join()),
+ KeyCode::Char('L') if n.joined() => n.step = Step::Leave,
+ KeyCode::Char('w') if n.joined() => n.step = Step::Rules(0),
KeyCode::Char('r') if n.joined() => {
n.busy = true;
- self.net("networkPeers", json!({}), NetReply::View);
+ self.net("networkPeers", json!({"network": n.id()}), NetReply::View);
}
- KeyCode::Char('i') if n.says("canInvite") => {
- self.net("networkInvite", json!({}), NetReply::Invite);
+ KeyCode::Char('i') if n.may("canInvite") => {
+ self.net("networkInvite", json!({"network": n.id()}), NetReply::Invite);
n.step = Step::Invite(None);
}
- KeyCode::Char('o') if n.says("canRecover") => n.step = Step::Recover(Editor::default()),
+ KeyCode::Char('o') if n.may("canRecover") => n.step = Step::Recover(Editor::default()),
KeyCode::Char('p') => match selected {
Some(c) if c["canPromote"] == true => {
- self.net("networkPromote", json!({"computer": name(&c)}), NetReply::Done("Made an admin"));
+ let body = json!({"network": n.id(), "computer": name(&c)});
+ self.net("networkPromote", body, NetReply::Done("Made an admin"));
}
Some(_) => self.flash("Only the owner makes plain members admins"),
None => {}
@@ -359,6 +426,7 @@ impl App {
_ => {
let editor = match s.field {
SetupField::Invite => Some(&mut s.invite),
+ SetupField::Network => Some(&mut s.network),
SetupField::Name => Some(&mut s.name),
SetupField::Relay => Some(&mut s.relay),
SetupField::Connector => None,
@@ -373,32 +441,38 @@ impl App {
}
#[cfg(test)]
-mod tests {
+pub(super) mod tests {
use super::super::super::app::test_app;
use super::*;
use crossterm::event::KeyModifiers;
- fn key(c: KeyCode) -> KeyEvent {
+ pub(in crate::tui::manage) fn key(c: KeyCode) -> KeyEvent {
KeyEvent::new(c, KeyModifiers::NONE)
}
- fn joined(role: &str) -> Value {
- json!({"joined": true, "computer": "desk", "role": role, "canInvite": role != "member", "canRecover": role != "owner",
- "assistants": false, "assistantsAvailable": true, "computers": [
- {"name": "desk", "role": role, "me": true, "online": true, "agents": [], "canRemove": false, "canPromote": false},
+ fn network(id: &str, role: &str, rules: &Value) -> Value {
+ json!({"id": id, "name": id, "computer": "desk", "role": role, "canInvite": role != "member",
+ "canRecover": role != "owner", "rules": rules, "computers": [
+ {"name": "desk", "role": role, "me": true, "online": true, "agents": [{"id": "reviewer", "name": "Reviewer"}],
+ "canRemove": false, "canPromote": false},
{"name": "laptop", "role": "member", "me": false, "online": true, "agents": [{"id": "coder", "name": "Coder"}],
"canRemove": role != "member", "canPromote": role == "owner"},
]})
}
- fn sheet(view: Value) -> Box<NetworkSheet> {
+ pub(in crate::tui::manage) fn sheet(networks: &[Value]) -> Box<NetworkSheet> {
+ let view = json!({"joined": !networks.is_empty(), "networks": networks, "assistants": false, "assistantsAvailable": true});
Box::new(NetworkSheet { view: Some(view), ..NetworkSheet::default() })
}
+ pub(in crate::tui::manage) fn owner() -> Box<NetworkSheet> {
+ sheet(&[network("home", "owner", &json!([]))])
+ }
+
#[tokio::test]
async fn removing_asks_first_and_cascade_is_a_choice() {
let mut app = test_app();
- let mut n = sheet(joined("owner"));
+ let mut n = owner();
n.cursor = 1;
let Some(Overlay::Network(n)) = app.network_key(n, key(KeyCode::Char('x'))) else { panic!("kept open") };
assert!(matches!(&n.step, Step::Remove { computer, cascade: false } if computer == "laptop"));
@@ -411,7 +485,7 @@ mod tests {
#[tokio::test]
async fn a_member_cant_remove_and_the_recovery_code_needs_saving() {
let mut app = test_app();
- let mut n = sheet(joined("member"));
+ let mut n = sheet(&[network("home", "member", &json!([]))]);
n.cursor = 1;
let Some(Overlay::Network(mut n)) = app.network_key(n, key(KeyCode::Char('x'))) else { panic!("kept open") };
assert!(matches!(n.step, Step::List), "the host said it can't");
@@ -430,14 +504,34 @@ mod tests {
assert!(matches!(&n.step, Step::Recovery(code) if code == "1234"));
}
+ #[tokio::test]
+ async fn several_networks_switch_and_a_new_view_keeps_the_one_shown() {
+ let mut app = test_app();
+ let n = sheet(&[network("home", "owner", &json!([])), network("work", "member", &json!([]))]);
+ assert_eq!(n.id(), "home");
+ let Some(Overlay::Network(mut n)) = app.network_key(n, key(KeyCode::Char(']'))) else { panic!("kept open") };
+ assert_eq!((n.id(), n.role()), (json!("work"), "member"));
+ // Work comes first in the next view: the sheet stays on work.
+ let view = json!({"networks": [network("work", "member", &json!([])), network("home", "owner", &json!([]))]});
+ n.show(view);
+ assert_eq!((n.net, n.id()), (0, json!("work")));
+ // Creating or joining another is always there.
+ let Some(Overlay::Network(n)) = app.network_key(n, key(KeyCode::Char('c'))) else { panic!("kept open") };
+ assert!(matches!(n.step, Step::Create(_)));
+ }
+
#[test]
fn a_relay_url_field_only_for_your_own_relay() {
let mut s = Setup::join();
- assert_eq!(s.fields(true), [SetupField::Invite, SetupField::Name, SetupField::Connector]);
+ assert_eq!(s.fields(true), [SetupField::Invite, SetupField::Network, SetupField::Name, SetupField::Connector]);
s.connector = 2;
- assert_eq!(s.fields(false), [SetupField::Name, SetupField::Connector, SetupField::Relay]);
+ assert_eq!(s.fields(false), [SetupField::Network, SetupField::Name, SetupField::Connector, SetupField::Relay]);
s.relay = Editor::with(" https://relay.example ");
assert_eq!(s.body()["connector"], "https://relay.example");
- assert_eq!(s.body()["name"], Value::Null, "the host name when left empty");
+ assert_eq!(
+ (&s.body()["name"], &s.body()["network"]),
+ (&Value::Null, &Value::Null),
+ "the defaults when left empty"
+ );
}
}
diff --git a/host/src/tui/manage/network_rules.rs b/host/src/tui/manage/network_rules.rs
new file mode 100644
index 00000000..16e75489
--- /dev/null
+++ b/host/src/tui/manage/network_rules.rs
@@ -0,0 +1,227 @@
+//! A network's rules in the network sheet: who on its other computers may message this
+//! computer's bots, the first match deciding (`codync_network::rules`).
+
+use crossterm::event::{KeyCode, KeyEvent};
+use serde_json::{Value, json};
+
+use super::super::app::{App, cycle};
+use super::super::l10n::tr;
+use super::network::{NetReply, NetworkSheet, Step};
+
+const ANY: &str = "*";
+
+/// A new rule: each choice cycles through "any" and the names the network offers.
+#[derive(Default)]
+pub struct RuleForm {
+ pub deny: bool,
+ /// Index into `NetworkSheet::rule_choices`; 0 is any.
+ pub from_computer: usize,
+ pub from_agent: usize,
+ pub to_agent: usize,
+ /// Put it on top instead of after the others.
+ pub first: bool,
+ pub field: RuleField,
+}
+
+#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
+pub enum RuleField {
+ #[default]
+ Access,
+ FromComputer,
+ FromAgent,
+ ToAgent,
+ First,
+}
+
+const FIELDS: [RuleField; 5] =
+ [RuleField::Access, RuleField::FromComputer, RuleField::FromAgent, RuleField::ToAgent, RuleField::First];
+
+/// What one of the rule form's choices offers: `*` first, then names and how they read.
+pub struct Choices {
+ pub computers: Vec<(String, String)>,
+ pub agents: Vec<(String, String)>,
+ pub mine: Vec<(String, String)>,
+}
+
+impl NetworkSheet {
+ /// The other computers, the agents of the one picked, and this computer's own.
+ pub fn rule_choices(&self, form: &RuleForm) -> Choices {
+ let any = |label: &str| (ANY.to_owned(), tr(label).into_owned());
+ let agents_of = |c: &Value| -> Vec<(String, String)> {
+ c["agents"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .map(|a| {
+ (s(a, "id"), a["name"].as_str().unwrap_or_else(|| a["id"].as_str().unwrap_or_default()).into())
+ })
+ .collect()
+ };
+ let others: Vec<&Value> = self.computers().iter().filter(|c| c["me"] != true).collect();
+ let mut computers = vec![any("Any computer")];
+ computers.extend(others.iter().map(|c| (s(c, "name"), s(c, "name"))));
+ let mut agents = vec![any("Any bot")];
+ if form.from_computer > 0
+ && let Some(c) = others.get(form.from_computer - 1)
+ {
+ agents.extend(agents_of(c));
+ }
+ let mut mine = vec![any("Any bot here")];
+ if let Some(me) = self.computers().iter().find(|c| c["me"] == true) {
+ mine.extend(agents_of(me));
+ }
+ Choices { computers, agents, mine }
+ }
+
+ /// How a rule reads: "Deny: any bot on laptop → any bot here".
+ pub fn rule_text(&self, rule: &Value) -> String {
+ let computer = s(rule, "fromComputer");
+ let agent = s(rule, "fromAgent");
+ let name_on = |computer: &str, id: &str| {
+ self.computers()
+ .iter()
+ .find(|c| c["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(computer)))
+ .and_then(|c| {
+ c["agents"].as_array()?.iter().find(|a| a["id"] == id)?["name"].as_str().map(str::to_owned)
+ })
+ .unwrap_or_else(|| id.to_owned())
+ };
+ let from = match (computer.as_str(), agent.as_str()) {
+ (ANY, ANY) => tr("any bot on any computer").into_owned(),
+ (ANY, agent) => tr("{bot} on any computer").replace("{bot}", agent),
+ (computer, ANY) => tr("any bot on {computer}").replace("{computer}", computer),
+ (computer, agent) => {
+ tr("{bot} on {computer}").replace("{bot}", &name_on(computer, agent)).replace("{computer}", computer)
+ }
+ };
+ let to = match s(rule, "toAgent").as_str() {
+ ANY => tr("any bot here").into_owned(),
+ id => self.computers().iter().find(|c| c["me"] == true).map_or_else(
+ || id.to_owned(),
+ |me| {
+ me["agents"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .find(|a| a["id"] == id)
+ .and_then(|a| a["name"].as_str())
+ .unwrap_or(id)
+ .to_owned()
+ },
+ ),
+ };
+ let template = if rule["access"] == "deny" { "Deny: {from} → {to}" } else { "Allow: {from} → {to}" };
+ tr(template).replace("{from}", &from).replace("{to}", &to)
+ }
+}
+
+fn s(v: &Value, k: &str) -> String {
+ v[k].as_str().unwrap_or_default().to_owned()
+}
+
+impl App {
+ /// Keys over the rules list: `n` adds one, `x` deletes, `K`/`J` move the picked one.
+ pub(super) fn rules_key(&mut self, n: &mut NetworkSheet, at: usize, k: KeyEvent) -> Step {
+ let mut rules: Vec<Value> = n.rules().to_vec();
+ let last = rules.len().saturating_sub(1);
+ match k.code {
+ KeyCode::Esc | KeyCode::Char('q' | 'w') => return Step::List,
+ KeyCode::Down | KeyCode::Char('j') => return Step::Rules((at + 1).min(last)),
+ KeyCode::Up | KeyCode::Char('k') => return Step::Rules(at.saturating_sub(1)),
+ KeyCode::Char('n') => return Step::NewRule(RuleForm::default()),
+ KeyCode::Char('x') if at < rules.len() => {
+ rules.remove(at);
+ }
+ KeyCode::Char('K') if at > 0 && at < rules.len() => rules.swap(at, at - 1),
+ KeyCode::Char('J') if at < last => rules.swap(at, at + 1),
+ _ => return Step::Rules(at),
+ }
+ let moved = match k.code {
+ KeyCode::Char('K') => at - 1,
+ KeyCode::Char('J') => at + 1,
+ _ => at.min(rules.len().saturating_sub(1)),
+ };
+ self.save_rules(n, &rules);
+ Step::Rules(moved)
+ }
+
+ pub(super) fn rule_form_key(&mut self, n: &mut NetworkSheet, mut form: RuleForm, k: KeyEvent) -> Step {
+ let choices = n.rule_choices(&form);
+ let i = FIELDS.iter().position(|f| *f == form.field).unwrap_or(0);
+ match k.code {
+ KeyCode::Esc => return Step::Rules(0),
+ KeyCode::Tab | KeyCode::Down => form.field = FIELDS[cycle(i, 1, FIELDS.len())],
+ KeyCode::BackTab | KeyCode::Up => form.field = FIELDS[cycle(i, -1, FIELDS.len())],
+ KeyCode::Left | KeyCode::Right | KeyCode::Char(' ') => {
+ let by = if k.code == KeyCode::Left { -1 } else { 1 };
+ match form.field {
+ RuleField::Access => form.deny = !form.deny,
+ RuleField::FromComputer => {
+ form.from_computer = cycle(form.from_computer, by, choices.computers.len());
+ form.from_agent = 0;
+ }
+ RuleField::FromAgent => form.from_agent = cycle(form.from_agent, by, choices.agents.len()),
+ RuleField::ToAgent => form.to_agent = cycle(form.to_agent, by, choices.mine.len()),
+ RuleField::First => form.first = !form.first,
+ }
+ }
+ KeyCode::Enter => {
+ let pick =
+ |list: &[(String, String)], i: usize| list.get(i).map_or_else(|| ANY.to_owned(), |c| c.0.clone());
+ let rule = json!({
+ "fromComputer": pick(&choices.computers, form.from_computer),
+ "fromAgent": pick(&choices.agents, form.from_agent),
+ "toAgent": pick(&choices.mine, form.to_agent),
+ "access": if form.deny { "deny" } else { "allow" },
+ });
+ let mut rules: Vec<Value> = n.rules().to_vec();
+ if form.first {
+ rules.insert(0, rule);
+ } else {
+ rules.push(rule);
+ }
+ self.save_rules(n, &rules);
+ return Step::Rules(if form.first { 0 } else { n.rules().len() });
+ }
+ _ => {}
+ }
+ Step::NewRule(form)
+ }
+
+ fn save_rules(&self, n: &mut NetworkSheet, rules: &[Value]) {
+ n.busy = true;
+ self.net("setNetworkRules", json!({"network": n.id(), "rules": rules}), NetReply::View);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::super::super::app::test_app;
+ use super::super::network::tests::{key, owner};
+ use super::*;
+
+ #[test]
+ fn rules_read_with_the_bots_names() {
+ let n = owner();
+ let deny = json!({"fromComputer": "laptop", "fromAgent": "*", "toAgent": "*", "access": "deny"});
+ assert_eq!(n.rule_text(&deny), "Deny: any bot on laptop → any bot here");
+ let allow = json!({"fromComputer": "laptop", "fromAgent": "coder", "toAgent": "reviewer", "access": "allow"});
+ assert_eq!(n.rule_text(&allow), "Allow: Coder on laptop → Reviewer");
+ }
+
+ #[tokio::test]
+ async fn a_new_rule_picks_from_what_the_network_offers() {
+ let mut app = test_app();
+ let mut n = owner();
+ let mut form = RuleForm::default();
+ for k in [KeyCode::Right, KeyCode::Tab, KeyCode::Right, KeyCode::Tab, KeyCode::Right] {
+ let Step::NewRule(next) = app.rule_form_key(&mut n, form, key(k)) else { panic!("still the form") };
+ form = next;
+ }
+ let choices = n.rule_choices(&form);
+ assert_eq!((form.deny, choices.computers[form.from_computer].0.as_str()), (true, "laptop"));
+ assert_eq!(choices.agents[form.from_agent].0, "coder", "only the laptop's agents once it's picked");
+ assert!(matches!(app.rule_form_key(&mut n, form, key(KeyCode::Enter)), Step::Rules(_)));
+ assert!(n.busy, "saved with setNetworkRules");
+ }
+}
diff --git a/host/src/tui/view/mod.rs b/host/src/tui/view/mod.rs
index e5e33759..5955e2c5 100644
--- a/host/src/tui/view/mod.rs
+++ b/host/src/tui/view/mod.rs
@@ -18,6 +18,7 @@ mod goto;
mod help;
mod lead_agent;
mod network;
+mod network_rules;
mod new_bot;
mod overlay;
mod pair;
diff --git a/host/src/tui/view/network.rs b/host/src/tui/view/network.rs
index 9a6020b9..aaae8c89 100644
--- a/host/src/tui/view/network.rs
+++ b/host/src/tui/view/network.rs
@@ -11,6 +11,7 @@ use super::super::l10n::tr;
use super::super::manage::{CONNECTORS, NetworkSheet, Setup, SetupField, Step};
use super::super::md;
use super::buffer::{centered, frame_box, hline, put, put_line, restyle, rput};
+use super::network_rules::{rule_form, rules};
use super::overlay::input_line;
use super::style::theme;
use super::time::clock;
@@ -33,6 +34,9 @@ pub(super) fn network(buf: &mut Buffer, area: Rect, n: &NetworkSheet) {
Step::Invite(invite) => invite_step(buf, body, n, invite.as_ref()),
Step::Recover(code) => recover(buf, body, code),
Step::Remove { computer, cascade } => remove(buf, body, computer, *cascade),
+ Step::Leave => leave(buf, body, n),
+ Step::Rules(at) => rules(buf, body, n, *at),
+ Step::NewRule(form) => rule_form(buf, body, n, form),
};
if let Some(e) = &n.error {
put(buf, inner.x, inner.bottom() - 3, inner.width, e, t.red.patch(t.panel));
@@ -49,9 +53,11 @@ fn recovery(buf: &mut Buffer, body: Rect, n: &NetworkSheet, code: &str) -> &'sta
y += 1;
line(buf, body, &mut y, code, t.bold);
y += 1;
- let note =
- tr("It makes another computer the owner if {name} is lost. It's shown only once and kept on no computer.");
- wrapped(buf, body, &mut y, &note.replace("{name}", &n.computer()), t.secondary);
+ let network = n.current().and_then(|x| x["name"].as_str()).unwrap_or_default();
+ let note = tr(
+ "It makes another computer the owner of {network} if {name} is lost. It's shown only once and kept on no computer.",
+ );
+ wrapped(buf, body, &mut y, &note.replace("{network}", network).replace("{name}", &n.computer()), t.secondary);
"y copy · s I saved it"
}
@@ -85,6 +91,18 @@ fn recover(buf: &mut Buffer, body: Rect, code: &Editor) -> &'static str {
"↵ recover · esc back"
}
+fn leave(buf: &mut Buffer, body: Rect, n: &NetworkSheet) -> &'static str {
+ let t = theme();
+ let mut y = body.y;
+ let network = n.current().and_then(|x| x["name"].as_str()).unwrap_or_default();
+ line(buf, body, &mut y, &tr("Leave {network}?").replace("{network}", network), t.red);
+ let note = tr(
+ "This computer stops being in {network}. The others keep listing it until the owner or an admin removes it there; rejoining needs a new invite.",
+ );
+ wrapped(buf, body, &mut y, &note.replace("{network}", network), t.text);
+ "↵ leave · esc cancel"
+}
+
fn remove(buf: &mut Buffer, body: Rect, computer: &str, cascade: bool) -> &'static str {
let t = theme();
let mut y = body.y;
@@ -101,22 +119,35 @@ fn remove(buf: &mut Buffer, body: Rect, computer: &str, cascade: bool) -> &'stat
fn list(buf: &mut Buffer, body: Rect, n: &NetworkSheet) -> &'static str {
let t = theme();
let mut y = body.y;
- let Some(view) = &n.view else {
+ if n.view.is_none() {
put(buf, body.x, y, body.width, &tr("Loading…"), t.dim.patch(t.panel));
return "esc close";
- };
- if n.joined() {
+ }
+ if let Some(current) = n.current() {
+ y = networks_line(buf, body, y, n);
let me = n.computer();
let role = role_name(n.role());
- let connector = view["connector"].as_str().unwrap_or("public");
+ let connector = current["connector"].as_str().unwrap_or("public");
put(buf, body.x, y, body.width, &format!("{me} · {role} · {connector}"), t.secondary.patch(t.panel));
y += 2;
- let room = usize::from(body.height).saturating_sub(7).max(1);
+ let rule_rows = n.rules().len().min(3);
+ let room = usize::from(body.height).saturating_sub(9 + rule_rows).max(1);
let off = n.cursor.saturating_sub(room.saturating_sub(1));
for (i, c) in n.computers().iter().enumerate().skip(off).take(room) {
computer_row(buf, body, y, c, i == n.cursor);
y += 1;
}
+ if rule_rows > 0 {
+ y += 1;
+ put(buf, body.x, y, body.width, &tr("Who may message bots here"), t.bold.patch(t.panel));
+ y += 1;
+ for rule in n.rules().iter().take(rule_rows) {
+ line(buf, body, &mut y, &format!(" {}", n.rule_text(rule)), t.secondary);
+ }
+ if n.rules().len() > rule_rows {
+ line(buf, body, &mut y, &format!(" {}", tr("w shows them all")), t.dim);
+ }
+ }
} else {
put(buf, body.x, y, body.width, &tr("Not in a network."), t.bold.patch(t.panel));
y += 1;
@@ -126,12 +157,28 @@ fn list(buf: &mut Buffer, body: Rect, n: &NetworkSheet) -> &'static str {
if n.says("assistantsAvailable") {
assistants(buf, body, y + 1, n.says("assistants"));
}
- match (n.joined(), n.says("canInvite"), n.says("canRecover")) {
+ match (n.joined(), n.may("canInvite"), n.may("canRecover")) {
(false, ..) => "c create network · J join with invite · esc close",
- (true, true, false) => "i invite · p make admin · x remove · r refresh · esc close",
- (true, true, true) => "i invite · x remove · o recover ownership · r refresh · esc close",
- (true, false, _) => "o recover ownership · r refresh · esc close",
+ (true, true, false) => "i invite · p make admin · x remove · w rules · c new · J join · L leave · esc",
+ (true, true, true) => "i invite · x remove · o recover · w rules · c new · J join · L leave · esc",
+ (true, false, _) => "o recover ownership · w rules · c new · J join · L leave · esc",
+ }
+}
+
+/// The networks this computer is in, the shown one bracketed; switching only when there are several.
+fn networks_line(buf: &mut Buffer, body: Rect, y: u16, n: &NetworkSheet) -> u16 {
+ let t = theme();
+ let mut x = body.x;
+ for (i, net) in n.networks().iter().enumerate() {
+ let name = net["name"].as_str().unwrap_or_default();
+ let (text, style) =
+ if i == n.net { (format!("‹ {name} ›"), t.bold) } else { (format!(" {name} "), t.secondary) };
+ x = put(buf, x, y, body.right().saturating_sub(x), &text, style.patch(t.panel));
}
+ if n.networks().len() > 1 {
+ rput(buf, body.right(), y, &tr("←→ network"), t.dim.patch(t.panel));
+ }
+ y + 1
}
/// The cloud assistants switch, for a computer in a Codync account (only there can they reach it).
@@ -194,6 +241,7 @@ fn setup(buf: &mut Buffer, body: Rect, s: &Setup, join: bool) -> &'static str {
let active = field == s.field;
let label = match field {
SetupField::Invite => "Invite",
+ SetupField::Network => "Network name",
SetupField::Name => "Computer name",
SetupField::Connector => "Connector",
SetupField::Relay => "Relay address",
@@ -205,6 +253,10 @@ fn setup(buf: &mut Buffer, body: Rect, s: &Setup, join: bool) -> &'static str {
SetupField::Invite => {
input_line(buf, r, y, &s.invite, "Paste the invite from the other computer.", active, false);
}
+ SetupField::Network => {
+ let hint = if join { "From the invite" } else { "home" };
+ input_line(buf, r, y, &s.network, hint, active, false);
+ }
SetupField::Name => input_line(buf, r, y, &s.name, "Host name", active, false),
SetupField::Relay => input_line(buf, r, y, &s.relay, "https://relay.example.com", active, false),
SetupField::Connector => {
@@ -219,14 +271,14 @@ fn setup(buf: &mut Buffer, body: Rect, s: &Setup, join: bool) -> &'static str {
"↵ done · tab next field · ←→ connector · esc back"
}
-fn line(buf: &mut Buffer, body: Rect, y: &mut u16, text: &str, style: Style) {
+pub(super) fn line(buf: &mut Buffer, body: Rect, y: &mut u16, text: &str, style: Style) {
if *y < body.bottom() {
put(buf, body.x, *y, body.width, text, style.patch(theme().panel));
*y += 1;
}
}
-fn wrapped(buf: &mut Buffer, body: Rect, y: &mut u16, text: &str, style: Style) {
+pub(super) fn wrapped(buf: &mut Buffer, body: Rect, y: &mut u16, text: &str, style: Style) {
let t = theme();
let width = usize::from(body.width);
for l in md::wrap(&[Span::styled(text.to_owned(), style.patch(t.panel))], width, &[], &[]) {
diff --git a/host/src/tui/view/network_rules.rs b/host/src/tui/view/network_rules.rs
new file mode 100644
index 00000000..81b5105a
--- /dev/null
+++ b/host/src/tui/view/network_rules.rs
@@ -0,0 +1,69 @@
+//! A network's rules in the network sheet: the list, and the form for a new one.
+
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+
+use super::super::l10n::tr;
+use super::super::manage::{NetworkSheet, RuleField, RuleForm};
+use super::buffer::{put, restyle};
+use super::network::{line, wrapped};
+use super::style::theme;
+
+const FOOTER: &str = "The first rule that matches decides. Without rules, every computer in the network may message every bot here. Answers to this computer's own messages always get in.";
+
+pub(super) fn rules(buf: &mut Buffer, body: Rect, n: &NetworkSheet, at: usize) -> &'static str {
+ let t = theme();
+ let mut y = body.y;
+ line(buf, body, &mut y, &tr("Who may message bots here"), t.bold);
+ y += 1;
+ if n.rules().is_empty() {
+ line(
+ buf,
+ body,
+ &mut y,
+ &tr("No rules: every computer in the network may message every bot here."),
+ t.secondary,
+ );
+ }
+ for (i, rule) in n.rules().iter().enumerate() {
+ if y >= body.bottom().saturating_sub(4) {
+ break;
+ }
+ let sel = i == at;
+ if sel {
+ restyle(buf, Rect::new(body.x - 1, y, body.width + 2, 1), t.sel);
+ }
+ let base = if sel { t.sel } else { t.panel };
+ put(buf, body.x, y, body.width, &format!("{:>2} {}", i + 1, n.rule_text(rule)), t.text.patch(base));
+ y += 1;
+ }
+ y += 1;
+ wrapped(buf, body, &mut y, &tr(FOOTER), t.secondary);
+ if n.rules().is_empty() { "n add rule · esc back" } else { "n add rule · x delete · K J move · esc back" }
+}
+
+pub(super) fn rule_form(buf: &mut Buffer, body: Rect, n: &NetworkSheet, form: &RuleForm) -> &'static str {
+ let t = theme();
+ let choices = n.rule_choices(form);
+ let mut y = body.y;
+ line(buf, body, &mut y, &tr("Add rule"), t.bold);
+ y += 1;
+ let label = |c: &[(String, String)], i: usize| c.get(i).map_or_else(String::new, |c| c.1.clone());
+ let rows = [
+ (RuleField::Access, "Access", tr(if form.deny { "Deny" } else { "Allow" }).into_owned()),
+ (RuleField::FromComputer, "From computer", label(&choices.computers, form.from_computer)),
+ (RuleField::FromAgent, "From bot", label(&choices.agents, form.from_agent)),
+ (RuleField::ToAgent, "To bot", label(&choices.mine, form.to_agent)),
+ (RuleField::First, "Put it first", tr(if form.first { "On" } else { "Off" }).into_owned()),
+ ];
+ for (field, name, value) in rows {
+ let active = field == form.field;
+ let style = if active { t.bold } else { t.secondary };
+ put(buf, body.x, y, 18, &tr(name), style.patch(t.panel));
+ put(buf, body.x + 18, y, body.width.saturating_sub(18), &format!("‹ {value} ›"), style.patch(t.panel));
+ y += 1;
+ }
+ y += 1;
+ wrapped(buf, body, &mut y, &tr(FOOTER), t.secondary);
+ "↵ add · tab next field · ←→ change · esc back"
+}
diff --git a/web/content/docs/cloud-assistants.mdx b/web/content/docs/cloud-assistants.mdx
index a7dc8533..3f9ce723 100644
--- a/web/content/docs/cloud-assistants.mdx
+++ b/web/content/docs/cloud-assistants.mdx
@@ -10,6 +10,8 @@ Cloud assistants are off on every computer until you turn them on there, at the
The switch carries the same warning as [Privacy](#privacy) below: Codync's cloud can read these calls. Phones show whether it's on (the network button on a computer's row in **Settings**) but can't change it. The computer has to be in your Codync account (signed in) and use the Codync relay.
+To keep one bot away from cloud assistants while they're on, turn off **Reachable by cloud assistants** in its settings.
+
## Add the connector
In your assistant's settings, add a custom connector (it may be called a connector, an app or an MCP server) with this address:
diff --git a/web/content/docs/teamwork.mdx b/web/content/docs/teamwork.mdx
index 571a60dc..67a69afe 100644
--- a/web/content/docs/teamwork.mdx
+++ b/web/content/docs/teamwork.mdx
@@ -54,25 +54,48 @@ In a [group chat](/docs/groups), members don't message each other this way; they
## Bots on your other computers
-Your computers can join one private network, codync-network, so a bot on your desktop can ask a bot on your laptop or server. Computers connect to each other directly; when they can't, traffic goes through a relay that sees only encrypted data. The network stays off until you set it up on each computer, in the Codync app or the terminal UI there. Phones only show it: who is in the network is decided at a computer.
+Your computers can join private networks, codync-network, so a bot on your desktop can ask a bot on your laptop or server. Computers connect to each other directly; when they can't, traffic goes through a relay that sees only encrypted data. Networks stay off until you set them up on each computer, in the Codync app or the terminal UI there. Phones only show them: who is in a network is decided at a computer. Networks are a **beta** feature.
- **Desktop:** Settings → **Computers**, the **Network** section under each computer.
- **Terminal UI:** `N` (or **Network** in the `^k` palette).
- **iPhone and Android:** the network button on a computer's row in **Settings** lists the computers, whether each one answers and the bots it offers.
-On the first computer, choose **Create network**. That computer becomes its owner. Codync then shows a **recovery code**, once: keep it in a password manager. It makes another computer the owner if this one is lost (**Recover ownership** on that computer), and it's kept on no computer, so it can't be shown again.
+On the first computer, choose **Create network** and give the network a name (for example `home`). That computer becomes its owner. Codync then shows a **recovery code**, once: keep it in a password manager. It makes another computer the owner if this one is lost (**Recover ownership** on that computer), and it's kept on no computer, so it can't be shown again.
Then add each other computer with a one-time invite, good for an hour while the inviting computer stays on: **Invite a computer** on the owner, then **Join with invite** on the new computer and paste it.
The network lists every computer with its role, whether it answers and how many bots it offers. The owner can make a computer an admin (**Make admin**), which can then invite computers and remove plain members too. **Remove** takes a computer out for good; **Remove with its invites** is for a stolen one, to also remove every computer it added. A computer that was off hears about a removal when it's back.
-Prefer the command line? `codync-host network` does the same: `create [name]`, `invite`, `join '<invite>' [name]`, `peers`, `promote <computer>`, `remove <computer> [--cascade]` and `recover <code>`. On a Mac where you installed the app from the disk image rather than with Homebrew, `codync-host` is inside the app: `/Applications/Codync.app/Contents/Resources/codync-host`.
+### Several networks
+
+A computer can be in more than one network, for example `home` with your laptop and `work` with a server. Each network is separate: its own members, roles, invites and rules, and the computers in one don't learn that yours is also in another. Create or join another one the same way; the invite brings the network's name with it. **Leave network** takes this computer out of one (the others keep listing it until you remove it there).
+
+While a computer is in several networks, addresses name the network: `[email protected]`. A shorter `reviewer@desk` or `reviewer` still works when only one network has it.
+
+Prefer the command line? `codync-host network` does the same: `create [name] --network home`, `invite`, `join '<invite>' [name]`, `peers`, `promote <computer>`, `remove <computer> [--cascade]`, `recover <code>` and `leave`, each with `--network <name>` when the computer is in several. On a Mac where you installed the app from the disk image rather than with Homebrew, `codync-host` is inside the app: `/Applications/Codync.app/Contents/Resources/codync-host`.
Once your computers are in the network, nothing else changes for your bots. A bot lists the bots on your other computers along with its own, as `name@computer` (for example `reviewer@desk`), and asks them the same way. The request runs in that bot's chat on its computer, with that computer's approvals, and the answer comes back to the sender. The rows in the chats name the bot and its computer, for example "Messaged Reviewer on desk".
- **Away computers:** a request to a computer that's asleep waits up to a day and goes out when it's back.
- **Limits:** besides the limits below, each computer accepts a burst of 5 messages between the same two bots, then one every 2 minutes, and refuses the same words twice within 10 minutes.
-- **Connector:** when you create or join, **When there's no direct path** picks how computers reach each other: **Public relays** (iroh's, meant for trying things out; the default), **Your own relay** (an `iroh-relay` you run) or **Private: direct only** (computers on the same network, Tailscale or a VPN). On the command line: `--connector public|private|https://your-relay`.
+- **Connector:** each network has its own. When you create or join, **When there's no direct path** picks how computers reach each other: **Public relays** (iroh's, meant for trying things out; the default), **Your own relay** (an `iroh-relay` you run) or **Private: direct only** (computers on the same network, Tailscale or a VPN). On the command line: `--connector public|private|https://your-relay`.
+
+### Choose who reaches your bots
+
+Each computer decides for itself who may message its bots; the senders can't get around it.
+
+- **Offered to the network**, in each bot's settings: turn it off and your other computers don't list that bot, and can't message it. On by default.
+- **Who may message bots here**, under each network on the desktop (or `w` in the terminal UI's network sheet): rules such as "Deny: any bot on server → any bot here" or "Allow: Lead on laptop → Reviewer". The first rule that matches decides, and without rules every computer in the network may message every bot. A refused bot is told why, and its request ends failed. Answers to this computer's own requests always get in. Phones show the rules but don't change them.
+
+### Agents that aren't Codync bots
+
+A Claude Code, Codex or other agent session on the same computer can list your bots (here and on your other computers), message one and read its reply, through an MCP server the host runs:
+
+```sh
+claude mcp add codync -- codync-host mcp network --name "Claude Code"
+```
+
+The bot's chat shows "Message from Claude Code (this computer)". Bots can take minutes, so the session collects answers with `read_replies` when it's ready, rather than waiting.
## Manage the team