Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
fix: review fixes for rules, several networks and cloud assistants
leepokaicc1e5a366e03
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.ktindex 6ad0a3c3..4d0bbfca 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@@ -45,15 +45,16 @@ import com.kyant.shapes.Capsule})CardForm {// 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 (network in view.networks) {+ CardSection(network.name) {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) }}}+ // The note that changes happen at a computer closes the networks, after the last one's rules.+ if (view.networks.isNotEmpty()) CardSection(footer = "Changes are made on a computer: in Codync's settings there, or with codync-host network.") {}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") }}@@ -65,9 +66,7 @@ private const val RULES_FOOTER = "The first rule that matches decides. Without r/** 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)+ Text(network.describe(rule, translator()), style = Type.body, color = Palette.text)}/** One computer: its name and role, whether it answers, and the bots it offers. */diff --git a/apps/android/app/src/main/kotlin/com/codync/android/WidgetCards.kt b/apps/android/app/src/main/kotlin/com/codync/android/WidgetCards.ktindex 164d9a42..3733138c 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/WidgetCards.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/WidgetCards.kt@@ -75,9 +75,7 @@ internal fun UsageWindow.resetsShort(now: Long = System.currentTimeMillis()): St/** "resets 3h 20m" / "resets in 2d 6h". Compact times become "3小时20分后重置". */@Composable internal fun resetLine(raw: String): String {val language = LocalAppLanguage.current.resolved(LocalSystemTag.current)- val systemChinese = LocalSystemChinese.current- val phrases = LocalPhrases.current- return spokenReset(raw, language.usesChinese(systemChinese)) { translate(it, language, systemChinese, phrases) }+ return spokenReset(raw, language.usesChinese(LocalSystemChinese.current), translator())}internal fun spokenReset(raw: String, chinese: Boolean, tr: (String) -> String): String {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.ktindex b62f0105..c0b2cb61 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@@ -54,7 +54,8 @@ data class NetworkInfo(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}"+ // An access this app doesn't know reads as deny, never wider than it is.+ val access = if (rule.access == "allow") "Allow: {from} → {to}" else "Deny: {from} → {to}"return tr(access).replace("{from}", from).replace("{to}", to)}@@ -86,4 +87,4 @@ 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")+data class NetworkRule(val fromComputer: String = "*", val fromAgent: String = "*", val toAgent: String = "*", val access: String = "deny")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.ktindex e248e407..e3e12e6c 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@@ -45,6 +45,8 @@ class NetworkTest {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 })+ // Nor does an access this app doesn't know.+ assertEquals("Deny: any bot on any computer → any bot here", home.describe(NetworkRule(access = "ask")) { it })}@Test fun `a computer in no network shows only when cloud assistants can reach it and are on`() {diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/L10n.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/L10n.ktindex 23698612..8ae7a61d 100644--- a/apps/android/design/src/main/kotlin/com/codync/android/design/L10n.kt+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/L10n.kt@@ -138,5 +138,11 @@ val LocalSystemChinese = staticCompositionLocalOf { false }val LocalPhrases = staticCompositionLocalOf { emptyMap<String, String>() }val LocalSetAppLanguage = staticCompositionLocalOf<(AppLanguage) -> Unit> { {} }-@Composable fun tr(text: String): String =- translate(text, LocalAppLanguage.current.resolved(LocalSystemTag.current), LocalSystemChinese.current, LocalPhrases.current)+@Composable fun tr(text: String): String = translator()(text)++/** [tr] as a function, for code that translates outside composition (a template filled in later). */+@Composable fun translator(): (String) -> String {+ val language = LocalAppLanguage.current.resolved(LocalSystemTag.current)+ val (chinese, phrases) = LocalSystemChinese.current to LocalPhrases.current+ return { translate(it, language, chinese, phrases) }+}diff --git a/apps/desktop/src/renderer/lib/bot-template.test.ts b/apps/desktop/src/renderer/lib/bot-template.test.tsnew file mode 100644index 00000000..015eef7b--- /dev/null+++ b/apps/desktop/src/renderer/lib/bot-template.test.ts@@ -0,0 +1,14 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { encodeTemplate } from './bot-template.ts'++test('a template keeps the setup, not the bot identity, fallbacks or who reaches it', () => {+ const encoded = encodeTemplate({+ id: 'b1', name: 'Reviewer', description: '', avatarColor: 'red', avatarShape: 'blob', backend: 'claude',+ cwd: '/src', permission: 'ask', model: null, pinned: true, fallbacks: [], offeredToNetwork: false, reachableByAssistants: false,+ })+ assert.equal(+ encoded,+ '{\n "avatarColor" : "red",\n "avatarShape" : "blob",\n "backend" : "claude",\n "cwd" : "/src",\n "description" : "",\n "name" : "Reviewer",\n "permission" : "ask"\n}',+ )+})diff --git a/apps/desktop/src/renderer/lib/bot-template.ts b/apps/desktop/src/renderer/lib/bot-template.tsnew file mode 100644index 00000000..2be11ba1--- /dev/null+++ b/apps/desktop/src/renderer/lib/bot-template.ts@@ -0,0 +1,18 @@+import type { BotDraft } from '@shared/models'++/**+ * Swift's `JSONEncoder` with `.prettyPrinted, .sortedKeys, .withoutEscapingSlashes`; nil fields are left out, and so+ * are fallbacks (they depend on the agents a computer has) and who reaches the bot (that belongs to its computer).+ */+export function encodeTemplate(draft: BotDraft): string {+ const {+ id: _id, pinned: _pinned, hidden: _hidden, fallbacks: _fallbacks, selfFallbacks: _selfFallbacks,+ offeredToNetwork: _offered, reachableByAssistants: _reachable, ...rest+ } = draft+ const sorted = Object.fromEntries(+ Object.entries(rest)+ .filter(([, v]) => v !== null && v !== undefined)+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),+ )+ return JSON.stringify(sorted, null, 2).replace(/^(\s*"(?:[^"\\]|\\.)*"): /gm, '$1 : ')+}diff --git a/apps/desktop/src/renderer/store/network.ts b/apps/desktop/src/renderer/store/network.tsindex 9f79fa51..39a2c52a 100644--- a/apps/desktop/src/renderer/store/network.ts+++ b/apps/desktop/src/renderer/store/network.ts@@ -38,13 +38,12 @@ export const network = {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: async (store: BotStore, networkName: string, name: string, connector: string) => {- const made = await call<{ recoveryCode: string; computer: string; network: string }>(+ // `name` is the one the host gave it, maybe numbered (`home-2`).+ const made = await call<{ recoveryCode: string; computer: string; name: 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 })+ store.setRecoveryCode({ code: made.recoveryCode, network: made.name, 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)),diff --git a/apps/desktop/src/renderer/views/bots/BotTemplateView.tsx b/apps/desktop/src/renderer/views/bots/BotTemplateView.tsxindex ec68e8a8..f9c0ede0 100644--- a/apps/desktop/src/renderer/views/bots/BotTemplateView.tsx+++ b/apps/desktop/src/renderer/views/bots/BotTemplateView.tsx@@ -4,23 +4,10 @@ import { Icon } from '../../components/Icon'import { ModalHeader } from '../../components/Overlay'import { HStack, VStack } from '../../components/Stack'import { Text } from '../../components/Text'+import { encodeTemplate } from '../../lib/bot-template'import { useTr } from '../../lib/use-language'import './bots.css'-/**- * Swift's `JSONEncoder` with `.prettyPrinted, .sortedKeys, .withoutEscapingSlashes`; nil fields are left out, and so- * are fallbacks (they depend on the agents a computer has).- */-export function encodeTemplate(draft: BotDraft): string {- const { id: _id, pinned: _pinned, hidden: _hidden, fallbacks: _fallbacks, selfFallbacks: _selfFallbacks, ...rest } = draft- const sorted = Object.fromEntries(- Object.entries(rest)- .filter(([, v]) => v !== null && v !== undefined)- .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),- )- return JSON.stringify(sorted, null, 2).replace(/^(\s*"(?:[^"\\]|\\.)*"): /gm, '$1 : ')-}-/** A portable settings snapshot, with no conversation identity or runtime state. */export function BotTemplateView({ draft }: { draft: BotDraft }) {const tr = useTr()diff --git a/apps/desktop/src/renderer/views/settings/NetworkSection.tsx b/apps/desktop/src/renderer/views/settings/NetworkSection.tsxindex b46d7fcc..1a90a8d1 100644--- a/apps/desktop/src/renderer/views/settings/NetworkSection.tsx+++ b/apps/desktop/src/renderer/views/settings/NetworkSection.tsx@@ -53,6 +53,8 @@ export function NetworkSection({ store }: { store: BotStore }) {const invite = sheetFor('invite')const recover = sheetFor('recover')const rule = sheetFor('rule')+ const removing = open?.kind === 'remove' ? open : null+ const leaving = open?.kind === 'leave' ? open.net : nullreturn (<VStack gap={14}>@@ -103,27 +105,27 @@ export function NetworkSection({ store }: { store: BotStore }) {{store.recoveryCode ? <RecoveryCodeSheet recovery={store.recoveryCode} done={() => store.setRecoveryCode(null)} /> : null}</Sheet><Dialog- open={open?.kind === 'remove'}- title={tr('Remove {name} from the network?').replaceAll('{name}', open?.kind === 'remove' ? open.computer.name : '')}+ open={removing !== null}+ title={tr('Remove {name} from the network?').replaceAll('{name}', removing?.computer.name ?? '')}message={tr("It can't come back with its current key. For a stolen computer, also remove the computers it invited.")}actions={- open?.kind === 'remove'+ removing? [- { 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)) },+ { title: 'Remove', destructive: true, action: () => run(() => network.remove(store, removing.net.id, removing.computer.name, false)) },+ { title: 'Remove with its invites', destructive: true, action: () => run(() => network.remove(store, removing.net.id, removing.computer.name, true)) },]: []}onClose={close}/><Dialog- open={open?.kind === 'leave'}- title={tr('Leave {network}?').replaceAll('{network}', open?.kind === 'leave' ? open.net.name : '')}+ open={leaving !== null}+ title={tr('Leave {network}?').replaceAll('{network}', leaving?.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 : '',+ leaving?.name ?? '',)}- actions={open?.kind === 'leave' ? [{ title: 'Leave', destructive: true, action: () => run(() => network.leave(store, open.net.id)) }] : []}+ actions={leaving ? [{ title: 'Leave', destructive: true, action: () => run(() => network.leave(store, leaving.id)) }] : []}onClose={close}/></VStack>diff --git a/apps/desktop/src/renderer/views/settings/NetworkSheets.tsx b/apps/desktop/src/renderer/views/settings/NetworkSheets.tsxindex 28cdc631..d40494a6 100644--- a/apps/desktop/src/renderer/views/settings/NetworkSheets.tsx+++ b/apps/desktop/src/renderer/views/settings/NetworkSheets.tsx@@ -10,9 +10,9 @@ import type { BotStore } from '../../store/bot-store'import { network } from '../../store/network'import { errorText } from './parts'-export const NETWORK_ICON = 'point.3.connected.trianglepath.dotted'+const NETWORK_ICON = 'point.3.connected.trianglepath.dotted'-export function Field({ label, value, set, placeholder, mono = false }: { label: string; value: string; set: (v: string) => void; placeholder: string; mono?: boolean }) {+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">diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/BotTemplateView.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/BotTemplateView.swiftindex 99f58e8c..a296436e 100644--- a/apps/ios/Kit/Sources/CodyncUI/Bots/BotTemplateView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/BotTemplateView.swift@@ -15,6 +15,9 @@ struct BotTemplateView: View {template.hidden = niltemplate.fallbacks = niltemplate.selfFallbacks = nil+ // Who reaches a bot belongs to its computer, not its setup.+ template.offeredToNetwork = nil+ template.reachableByAssistants = nilself.template = templatelet encoder = JSONEncoder()encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]diff --git a/apps/ios/Kit/Sources/CodyncUI/Controls.swift b/apps/ios/Kit/Sources/CodyncUI/Controls.swiftindex 3fdd1e7b..eb87164c 100644--- a/apps/ios/Kit/Sources/CodyncUI/Controls.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Controls.swift@@ -463,14 +463,17 @@ public struct CardSection<Content: View, Accessory: View>: View {}.padding(.leading, 2)}- VStack(alignment: .leading, spacing: 0) {- _VariadicView.Tree(HairlineRows()) { content }- }- .frame(maxWidth: .infinity, alignment: .leading)- .background(cardStyle == .filled ? Palette.surface : .clear, in: RoundedRectangle(cornerRadius: 16, style: .continuous))- .overlay {- if cardStyle == .outlined {- RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(Palette.border)+ // No rows (`{}`): a footer-only note, without an empty card.+ if Content.self != EmptyView.self {+ VStack(alignment: .leading, spacing: 0) {+ _VariadicView.Tree(HairlineRows()) { content }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(cardStyle == .filled ? Palette.surface : .clear, in: RoundedRectangle(cornerRadius: 16, style: .continuous))+ .overlay {+ if cardStyle == .outlined {+ RoundedRectangle(cornerRadius: 14, style: .continuous).strokeBorder(Palette.border)+ }}}if let footer {diff --git a/apps/ios/Kit/Sources/CodyncUI/NetworkSheet.swift b/apps/ios/Kit/Sources/CodyncUI/NetworkSheet.swiftindex 2ab6d97b..b43b1078 100644--- a/apps/ios/Kit/Sources/CodyncUI/NetworkSheet.swift+++ b/apps/ios/Kit/Sources/CodyncUI/NetworkSheet.swift@@ -28,9 +28,8 @@ public struct NetworkSheet: View {CardForm {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) {+ // One section per network: its computers, then who may message the bots here.+ CardSection(network.name) {ForEach(network.computers ?? []) { NetworkComputerRow(computer: $0) }}if let rules = network.rules, !rules.isEmpty {@@ -43,6 +42,10 @@ public struct NetworkSheet: View {}}}+ // The note that changes happen at a computer closes the networks, after the last one's rules.+ if !networks.isEmpty {+ CardSection(footer: "Changes are made on a computer: in Codync's settings there, or with codync-host network.") {}+ }if store.network?.assistantsAvailable == true {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.") {ValueRow("Cloud assistants", value: store.network?.assistants == true ? "On" : "Off")diff --git a/docs/architecture/file-structure.md b/docs/architecture/file-structure.mdindex be4f5b42..1c59584a 100644--- a/docs/architecture/file-structure.md+++ b/docs/architecture/file-structure.md@@ -94,7 +94,7 @@ Codync/| Group room turns / bot-to-bot requests | `host/src/chat/group.rs` / `team.rs` || Voice calls (the call, the voice's instructions and tools, transcripts, call lines) | `host/src/chat/calls/` (`mod.rs`, `context.rs`, `project.rs` the git state, `tools.rs`, `announce.rs` what the voice hears while the call lasts, `speech.rs` text as a voice says it); the user's messages it relays go through `host/src/chat/messages.rs` like typed ones; clients' `CallLink` (iPhone `CodyncUI/Call/CallLink.swift`, desktop `views/call/call-link.ts`, Android `core/Calls.kt` + `HostCallLink.kt`) and call rows (`CallRows`); the call on the iPhone's Lock Screen (`CodyncUI/Call/CallActivity.swift`, the Live Activity) and Android's call notification (`VoiceService.kt`) || Team management (bots creating and changing bots) | `host/src/chat/manage.rs`, its approval card (`Cmd::Approve`) in `agent/bot/updates.rs` |-| codync-network (your computers' network) | `host/crates/network` (the crate: roster, letters, reach, budgets), `host/src/network/` (the host's node, its bots' address names, `networkView` and the `network` event), `host/src/network_cli.rs`; across-computer bot requests in `host/src/chat/team/remote.rs`; desktop `apps/desktop/src/renderer/views/settings/NetworkSection.tsx`, `NetworkSheets.tsx` (+ `store/network.ts`, `lib/network-copy.ts`, `src/shared/network.ts`); iPhone `apps/ios/Kit/Sources/CodyncUI/NetworkSheet.swift` (+ `CodyncKit/Models/Network.swift`); Android `NetworkSheet.kt`, `AppStoreNetwork.kt` (+ `core/Network.kt`); terminal `host/src/tui/manage/network.rs`, `view/network.rs` |+| codync-network (your computers' network) | `host/crates/network` (the crate: roster, letters, reach, budgets, `rules.rs`; `node/endpoint.rs` for where a computer is), `host/src/network/` (one node per network in `mod.rs`, the saved networks in `saved.rs`, its bots' address names in `handles.rs`, the `network*` methods, `networkView` and the `network` event in `api.rs`), `host/src/network_cli.rs`; across-computer bot requests in `host/src/chat/team/remote.rs`; desktop `apps/desktop/src/renderer/views/settings/NetworkSection.tsx`, `NetworkCard.tsx`, `NetworkSheets.tsx`, `RuleSheet.tsx` and the bot editor's `views/bots/NetworkSwitches.tsx` (+ `store/network.ts`, `lib/network-copy.ts`, `src/shared/network.ts`); iPhone `apps/ios/Kit/Sources/CodyncUI/NetworkSheet.swift` (+ `CodyncKit/Models/Network.swift`); Android `NetworkSheet.kt`, `AppStoreNetwork.kt` (+ `core/Network.kt`); terminal `host/src/tui/manage/network.rs`, `network_setup.rs`, `network_rules.rs` and `view/network.rs`, `view/network_rules.rs` || Prompt snapshots and memory | `host/src/chat/context.rs`, `memory/` (`api.rs` the apps' read-only view, `tools.rs` and `file_tools.rs` the MCP tools, `files.rs` the folders and scan, `turns.rs` which bot's turn a found change is credited to, `file_api.rs`, `dream.rs`, `import.rs`); the rules in `host/crates/memory` (`codync-mem`: files and facts in `files/`, dreaming in `dream/`, tombstones in `store.rs`, the old entries in `legacy.rs`); harnesses' own memory turned off in `host/src/agent/own_memory.rs` || Identity, encryption and direct channel | `host/src/remote/identity.rs`, `crypto.rs`, `channel.rs` || Host cloud state and relay connection | `host/src/remote/cloud.rs`, `cloud_url.rs`, `relay.rs` |diff --git a/docs/features/cloud-assistants.md b/docs/features/cloud-assistants.mdindex 72192500..198bc32a 100644--- a/docs/features/cloud-assistants.md+++ b/docs/features/cloud-assistants.md@@ -30,12 +30,16 @@ ChatGPT / Claude ──MCP over HTTPS──▶ mcp.codync.dev (cloud Worker)nothing can wake a hosted assistant.- **Host** (`host/src/chat/team/assistant.rs`): the assistant messages bots like a bot does(`Back::Assistant`): the bot's chat shows "Message from Cloud assistant" and the reply is kept in memory (the- newest 50 requests, at most 16 running) until read. `list_bots` also lists the bots the user's other+ newest 50 requests, at most 16 running) until read. A bot with **Reachable by cloud assistants** off+ (`reachableByAssistants`) is left out of `list_bots` and refused by `message_bot`; agents on this computer using+ `codync-host mcp network` aren't held to it. `list_bots` also lists the bots the user's othercomputers in this one's network offer (`reviewer@laptop`), and `message_bot` sends those a letter from`cloud-assistant@<this computer>` (`Node::set_senders`: it may send but isn't offered, so nothing elsewhere can- ask it). That computer's own rules decide whether it takes it, like any sender's; the outcome comes back into the- same replies, and a refusal ends the request as failed with that computer's reason. The receiving bot's chat- shows "Message from Cloud assistant on desk".+ ask it). That computer decides whether it takes it with its own rules, its Cloud assistants switch and the bot's+ `reachableByAssistants` (`remote::take`); the outcome comes back into the same replies, and a refusal ends the+ request as failed with that computer's reason. The receiving bot's chat shows "Message from Cloud assistant on+ desk". The relay session answers each call in a task of its own, so a listing that waits for the other+ computers doesn't hold up the phones on the same connection.## Who can get indiff --git a/docs/features/codync-network.md b/docs/features/codync-network.mdindex 4ef18628..98453cb4 100644--- a/docs/features/codync-network.md+++ b/docs/features/codync-network.md@@ -135,7 +135,7 @@ that was off learns of a removal.`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 Codesessions (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.+ `~/.codync-network` (the host's are `~/.codync/network` and `network-…`, one per network), so beside a host it is a computer of its own.## Who reaches this computer's bots@@ -144,17 +144,22 @@ and nothing new crosses the wire beyond a refusal's reason.- **Offered to the network**, per bot (`offeredToNetwork` on the bot, on by default): a bot that's off isn'tpublished (`network::publish` filters it), so other computers don't list it, and a letter to it is refused like- one to an unknown agent. It's a bot setting, so any paired device may change it.+ one to an unknown agent. It still messages bots elsewhere and hears back (the node sends as it without offering+ it, `Node::set_senders`). It's a bot setting, so any paired device may change it.- **Reachable by cloud assistants**, per bot (`reachableByAssistants`, on by default): `list_bots` from the cloud- assistant leaves it out and `message_bot` refuses it (`chat/team/assistant.rs`).-- **Rules**, per computer: an ordered list of `{fromComputer, fromAgent, toAgent, access}` (`allow`/`deny`, `*`+ assistant leaves it out and `message_bot` refuses it (`chat/team/assistant.rs`). A letter from the cloud+ assistant through another computer (`cloud-assistant@desk`) meets the same checks here, and this computer's own+ Cloud assistants switch: off, it refuses them all (`remote::take`).+- **Rules**, per network: an ordered list of `{fromComputer, fromAgent, toAgent, access}` (`allow`/`deny`, `*`for any). The first rule that matches decides; with none, everyone may write (`codync_network::rules`). The cratechecks them in `node/inbound.rs` before it takes a letter, so the standalone daemon has them too (`rules.json`beside `agents.json`, `codync-network rules allow|deny <agent@computer> <agent> [--first]`, `rules remove <n>`).A refused letter's sender gets the reason as its tool error, for example "desk refused it: reviewer doesn't take- messages from lead@laptop", and its exchange notice ends failed. Answers to this computer's own letters always- pass (the crate keeps the ids it sent), so a rule added while a request runs doesn't strand it. The host keeps- its rules in kv `network_rules`, applies them when the node starts, and changes them with `setNetworkRules`+ messages from lead@laptop", and its exchange notice ends failed. An answer to one of this computer's own+ requests passes (the crate keeps each request's id, the computer it went to and the agent that sent it), so a+ rule added while a request runs doesn't strand it: only from that computer, only to that agent, and only until+ the answer that says how it ended (`meta`). The host keeps each network's rules with it in kv `networks`+ (`network/saved.rs`), applies them when its node starts, and changes them with `setNetworkRules {network, rules}`(loopback only, like membership); `networkView` shows them, so phones list them read-only.- The master switches stay at the computer: being in a network, and cloud assistants on or off.@@ -172,13 +177,15 @@ Planned in order, with what each step touches: [what's left](../plans/codync-net## Code and verification-- `host/crates/network`: the crate (`node/`, `roster.rs`, `guard.rs`, `reach.rs`, `wire.rs`); `cargo test -p codync-network`+- `host/crates/network`: the crate (`node/`, `roster.rs`, `rules.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 nodes (one per network, `mod.rs`), the saved networks (`saved.rs`), published botsand 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`.+- Clients: desktop `apps/desktop/src/renderer/views/settings/NetworkSection.tsx` (+ `NetworkCard.tsx`,+ `NetworkSheets.tsx`, `RuleSheet.tsx`, `store/network.ts`) and the bot editor's `views/bots/NetworkSwitches.tsx`;+ terminal `host/src/tui/manage/network.rs` (+ `network_setup.rs`, `network_rules.rs`) and `view/network.rs`+ (+ `view/network_rules.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`;`assistant.rs`: the cloud assistant and agents that aren't bots (`codync-host mcp network`, `agentCall`).- `host/src/network_cli.rs`: `codync-host network`.diff --git a/docs/reference/analytics-events.md b/docs/reference/analytics-events.mdindex 65a5a8b9..b44997d3 100644--- a/docs/reference/analytics-events.md+++ b/docs/reference/analytics-events.md@@ -99,7 +99,7 @@ host answers and sends it once the host is up.| `setting_changed` | host, iOS, Android | A setting is switched | `setting` (host: `remote_access`/`remote_access_url` (`on`: a relay address is saved, never the address)/`approval` (`on`: approved without the code)/`automatic_updates`/`remote_screen`/`cloud_assistants`; phones: `push`/`live_activities`), `on` || `host_update_installed` | host | `installHostUpdate` | — || `network_joined` | host | `networkCreate` / `networkJoin`: the computer is in a network of the user's computers | `via` (`create`/`invite`), never a name, invite or connector address |-| `network_changed` | host | `networkInvite` / `networkPromote` / `networkRemove` / `networkRecover` | `action` (`invite`/`promote`/`remove`/`recover`), never a computer's name, the invite or the recovery code |+| `network_changed` | host | `networkInvite` / `networkPromote` / `networkRemove` / `networkRecover` / `setNetworkRules` / `networkLeave` | `action` (`invite`/`promote`/`remove`/`recover`/`rules`/`leave`), never a computer's name, the invite, the recovery code or a rule |## Screensdiff --git a/docs/reference/remote-relay.md b/docs/reference/remote-relay.mdindex 44aba76a..27543615 100644--- a/docs/reference/remote-relay.md+++ b/docs/reference/remote-relay.md@@ -467,7 +467,7 @@ Close code 總表:`1000` 正常、`1011` 內部錯誤/逾時、`4001 unautho- **登入**:Clerk 是 authorization server,Worker 只是 protected resource。未帶有效 token → `401`,`WWW-Authenticate: Bearer resource_metadata="<origin>/.well-known/oauth-protected-resource/mcp", scope="profile email"`;metadata 指向 Clerk issuer(`/.well-known/oauth-authorization-server` 也代轉 Clerk 的,給舊 client)。Client 以 CIMD 註冊(DCR 關閉)。Token 必須是 Clerk 發的 OAuth access token(`at+jwt`,或 opaque 時向 Clerk 驗),`aud` 必須等於 `<origin>/mcp`;App 的 session token 不算。`ASSISTANT_LIMITER`:每帳號每分鐘 120 次。- **路由**:Worker 只把呼叫送到 token 帳號擁有、`active` 的 computer。`list_computers` 由 Worker 從 D1 回答;其餘工具:指定 `computer`(名稱或 id)→ 該台;未指定時帳號只有一台、或只有一台在線 → 該台;`list_bots`/`read_replies` 在多台在線時每台都問並合併成 `{computers:[{computer, …}]}`;`message_bot` 則要求指定。- **DO**:`POST /internal/assistant {user, tool, args}` → host 不在線 `503 {"ok":false,"code":"offline"}`;否則送 `assistant.call`,在 request 存活期間等同 `id` 的 `assistant.result`,最多 10 秒(逾時 `{"ok":false,"code":"timeout"}`,舊 host 會忽略這個訊息)。host 斷線時等待中的呼叫一律 `offline`。只在 request 存活時佔用 DO,不排隊、不存任何內容。-- **Host**(`chat::team::assistant`):預設關閉,`setAssistants`(loopback only:桌面 app 與 TUI 的 Cloud assistants 開關,或 `codync-host cloud --assistants on|off`)才開;`user` 必須等於 host 的 owner(`/v1/host/state`);private relay 上不處理。`message_bot` 走一般 bot request(`Back::Assistant`),回覆留在 host 記憶體給 `read_replies`(最新 50 則,同時最多 16 則執行中,重啟即忘)。+- **Host**(`chat::team::assistant`):預設關閉,`setAssistants`(loopback only:桌面 app 與 TUI 的 Cloud assistants 開關,或 `codync-host cloud --assistants on|off`)才開;`user` 必須等於 host 的 owner(`/v1/host/state`);private relay 上不處理。`message_bot` 走一般 bot request(`Back::Assistant`),回覆留在 host 記憶體給 `read_replies`(最新 50 則,同時最多 16 則執行中,重啟即忘)。`reachableByAssistants` 關掉的 bot 不列出、不收。`list_bots` 也列同一 network 裡其他電腦提供的 bot(`reviewer@laptop`);對它們的 `message_bot` 是一封由 `cloud-assistant@<這台>` 寄出的 codync-network 信,結果回到同一份 replies。收信的電腦自己再檢查:它的 Cloud assistants 開關、該 bot 的 `reachableByAssistants` 與 network rules。Host 在 relay session 外另起 task 回答 `assistant.call`(第一次列出時可能要等其他電腦最多 5 秒),不會卡住同一條連線上的裝置訊息。- **信任邊界**:和 §7.8 一樣,雲端以 HTTPS 解開並看得到這些呼叫與回覆的明文,不是 §6 的端對端加密。因此要電腦本機同意(開關)才放行,雲端無法自行替電腦打開;App 與文件都需明講。---diff --git a/host/crates/network/README.md b/host/crates/network/README.mdindex 6a2a3346..0a49e112 100644--- a/host/crates/network/README.md+++ b/host/crates/network/README.md@@ -45,6 +45,12 @@ standalone crate, and it reaches Claude Code and Codex sessions too.minutes are refused. A sender's retry of a letter already taken is acknowledged, not delivered again.- **Letters wait.** A letter for a computer that is asleep waits in the sender's outbox for up to a day and goesout when that computer answers again.+- **The receiver decides who writes.** Each computer keeps ordered rules of who on the others may write to which of+ its agents (`deny *@laptop → *`), the first match deciding; with none, every member may. The answer to a request+ this computer sent still gets in, from the computer it asked and to the agent that asked, so a rule added+ meanwhile doesn't strand it.+- **A computer that moves says so.** When its addresses change (a laptop on another Wi-Fi), it signs where it is+ now into the roster and tells the others, so they find it without a restart.## Layers@@ -56,6 +62,7 @@ New ways of working together don't change the layers below them:| Letters (`Letter`, `Message`) | text from agent to agent, `wake` or notice; `reply_to` links letters, `meta` carries an app's own structure untouched || Reach (`Reach`) | how a letter gets into the agent: the app, Claude Code, Codex || Budgets (`guard`) | chain length, bursts, repeats |+| Rules (`rules`) | who on the other computers may write to which agents here |Requests and replies, rooms or shared task boards are patterns of letters, built by the app above the network.@@ -84,7 +91,7 @@ It builds iroh on rustls with ring. An app that already uses rustls with aws-lc-aren't built in together (rustls then can't pick a provider by itself):```toml-codync-network = { version = "0.1", default-features = false, features = ["tls-aws-lc-rs"] }+codync-network = { version = "0.2", default-features = false, features = ["tls-aws-lc-rs"] }```## Try it@@ -105,6 +112,10 @@ codync-network send terminal@desk hello # delivered to terminal@deskcodync-network send terminal@desk --notice "tests are green"codync-network promote laptop # the owner makes laptop an admincodync-network remove laptop [--cascade] # out for good (--cascade: and whom it admitted)+codync-network rules deny '*@laptop' reviewer # laptop's agents can't write to reviewer here+codync-network rules allow lead@laptop reviewer --first # except lead (the first match decides)+codync-network rules # the rules, numbered+codync-network rules remove 2 # take out rule 2```To put a Claude Code session or a Codex thread on the network, run this in it (or have the agent run it):@@ -119,8 +130,9 @@ skips permission prompts holds messages from outside it for your approval, unlesis `accept`.`--connector public|private|https://your-relay` picks the connector (default `public`), `--dir` the state folder-(default `~/.codync-network`: the key in `secret.key`, the roster in `network.json`, the agents in `agents.json`).-A Codync host keeps its own node in `~/.codync/network`; never point two nodes at one folder.+(default `~/.codync-network`: the key in `secret.key`, the roster in `network.json`, the agents in `agents.json`,+the rules in `rules.json`). A Codync host keeps a node per network in `~/.codync` (`network`, `network-…`); never+point two nodes at one folder.## Use@@ -143,6 +155,13 @@ while let Some(message) = inbox.recv().await {`node.changes()` ticks whenever `node.directory()` would show something new (a computer joins or leaves, a role,name or presence changes, another computer offers different agents), for an app that shows the network live.+- `node.set_rules(rules)` sets who may write to this computer's agents (`Rule::new(Access::Deny, "*@laptop", "*")`).+- `node.set_senders(names)` lets the app send as agents it doesn't offer (a hosted assistant that asks agents+ elsewhere but can't be asked itself); the answers to its letters still come back.+- `node.set_network_name(Some("home"))` names the network in the invites this computer makes, and+ `read_invite(invite)` reads the network's id and name before joining, for an app in several networks: one+ `Node`, with its own folder, per network.+## Build```shdiff --git a/host/crates/network/src/lib.rs b/host/crates/network/src/lib.rsindex af7df218..f66a9f0e 100644--- a/host/crates/network/src/lib.rs+++ b/host/crates/network/src/lib.rs@@ -26,9 +26,9 @@ pub mod rules;mod types;mod wire;-pub use node::{INVITE_FOR, InviteInfo, Node, read_invite};+pub use node::{INVITE_FOR, Node};pub use reach::Reach;pub use roster::Role;pub use rules::{Access, Rule};pub use types::{Address, Connector, Letter, Message, Peer, Sent};-pub use wire::{Agent, MAX_BODY};+pub use wire::{Agent, InviteInfo, MAX_BODY, read_invite};diff --git a/host/crates/network/src/node/endpoint.rs b/host/crates/network/src/node/endpoint.rsnew file mode 100644index 00000000..93def8a5--- /dev/null+++ b/host/crates/network/src/node/endpoint.rs@@ -0,0 +1,143 @@+//! Where this computer is: its key, its iroh endpoint, and the location it signs into the roster,+//! again whenever its addresses change.++use super::{Inner, locked};+use crate::roster::Change;+use crate::types::Connector;+use crate::wire;+use anyhow::{Context, Result, anyhow};+use iroh::endpoint::presets;+use iroh::{Endpoint, EndpointAddr, RelayMode, RelayUrl, SecretKey, Watcher};+use std::path::Path;+use std::sync::Weak;+use std::time::{Duration, Instant};++const KEY_FILE: &str = "secret.key";+/// How long addresses get to settle after a change before this computer signs where it is.+const ADDR_SETTLE: Duration = Duration::from_secs(2);++impl Inner {+ /// Writes where this computer is into the roster when it moved. Returns whether it did.+ pub(super) fn locate(&self, addr: EndpointAddr) -> Result<bool> {+ let mut guard = locked(&self.roster);+ let Some(roster) = guard.as_mut() else { return Ok(false) };+ if roster.members().get(&self.me()).is_none_or(|m| m.addr == addr) {+ return Ok(false);+ }+ roster.sign(self.endpoint.secret_key(), wire::now_ms(), Change::Locate { addr })?;+ self.save(roster)?;+ Ok(true)+ }+}++/// Signs where this computer is again whenever its addresses change (a laptop that moved to+/// another network) and tells the others, so they find it without a restart: with the `private`+/// connector, nothing else would. The roster keeps only each computer's newest location.+pub(super) async fn follow_addr(inner: Weak<Inner>, mut addr: impl Watcher<Value = EndpointAddr>) {+ while addr.updated().await.is_ok() {+ // Addresses change in bursts (an interface comes up, then the relay answers): sign once.+ tokio::time::sleep(ADDR_SETTLE).await;+ let Some(inner) = inner.upgrade() else { return };+ match inner.locate(addr.get()) {+ Ok(true) => {+ tracing::info!("this computer moved; telling the others");+ inner.hello_all();+ }+ Ok(false) => {}+ Err(e) => tracing::warn!(error = format!("{e:#}"), "couldn't sign where this computer is"),+ }+ }+}++pub(super) async fn bind(key: SecretKey, connector: &Connector) -> Result<Endpoint> {+ let builder = match connector {+ Connector::Public => Endpoint::builder(presets::N0),+ Connector::Relay(url) => {+ let url: RelayUrl = url.parse().context("not a relay URL")?;+ Endpoint::builder(presets::Minimal).relay_mode(RelayMode::custom([url]))+ }+ Connector::Private => Endpoint::builder(presets::Minimal).relay_mode(RelayMode::Disabled),+ };+ Ok(builder.secret_key(key).bind().await?)+}++/// Waits briefly until the endpoint knows its own addresses, so invites and the roster carry them.+pub(super) async fn settle(endpoint: &Endpoint, connector: &Connector) {+ if *connector != Connector::Private {+ let _ = tokio::time::timeout(Duration::from_secs(5), endpoint.online()).await;+ }+ let until = Instant::now() + Duration::from_secs(3);+ while endpoint.addr().ip_addrs().next().is_none() && Instant::now() < until {+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+}++pub(super) fn load_key(dir: &Path) -> Result<SecretKey> {+ let path = dir.join(KEY_FILE);+ match std::fs::read(&path) {+ Ok(bytes) => {+ let bytes: [u8; 32] = bytes.try_into().map_err(|_| anyhow!("{} is damaged", path.display()))?;+ Ok(SecretKey::from_bytes(&bytes))+ }+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {+ let key = SecretKey::generate();+ write_private(&path, &key.to_bytes())?;+ Ok(key)+ }+ Err(e) => Err(e).context("couldn't read this computer's key"),+ }+}++fn write_private(path: &Path, bytes: &[u8]) -> Result<()> {+ #[cfg(unix)]+ {+ use std::io::Write;+ use std::os::unix::fs::OpenOptionsExt;+ let mut file = std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(path)?;+ file.write_all(bytes)?;+ }+ #[cfg(not(unix))]+ std::fs::write(path, bytes)?;+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::super::Node;+ use super::*;+ use std::path::PathBuf;+ use std::sync::Arc;++ fn temp_dir(name: &str) -> PathBuf {+ let dir = std::env::temp_dir().join(format!("codync-network-unit-{name}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ dir+ }++ #[tokio::test]+ async fn a_computer_that_moves_tells_the_others_without_a_restart() {+ let (desk_dir, laptop_dir) = (temp_dir("desk"), temp_dir("laptop"));+ let (desk, _) = Node::start(&desk_dir, &Connector::Private).await.expect("desk starts");+ desk.create("desk").expect("a network");+ let (laptop, _) = Node::start(&laptop_dir, &Connector::Private).await.expect("laptop starts");+ laptop.join(&desk.invite().expect("an invite"), "laptop").await.expect("joined");++ // The laptop moves: an address it didn't have before.+ let moved = laptop.inner.endpoint.addr().with_ip_addr("192.0.2.7:4242".parse().expect("an address"));+ let watched = n0_watcher::Watchable::new(laptop.inner.endpoint.addr());+ tokio::spawn(follow_addr(Arc::downgrade(&laptop.inner), watched.watch()));+ watched.set(moved.clone()).expect("watched");+ let desk_sees =+ || locked(&desk.inner.roster).as_ref().and_then(|r| r.members().get(&laptop.id()).map(|m| m.addr.clone()));+ tokio::time::timeout(Duration::from_secs(10), async {+ while desk_sees() != Some(moved.clone()) {+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ })+ .await+ .expect("the desk hears where the laptop is now");+ for dir in [desk_dir, laptop_dir] {+ let _ = std::fs::remove_dir_all(dir);+ }+ }+}diff --git a/host/crates/network/src/node/inbound.rs b/host/crates/network/src/node/inbound.rsindex 541ebad3..79cab63a 100644--- a/host/crates/network/src/node/inbound.rs+++ b/host/crates/network/src/node/inbound.rs@@ -1,6 +1,6 @@//! What this computer answers: joins, hellos and letters for its agents.-use super::{Inner, check_name, locked};+use super::{Inner, check_name, locked, remember};use crate::guard::digest;use crate::reach::Reach;use crate::roster::Change;@@ -89,12 +89,18 @@ impl Inner {if !self.ready.load(Ordering::Acquire) {return Response::Later { reason: "this computer is still starting".into() };}+ let key = format!("{peer}:{}", envelope.id);+ if locked(&self.taken).contains(&key) {+ // The sender didn't hear back the first time; it was already delivered.+ return Response::Stored;+ }// Without a network, only this computer's own agents write here.let roster = locked(&self.roster).clone();let name = |id: &EndpointId| roster.as_ref().map_or_else(|| "local".into(), |r| r.name(id));// This computer's rules, for letters from the others that don't answer one of its own.+ let answers = self.answers(peer, &envelope);if peer != self.me()- && !self.answers(peer, envelope.reply_to.as_deref())+ && !answers&& !rules::allows(&locked(&self.rules), &name(&peer), &envelope.from, &envelope.to){return refuse(format!("{} doesn't take messages from {}@{}", envelope.to, envelope.from, name(&peer)));@@ -107,11 +113,6 @@ impl Inner {None if envelope.reply_to.is_some() => Reach::App,None => return refuse(format!("{} has no agent called {}", name(&self.me()), envelope.to)),};- let key = format!("{peer}:{}", envelope.id);- if locked(&self.taken).contains(&key) {- // The sender didn't hear back the first time; it was already delivered.- return Response::Stored;- }let pair = format!("{peer}/{}>{}", envelope.from, envelope.to);let meta = envelope.meta.as_ref().map(ToString::to_string).unwrap_or_default();// Two answers to two different letters may well say the same thing ("Done.").@@ -120,14 +121,15 @@ impl Inner {return refuse(reason);}let (id, hops) = (envelope.id.clone(), envelope.hops);+ // An answer that says how the request ended (`meta`) is the last one past the rules.+ let ended = envelope.reply_to.clone().filter(|_| answers && envelope.meta.is_some());match self.hand_over(&reach, envelope.open(name(&peer))).await {Ok(()) => {self.heard(&id, hops);- let mut taken = locked(&self.taken);- if taken.len() >= TAKEN_MAX {- taken.pop_front();+ remember(&mut locked(&self.taken), key, TAKEN_MAX);+ if let Some(request) = ended {+ locked(&self.asked).retain(|(sent, to, _)| *sent != request || *to != peer);}- taken.push_back(key);Response::Stored}Err(e) => {diff --git a/host/crates/network/src/node/mod.rs b/host/crates/network/src/node/mod.rsindex 080f2787..b2f5a687 100644--- a/host/crates/network/src/node/mod.rs+++ b/host/crates/network/src/node/mod.rs@@ -1,6 +1,7 @@//! One computer on the network: its iroh endpoint, its roster and the agents it offers.mod directory;+mod endpoint;mod inbound;mod outbox;@@ -11,27 +12,24 @@ use crate::rules::{self, Rule};use crate::types::{Address, Connector, Letter, Message, Peer, Sent};use crate::wire::{self, ALPN, Agent, Request, Response, Ticket};use anyhow::{Context, Result, anyhow, bail};-use iroh::endpoint::{Connection, presets};+use iroh::endpoint::Connection;use iroh::protocol::Router;-use iroh::{Endpoint, EndpointAddr, EndpointId, RelayMode, RelayUrl, SecretKey, Watcher};+use iroh::{Endpoint, EndpointAddr, EndpointId};use std::collections::{HashMap, VecDeque};use std::path::{Path, PathBuf};use std::sync::atomic::{AtomicBool, Ordering};-use std::sync::{Arc, Mutex, MutexGuard, Weak};+use std::sync::{Arc, Mutex, MutexGuard};use std::time::{Duration, Instant};use tokio::sync::{mpsc, watch};use tokio::task::JoinSet;-const KEY_FILE: &str = "secret.key";/// How long an invite stays good.pub const INVITE_FOR: Duration = Duration::from_hours(1);const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);/// Long enough for the other computer to knock on its agent's harness.const CALL_TIMEOUT: Duration = Duration::from_secs(20);const INBOX_SIZE: usize = 256;-/// How long addresses get to settle after a change before this computer signs where it is.-const ADDR_SETTLE: Duration = Duration::from_secs(2);-/// Letters whose handoff count a reply may need, newest kept.+/// Letters whose handoff count a reply may need, and requests an answer may come back to, newest kept.const HEARD_MAX: usize = 1000;pub struct Node {@@ -59,8 +57,9 @@ struct Inner {taken: Mutex<VecDeque<String>>,/// Who may write to this computer's agents (`rules`).rules: Mutex<Vec<Rule>>,- /// Requests this computer sent, newest kept, and to whom: an answer to one passes the rules.- asked: Mutex<VecDeque<(String, EndpointId)>>,+ /// Requests this computer sent, newest kept: the letter's id, the computer it went to and+ /// the agent here that sent it. That computer's answer to that agent passes the rules.+ asked: Mutex<VecDeque<(String, EndpointId, String)>>,outbox: Mutex<Vec<outbox::Queued>>,inbox: mpsc::Sender<Message>,/// The command an agent the network knocks on runs to answer.@@ -81,8 +80,8 @@ impl Node {/// agents the app delivers to ([`Reach::App`]) come out of the returned inbox.pub async fn start(dir: &Path, connector: &Connector) -> Result<(Self, mpsc::Receiver<Message>)> {std::fs::create_dir_all(dir)?;- let key = load_key(dir)?;- let endpoint = bind(key, connector).await?;+ let key = endpoint::load_key(dir)?;+ let endpoint = endpoint::bind(key, connector).await?;let (tx, rx) = mpsc::channel(INBOX_SIZE);let inner = Arc::new(Inner {endpoint: endpoint.clone(),@@ -106,12 +105,12 @@ impl Node {changed: watch::Sender::new(()),});let router = Router::builder(endpoint).accept(ALPN, inbound::Handler(inner.clone())).spawn();- settle(&inner.endpoint, connector).await;+ endpoint::settle(&inner.endpoint, connector).await;inner.locate(inner.endpoint.addr())?;// Catch up with the others: a computer that was off may have missed a removal.inner.clone().hello_all();tokio::spawn(outbox::retry_loop(Arc::downgrade(&inner)));- tokio::spawn(follow_addr(Arc::downgrade(&inner), inner.endpoint.watch_addr()));+ tokio::spawn(endpoint::follow_addr(Arc::downgrade(&inner), inner.endpoint.watch_addr()));Ok((Self { inner, router }, rx))}@@ -258,7 +257,7 @@ impl Node {}/// What the app calls this network (`home`, `work`) when a computer is in several: the invites- /// it makes carry the name, so the computer that joins can call it the same ([`read_invite`]).+ /// it makes carry the name, so the computer that joins can call it the same ([`crate::read_invite`]).pub fn set_network_name(&self, name: Option<String>) {*locked(&self.inner.network_name) = name;}@@ -327,7 +326,7 @@ impl Node {wire::check(&envelope)?;// A request, which an answer may come back to past the other computer's rules.if !local && envelope.wake && envelope.reply_to.is_none() {- self.inner.asked(&envelope.id, id);+ remember(&mut locked(&self.inner.asked), (envelope.id.clone(), id, envelope.from.clone()), HEARD_MAX);}let name = |id: &EndpointId| roster.as_ref().map_or_else(|| "this computer".into(), |r| r.name(id));let answer = if local {@@ -368,17 +367,11 @@ impl Inner {self.endpoint.id()}- fn asked(&self, letter: &str, to: EndpointId) {- let mut asked = locked(&self.asked);- if asked.len() >= HEARD_MAX {- asked.pop_front();- }- asked.push_back((letter.to_owned(), to));- }-- /// Whether a letter from `peer` answers one this computer sent it.- pub(super) fn answers(&self, peer: EndpointId, reply_to: Option<&str>) -> bool {- reply_to.is_some_and(|id| locked(&self.asked).iter().any(|(sent, to)| sent == id && *to == peer))+ /// Whether a letter from `peer` answers a request this computer sent there, from the agent+ /// the letter is for.+ pub(super) fn answers(&self, peer: EndpointId, envelope: &wire::Envelope) -> bool {+ let Some(id) = envelope.reply_to.as_deref() else { return false };+ locked(&self.asked).iter().any(|(sent, to, by)| sent == id && *to == peer && *by == envelope.to)}fn hops_of(&self, letter: &str) -> Option<u8> {@@ -386,11 +379,7 @@ impl Inner {}fn heard(&self, letter: &str, hops: u8) {- let mut heard = locked(&self.heard);- if heard.len() >= HEARD_MAX {- heard.pop_front();- }- heard.push_back((letter.to_owned(), hops));+ remember(&mut locked(&self.heard), (letter.to_owned(), hops), HEARD_MAX);}fn offered(&self) -> Vec<Agent> {@@ -412,18 +401,6 @@ impl Inner {Ok(())}- /// Writes where this computer is into the roster when it moved. Returns whether it did.- fn locate(&self, addr: EndpointAddr) -> Result<bool> {- let mut guard = locked(&self.roster);- let Some(roster) = guard.as_mut() else { return Ok(false) };- if roster.members().get(&self.me()).is_none_or(|m| m.addr == addr) {- return Ok(false);- }- roster.sign(self.endpoint.secret_key(), wire::now_ms(), Change::Locate { addr })?;- self.save(roster)?;- Ok(true)- }-/// Keeps `roster` on disk and tells whoever watches [`Node::changes`]. Callers hold the roster/// lock until `roster` is the one kept in memory, so a watcher woken here reads it.fn save(&self, roster: &Roster) -> Result<()> {@@ -496,90 +473,6 @@ impl Inner {}}-/// What an invite says about its network, before joining it.-pub struct InviteInfo {- /// The network's id (its root key), as [`Node::network_id`] gives it.- pub network: String,- /// What the inviting computer calls the network, if it named it.- pub name: Option<String>,-}--pub fn read_invite(invite: &str) -> Result<InviteInfo> {- let ticket = Ticket::decode(invite)?;- Ok(InviteInfo { network: ticket.network.to_string(), name: ticket.name })-}--/// Signs where this computer is again whenever its addresses change (a laptop that moved to-/// another network) and tells the others, so they find it without a restart: with the `private`-/// connector, nothing else would. The roster keeps only each computer's newest location.-async fn follow_addr(inner: Weak<Inner>, mut addr: impl Watcher<Value = EndpointAddr>) {- while addr.updated().await.is_ok() {- // Addresses change in bursts (an interface comes up, then the relay answers): sign once.- tokio::time::sleep(ADDR_SETTLE).await;- let Some(inner) = inner.upgrade() else { return };- match inner.locate(addr.get()) {- Ok(true) => {- tracing::info!("this computer moved; telling the others");- inner.hello_all();- }- Ok(false) => {}- Err(e) => tracing::warn!(error = format!("{e:#}"), "couldn't sign where this computer is"),- }- }-}--async fn bind(key: SecretKey, connector: &Connector) -> Result<Endpoint> {- let builder = match connector {- Connector::Public => Endpoint::builder(presets::N0),- Connector::Relay(url) => {- let url: RelayUrl = url.parse().context("not a relay URL")?;- Endpoint::builder(presets::Minimal).relay_mode(RelayMode::custom([url]))- }- Connector::Private => Endpoint::builder(presets::Minimal).relay_mode(RelayMode::Disabled),- };- Ok(builder.secret_key(key).bind().await?)-}--/// Waits briefly until the endpoint knows its own addresses, so invites and the roster carry them.-async fn settle(endpoint: &Endpoint, connector: &Connector) {- if *connector != Connector::Private {- let _ = tokio::time::timeout(Duration::from_secs(5), endpoint.online()).await;- }- let until = Instant::now() + Duration::from_secs(3);- while endpoint.addr().ip_addrs().next().is_none() && Instant::now() < until {- tokio::time::sleep(Duration::from_millis(50)).await;- }-}--fn load_key(dir: &Path) -> Result<SecretKey> {- let path = dir.join(KEY_FILE);- match std::fs::read(&path) {- Ok(bytes) => {- let bytes: [u8; 32] = bytes.try_into().map_err(|_| anyhow!("{} is damaged", path.display()))?;- Ok(SecretKey::from_bytes(&bytes))- }- Err(e) if e.kind() == std::io::ErrorKind::NotFound => {- let key = SecretKey::generate();- write_private(&path, &key.to_bytes())?;- Ok(key)- }- Err(e) => Err(e).context("couldn't read this computer's key"),- }-}--fn write_private(path: &Path, bytes: &[u8]) -> Result<()> {- #[cfg(unix)]- {- use std::io::Write;- use std::os::unix::fs::OpenOptionsExt;- let mut file = std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(path)?;- file.write_all(bytes)?;- }- #[cfg(not(unix))]- std::fs::write(path, bytes)?;- Ok(())-}-fn check_name(name: &str) -> Result<String> {let name = name.trim();if name.is_empty() || name.len() > 40 || name.contains(['/', ' ', '@', '.']) {@@ -588,40 +481,10 @@ fn check_name(name: &str) -> Result<String> {Ok(name.into())}-#[cfg(test)]-mod tests {- use super::*;-- fn temp_dir(name: &str) -> PathBuf {- let dir = std::env::temp_dir().join(format!("codync-network-unit-{name}-{}", std::process::id()));- let _ = std::fs::remove_dir_all(&dir);- dir- }-- #[tokio::test]- async fn a_computer_that_moves_tells_the_others_without_a_restart() {- let (desk_dir, laptop_dir) = (temp_dir("desk"), temp_dir("laptop"));- let (desk, _) = Node::start(&desk_dir, &Connector::Private).await.expect("desk starts");- desk.create("desk").expect("a network");- let (laptop, _) = Node::start(&laptop_dir, &Connector::Private).await.expect("laptop starts");- laptop.join(&desk.invite().expect("an invite"), "laptop").await.expect("joined");-- // The laptop moves: an address it didn't have before.- let moved = laptop.inner.endpoint.addr().with_ip_addr("192.0.2.7:4242".parse().expect("an address"));- let watched = n0_watcher::Watchable::new(laptop.inner.endpoint.addr());- tokio::spawn(follow_addr(Arc::downgrade(&laptop.inner), watched.watch()));- watched.set(moved.clone()).expect("watched");- let desk_sees =- || locked(&desk.inner.roster).as_ref().and_then(|r| r.members().get(&laptop.id()).map(|m| m.addr.clone()));- tokio::time::timeout(Duration::from_secs(10), async {- while desk_sees() != Some(moved.clone()) {- tokio::time::sleep(Duration::from_millis(50)).await;- }- })- .await- .expect("the desk hears where the laptop is now");- for dir in [desk_dir, laptop_dir] {- let _ = std::fs::remove_dir_all(dir);- }+/// Keeps `item` in a list of the newest `max`.+fn remember<T>(list: &mut VecDeque<T>, item: T, max: usize) {+ if list.len() >= max {+ list.pop_front();}+ list.push_back(item);}diff --git a/host/crates/network/src/types.rs b/host/crates/network/src/types.rsindex 5592c3a2..ec846998 100644--- a/host/crates/network/src/types.rs+++ b/host/crates/network/src/types.rs@@ -4,14 +4,17 @@ use crate::roster::Role;use crate::wire::{self, Agent, Envelope};use anyhow::{Result, anyhow, bail};use iroh::EndpointId;+use serde::{Deserialize, Deserializer, Serialize, Serializer};use serde_json::Value;use std::fmt;use std::str::FromStr;-/// How computers reach each other when they can't connect directly.-#[derive(Clone, Debug, PartialEq, Eq)]+/// How computers reach each other when they can't connect directly. Written as `public`,+/// `private` or the relay's URL, also in JSON.+#[derive(Clone, Debug, Default, PartialEq, Eq)]pub enum Connector {/// iroh's public relays and address lookup. Free, rate-limited, meant for trying things out.+ #[default]Public,/// Your own `iroh-relay`, and nothing of anyone else's.Relay(String),@@ -32,6 +35,28 @@ impl FromStr for Connector {}}+impl fmt::Display for Connector {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Self::Public => f.write_str("public"),+ Self::Private => f.write_str("private"),+ Self::Relay(url) => f.write_str(url),+ }+ }+}++impl Serialize for Connector {+ fn serialize<S: Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {+ s.collect_str(self)+ }+}++impl<'de> Deserialize<'de> for Connector {+ fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {+ String::deserialize(d)?.parse().map_err(serde::de::Error::custom)+ }+}+/// `agent@computer`, like ssh's `user@host`. A bare `agent` is looked up with/// [`Node::resolve`](crate::Node::resolve).#[derive(Clone, Debug, PartialEq, Eq)]@@ -161,3 +186,18 @@ pub enum Sent {/// The computer is away; it gets the letter when it's back (within a day).Queued,}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn connectors_read_and_write_as_text() {+ for text in ["public", "private", "https://relay.example"] {+ let connector: Connector = serde_json::from_value(json!(text)).unwrap();+ assert_eq!(serde_json::to_value(&connector).unwrap(), text);+ }+ assert!(serde_json::from_value::<Connector>(json!("ftp://relay.example")).is_err());+ }+}diff --git a/host/crates/network/src/wire.rs b/host/crates/network/src/wire.rsindex 485ba25c..6b518771 100644--- a/host/crates/network/src/wire.rs+++ b/host/crates/network/src/wire.rs@@ -114,6 +114,19 @@ impl Ticket {}}+/// What an invite says about its network, before joining it.+pub struct InviteInfo {+ /// The network's id (its root key), as [`Node::network_id`](crate::Node::network_id) gives it.+ pub network: String,+ /// What the inviting computer calls the network, if it named it.+ pub name: Option<String>,+}++pub fn read_invite(invite: &str) -> Result<InviteInfo> {+ let ticket = Ticket::decode(invite)?;+ Ok(InviteInfo { network: ticket.network.to_string(), name: ticket.name })+}+pub async fn call(conn: &Connection, request: &Request) -> Result<Response> {let (mut send, mut recv) = conn.open_bi().await?;send.write_all(&serde_json::to_vec(request)?).await?;diff --git a/host/crates/network/tests/two_computers.rs b/host/crates/network/tests/two_computers.rsindex 53d6deff..8fb5c228 100644--- a/host/crates/network/tests/two_computers.rs+++ b/host/crates/network/tests/two_computers.rs@@ -278,7 +278,7 @@ fn roles_decide_who_invites_removes_and_promotes() {}#[tokio::test]-async fn the_receiving_computers_rules_decide_but_answers_always_pass() {+async fn the_receiving_computers_rules_decide_but_answers_to_the_asker_pass() {use codync_network::{Access, Rule};let (desk_dir, laptop_dir) = (temp_dir("desk7"), temp_dir("laptop7"));let (desk, mut desk_inbox) = Node::start(&desk_dir, &Connector::Private).await.unwrap();@@ -302,10 +302,17 @@ async fn the_receiving_computers_rules_decide_but_answers_always_pass() {assert_eq!(next(&mut desk_inbox).await.body, "review this", "allowed by the first rule");let refused = laptop.send(Letter::new("intern", to("coder@desk"), "hi")).await.unwrap_err();assert_eq!(refused.to_string(), "desk refused it: coder doesn't take messages from intern@laptop");- // An answer to the desk's own question still gets in, whoever sends it.- let answer = Letter::new("intern", to("reviewer@desk"), "main").reply_to(asked);+ // An answer to the desk's own question still gets in, whoever sends it, but only to the+ // agent that asked, and only until the one that says how it ended (`meta`).+ let elsewhere = Letter::new("intern", to("coder@desk"), "main").reply_to(asked.clone());+ assert!(laptop.send(elsewhere).await.is_err(), "coder didn't ask");+ let answer = Letter::new("intern", to("reviewer@desk"), "main").reply_to(asked.clone());assert_eq!(laptop.send(answer).await.unwrap(), Sent::Delivered);assert_eq!(next(&mut desk_inbox).await.body, "main");+ let last = Letter::new("intern", to("reviewer@desk"), "done").reply_to(asked.clone()).meta(serde_json::json!({}));+ assert_eq!(laptop.send(last).await.unwrap(), Sent::Delivered);+ assert_eq!(next(&mut desk_inbox).await.body, "done");+ assert!(laptop.send(Letter::new("intern", to("reviewer@desk"), "more").reply_to(asked)).await.is_err());// A made-up answer doesn't.let fake = Letter::new("intern", to("coder@desk"), "sneaky").reply_to("not-a-letter-of-yours");assert!(laptop.send(fake).await.is_err());diff --git a/host/src/chat/team/assistant.rs b/host/src/chat/team/assistant.rsindex 70a12c62..4f76c0ec 100644--- a/host/src/chat/team/assistant.rs+++ b/host/src/chat/team/assistant.rs@@ -16,8 +16,8 @@ use crate::LockExt;use crate::hub::Hub;use crate::network::Recipient;use crate::remote::cloud::{self, CloudStatus};-use crate::store::{Store, now_ms};-use anyhow::{Result, bail};+use crate::store::{BotConfig, Store, now_ms};+use anyhow::{Result, anyhow, bail};use serde_json::{Value, json};use std::sync::{Arc, Mutex};@@ -47,6 +47,22 @@ pub fn available(hub: &Hub) -> bool {hub.cloud.status().owner.is_some()}+/// A letter the cloud assistant sent through another of the user's computers: this computer's own+/// switches decide whether it reaches `bot`, as they do for its calls here.+pub(super) fn admit_letter(hub: &Hub, bot: &BotConfig) -> Result<()> {+ if !enabled(&hub.store) {+ bail!(OFF);+ }+ if !bot.reachable_by_assistants {+ return Err(closed(bot));+ }+ Ok(())+}++fn closed(bot: &BotConfig) -> anyhow::Error {+ anyhow!("{} isn't open to cloud assistants: Reachable by cloud assistants is off in its settings", bot.name)+}+/// `setAssistants`: whether the cloud assistant may reach this computer's bots. Local only.pub fn set_enabled(hub: &Hub, on: bool) -> Result<CloudStatus> {cloud::require_accounts(&hub.store)?;@@ -99,7 +115,15 @@ struct Asker {who: String,/// What it signs letters to the user's other computers with.handle: String,- cloud: bool,+ kind: Kind,+}++#[derive(Clone, Copy, PartialEq, Eq)]+enum Kind {+ /// The user's cloud assistant, through the relay.+ Cloud,+ /// An agent on this computer (`codync-host mcp network`).+ Local,}impl Asker {@@ -109,7 +133,7 @@ impl Asker {name: NAME.into(),who: "The user's cloud assistant (ChatGPT, Claude or another assistant they connected to Codync)".into(),handle: HANDLE.into(),- cloud: true,+ kind: Kind::Cloud,}}@@ -125,19 +149,20 @@ impl Asker {name: format!("{name} (this computer)"),who: format!("{name}, an agent on this computer that isn't a Codync bot,"),handle: format!("agent-{handle}"),- cloud: false,+ kind: Kind::Local,})}++ /// Whether it may see and message `bot`: a cloud assistant only the bots open to it.+ fn reaches(&self, bot: &BotConfig) -> bool {+ self.kind == Kind::Local || bot.reachable_by_assistants+ }}async fn run(hub: &Arc<Hub>, asker: &Asker, tool: &str, args: &Value) -> Result<Value> {match tool {// Also the bots on the user's other computers in this one's network (what they offer).- "list_bots" => {- let keep: fn(&crate::store::BotConfig) -> bool =- if asker.cloud { |bot| bot.reachable_by_assistants } else { |_| true };- directory::list(hub, &asker.id, args, &hub.network.directory().await, keep)- }+ "list_bots" => directory::list(hub, &asker.id, args, &hub.network.directory().await, |bot| asker.reaches(bot)),"message_bot" => message(hub, asker, args),"read_replies" => Ok(hub.assistant.read(&asker.id, args["requestId"].as_str())),_ => bail!("unknown tool: {tool}"),@@ -155,8 +180,8 @@ fn message(hub: &Arc<Hub>, asker: &Asker, args: &Value) -> Result<Value> {Recipient::There(address) => return message_elsewhere(hub, asker, &address, message),};let target = visible_bot(hub, &to)?;- if asker.cloud && !target.reachable_by_assistants {- bail!("{} isn't open to cloud assistants: Reachable by cloud assistants is off in its settings", target.name);+ if !asker.reaches(&target) {+ return Err(closed(&target));}let request = uuid::Uuid::new_v4().to_string();let back = Back::Assistant { request: request.clone() };@@ -164,15 +189,7 @@ fn message(hub: &Arc<Hub>, asker: &Asker, args: &Value) -> Result<Value> {let (source, name) = (asker.id.as_str(), asker.name.as_str());let exchange = Exchange { request: &request, source, target: &target.id, text: message, peer_name: Some(name) };lifetime.entries.push(exchange.notice(hub, &target.id, &format!("Message from {name}: {message}"), true)?);- hub.assistant.add(Reply {- asker: asker.id.clone(),- request: request.clone(),- bot: target.name.clone(),- quote: lifetime.quote.clone(),- status: RequestStatus::Queued,- text: None,- at: now_ms(),- });+ hub.assistant.add(Reply::queued(&asker.id, &request, &target.name, message));lifetime.deliver(&target.id, 1, request_prompt(&asker.who, name, message))?;Ok(json!({"requestId": request, "botId": target.id, "name": target.name, "status": RequestStatus::Queued,@@ -181,18 +198,9 @@ fn message(hub: &Arc<Hub>, asker: &Asker, args: &Value) -> Result<Value> {}/// A bot on another of the user's computers (`reviewer@laptop`): a letter from this computer,-/// whose answer comes back here. That computer's own rules decide whether it takes it.+/// whose answer comes back here. That computer's own rules and switches decide whether it takes it.fn message_elsewhere(hub: &Arc<Hub>, asker: &Asker, to: &crate::network::Target, message: &str) -> Result<Value> {- let (request, peer) = remote::ask_for_assistant(hub, &asker.handle, to, message)?;- hub.assistant.add(Reply {- asker: asker.id.clone(),- request: request.clone(),- bot: peer.clone(),- quote: crate::agent::acp::truncate(message, super::REQUEST_QUOTE_BYTES),- status: RequestStatus::Queued,- text: None,- at: now_ms(),- });+ let (request, peer) = remote::ask_for_replies(hub, &asker.id, &asker.handle, to, message)?;Ok(json!({"requestId": request, "botId": hub.network.address_text(to), "name": peer, "status": RequestStatus::Queued,"note": "Queued on that computer. Bots can take minutes: get the reply later with read_replies.",@@ -242,7 +250,7 @@ your work and check read_replies later instead of waiting in a loop.";#[derive(Default)]pub struct Replies(Mutex<Vec<Reply>>);-struct Reply {+pub(super) struct Reply {/// Whose request (`Asker::id`).asker: String,request: String,@@ -255,6 +263,19 @@ struct Reply {}impl Reply {+ /// A request just made, before anything came back.+ pub(super) fn queued(asker: &str, request: &str, bot: &str, message: &str) -> Self {+ Self {+ asker: asker.into(),+ request: request.into(),+ bot: bot.into(),+ quote: crate::agent::acp::truncate(message, super::REQUEST_QUOTE_BYTES),+ status: RequestStatus::Queued,+ text: None,+ at: now_ms(),+ }+ }+fn running(&self) -> bool {matches!(self.status, RequestStatus::Queued | RequestStatus::Sent)}@@ -269,7 +290,7 @@ impl Reply {}impl Replies {- fn add(&self, reply: Reply) {+ pub(super) fn add(&self, reply: Reply) {let mut all = self.0.locked();all.push(reply);while all.len() > KEEP {@@ -289,8 +310,12 @@ impl Replies {}}+ /// The bot took the request, unless its outcome already came (a quick one can beat this).pub(super) fn started(&self, request: &str) {- self.set(request, RequestStatus::Sent, None);+ if let Some(r) = self.0.locked().iter_mut().find(|r| r.request == request && r.status == RequestStatus::Queued)+ {+ r.status = RequestStatus::Sent;+ }}pub(super) fn answered(&self, request: &str, outcome: std::result::Result<String, String>) {diff --git a/host/src/chat/team/assistant/tests.rs b/host/src/chat/team/assistant/tests.rsindex 7fb1e6ca..48899c75 100644--- a/host/src/chat/team/assistant/tests.rs+++ b/host/src/chat/team/assistant/tests.rs@@ -99,6 +99,12 @@ async fn a_bot_closed_to_cloud_assistants_is_neither_listed_nor_reached() {&call(hub, "user_1", "message_bot", &json!({"botId": "b", "message": "hi"})).await,"isn't open to cloud assistants",);+ // Nor through another of the user's computers: this computer's switches decide its letters too.+ let bot = |id: &str| hub.store.bot(id).unwrap().unwrap().config;+ assert!(admit_letter(hub, &bot("b")).unwrap_err().to_string().contains("isn't open to cloud assistants"));+ assert!(admit_letter(hub, &bot("c")).is_ok());+ set_enabled(hub, false).unwrap();+ assert!(admit_letter(hub, &bot("c")).unwrap_err().to_string().contains("Cloud assistants are off"));f.shutdown().await;}@@ -117,7 +123,7 @@ async fn an_answer_from_another_computer_waits_in_the_replies() {};for request in ["l1", "l2"] {hub.assistant.add(added(request));- remote::awaits_for_assistant(hub, request, "Coder on laptop", "status?");+ remote::awaits_in_replies(hub, request, "Coder on laptop", "status?");}let (tx, rx) = tokio::sync::mpsc::channel(4);tokio::spawn(remote::listen(hub.clone(), "network".into(), rx));diff --git a/host/src/chat/team/directory.rs b/host/src/chat/team/directory.rsindex d53c8104..a38a0ba3 100644--- a/host/src/chat/team/directory.rs+++ b/host/src/chat/team/directory.rs@@ -28,7 +28,7 @@ pub(super) fn list(from: &str,args: &Value,remote: &[Peer],- keep: fn(&BotConfig) -> bool,+ keep: impl Fn(&BotConfig) -> bool,) -> Result<Value> {let filter = Filter::of(args);let here = hub.network.my_name();@@ -39,7 +39,7 @@ pub(super) fn list(/// Everyone `from` can message, nearest first: this computer's bots, then the ones on computers/// that can take a message now.-fn rows(hub: &Hub, from: &str, remote: &[Peer], keep: fn(&BotConfig) -> bool) -> Result<Vec<Row>> {+fn rows(hub: &Hub, from: &str, remote: &[Peer], keep: impl Fn(&BotConfig) -> bool) -> Result<Vec<Row>> {let mut rows: Vec<Row> = visible_bots(&hub.store)?.into_iter().filter(|c| c.id != from && keep(c))@@ -96,9 +96,8 @@ impl Filter {fn keeps(&self, row: &Row, here: Option<&str>) -> bool {let at = row.computer.as_deref().or(here).map(str::to_lowercase);// `desk` also finds `desk.home`, a computer in one of this computer's several networks.- let at_computer = |c: &String| {- at.as_ref().is_some_and(|a| a == c || a.strip_prefix(c.as_str()).is_some_and(|rest| rest.starts_with('.')))- };+ let at_computer =+ |c: &String| at.as_deref().is_some_and(|a| a == c || crate::network::split_computer(a).0 == c);let on = |c: &String| at_computer(c) || (row.computer.is_none() && c == HERE);self.words.iter().all(|w| row.words.contains(w))&& self.computer.as_ref().is_none_or(on)@@ -169,6 +168,10 @@ mod tests {assert_eq!(kept(&rows, &json!({"computer": HERE}), None), ["Coder", "Code Reviewer"]);assert_eq!(kept(&rows, &json!({"online": true}), None), ["Coder", "Code Reviewer"]);assert_eq!(kept(&rows, &json!({"computer": "elsewhere"}), None), Vec::<&str>::new());+ // In several networks, a computer is named with its network: its bare name still finds it.+ let several = [row("Lead", "", Some("laptop.home"), true), row("Ops", "", Some("laptop-2.work"), true)];+ assert_eq!(kept(&several, &json!({"computer": "laptop"}), None), ["Lead"]);+ assert_eq!(kept(&several, &json!({"computer": "laptop-2.work"}), None), ["Ops"]);let first = page(&rows, &json!({"limit": 2}), true);assert_eq!((first["total"].as_u64(), first["next"].as_str()), (Some(3), Some("2")));diff --git a/host/src/chat/team/remote.rs b/host/src/chat/team/remote.rsindex 95ecd392..fc7198eb 100644--- a/host/src/chat/team/remote.rs+++ b/host/src/chat/team/remote.rs@@ -26,18 +26,19 @@ use tokio::sync::mpsc;pub struct Waiting(Mutex<HashMap<String, Waiter>>);struct Waiter {- asker: Asker,+ to: ReplyTo,quote: String,/// How the recipient is shown ("Reviewer on desk").peer: String,}-/// Who waits for an answer from another computer.-enum Asker {+/// Where an answer from another computer goes.+enum ReplyTo {/// One of this computer's bots, with its exchange notice.Bot { id: String, entry: String },- /// The user's cloud assistant: the answer waits in its replies (by the letter's id).- Assistant,+ /// The asker's replies, by the letter's id: the cloud assistant's, or an agent's on this+ /// computer that isn't a bot (`assistant::Asker`).+ Replies,}impl Waiting {@@ -76,14 +77,22 @@ fn take(hub: &Arc<Hub>, network: &str, m: &Message) -> Result<()> {}let back = Return { network: network.to_owned(), to: m.from.clone(), request: m.id.clone(), from: m.to.clone() };let target = hub.network.bot_for(&m.to).ok_or_else(|| anyhow!("no bot called {} here", m.to));- match target.and_then(|bot| visible_bot(hub, &bot)) {+ let target = target.and_then(|bot| visible_bot(hub, &bot)).and_then(|bot| {+ // The cloud assistant asking through another computer: this one's cloud switches decide too.+ if m.from.agent == super::assistant::HANDLE && m.reply_to.is_none() {+ super::assistant::admit_letter(hub, &bot)?;+ }+ Ok(bot)+ });+ match target {// A note, or a reply this computer no longer waits for (it restarted): the chat shows it.Ok(target) if !m.wake || m.reply_to.is_some() => {note(hub, network, &target, m);Ok(())}Ok(target) => requested(hub, network, &target, m, back),- // The bot went away after this computer took the request: its sender would wait for good.+ // The bot went away after this computer took the request, or it doesn't take the sender's+ // requests: the sender would wait for good.Err(error) if m.wake && m.reply_to.is_none() => {send_back(hub, &back, format!("Couldn't take it: {error:#}"), RequestStatus::Failed, m.hops);Err(error)@@ -129,8 +138,7 @@ async fn send(hub: &Arc<Hub>, node: &Node, source: &BotConfig, to: &Target, lettExchange { request: &id, source: &source.id, target: &address, text: &letter.body, peer_name: Some(&peer) };let entry = exchange.notice(hub, &source.id, &heading, false)?;let quote = truncate(&letter.body, REQUEST_QUOTE_BYTES);- let asker = Asker::Bot { id: source.id.clone(), entry: entry.clone() };- let waiter = Waiter { asker, quote, peer: peer.clone() };+ let waiter = Waiter { to: ReplyTo::Bot { id: source.id.clone(), entry: entry.clone() }, quote, peer: peer.clone() };hub.waiting.insert(id.clone(), waiter);let said = match node.send(letter).await {Ok(Sent::Delivered) => {@@ -154,15 +162,24 @@ async fn send(hub: &Arc<Hub>, node: &Node, source: &BotConfig, to: &Target, lett}))}-/// The user's cloud assistant asks a bot on another computer. Returns the request's id (the-/// letter's) at once: the letter goes in the background, and its outcome waits in the-/// assistant's replies.-pub(super) fn ask_for_assistant(hub: &Arc<Hub>, from: &str, to: &Target, message: &str) -> Result<(String, String)> {+/// The cloud assistant, or an agent on this computer that isn't a bot, asks a bot on another+/// computer: `asker` is whose replies the outcome waits in, `from` the address name it signs with.+/// Returns the request's id (the letter's) and how the bot is shown, at once: the letter goes in+/// the background.+pub(super) fn ask_for_replies(+ hub: &Arc<Hub>,+ asker: &str,+ from: &str,+ to: &Target,+ message: &str,+) -> Result<(String, String)> {let node = hub.network.slot(Some(&to.network))?.node;hub.network.send_as(from)?;let letter = Letter::new(from, to.address.clone(), message);let (id, peer) = (letter.id.clone(), peer_name(hub, &to.network, &to.address));- awaits_for_assistant(hub, &id, &peer, message);+ // Kept before the letter goes, so an outcome as quick as a refusal finds them.+ hub.assistant.add(super::assistant::Reply::queued(asker, &id, &peer, message));+ awaits_in_replies(hub, &id, &peer, message);let (hub, request) = (hub.clone(), id.clone());tokio::spawn(async move {match node.send(letter).await {@@ -177,10 +194,10 @@ pub(super) fn ask_for_assistant(hub: &Arc<Hub>, from: &str, to: &Target, messageOk((id, peer))}-/// The answer to letter `id` goes to the cloud assistant's replies.-pub(super) fn awaits_for_assistant(hub: &Hub, id: &str, peer: &str, message: &str) {+/// The answer to letter `id` goes to its asker's replies.+pub(super) fn awaits_in_replies(hub: &Hub, id: &str, peer: &str, message: &str) {let quote = truncate(message, REQUEST_QUOTE_BYTES);- hub.waiting.insert(id.to_owned(), Waiter { asker: Asker::Assistant, quote, peer: peer.to_owned() });+ hub.waiting.insert(id.to_owned(), Waiter { to: ReplyTo::Replies, quote, peer: peer.to_owned() });}/// Says where a request waits, unless its reply already came (a quick one can beat this).@@ -252,7 +269,7 @@ fn send_back(hub: &Hub, to: &Return, mut body: String, status: RequestStatus, hofn replied(hub: &Hub, id: &str, waiter: Waiter, m: &Message) {let peer = &waiter.peer;let status = m.meta.as_ref().and_then(|meta| serde_json::from_value(meta["codync"].clone()).ok());- let Asker::Bot { id: sender, entry } = waiter.asker else {+ let ReplyTo::Bot { id: sender, entry } = waiter.to else {match status {Some(RequestStatus::Cancelled) => hub.assistant.cancelled(id),Some(RequestStatus::Failed) => hub.assistant.answered(id, Err(m.body.clone())),diff --git a/host/src/network/api.rs b/host/src/network/api.rsindex 28a1b636..7a57895f 100644--- a/host/src/network/api.rs+++ b/host/src/network/api.rs@@ -22,14 +22,7 @@ pub fn emit(hub: &Hub) {/// plus the cloud assistants switch, and whether they can reach this computer at all/// (`assistantsAvailable`). Never an invite: phones read it too.pub fn status(hub: &Hub) -> Value {- let saved = saved::load(hub);- let networks: Vec<Value> = hub- .network- .slots()- .iter()- .filter(|s| s.node.name().is_some())- .map(|s| network(s, saved.iter().find(|x| x.id == s.id)))- .collect();+ let networks: Vec<Value> = hub.network.slots().iter().filter(|s| s.node.name().is_some()).map(network).collect();json!({"joined": !networks.is_empty(), "networks": networks,"assistants": crate::chat::team::assistant::enabled(&hub.store),@@ -37,7 +30,7 @@ pub fn status(hub: &Hub) -> Value {})}-fn network(slot: &Slot, saved: Option<&Saved>) -> Value {+fn network(slot: &Slot) -> Value {let node = &slot.node;let mine = node.role();let computers: Vec<Value> = node@@ -55,7 +48,7 @@ fn network(slot: &Slot, saved: Option<&Saved>) -> Value {json!({"id": slot.id, "name": slot.name, "computer": node.name(), "role": mine,"canInvite": mine.is_some_and(Role::invites), "canRecover": mine.is_some_and(|r| r != Role::Owner),- "connector": saved.map_or("public", |s| s.connector.as_str()),+ "connector": slot.connector,"computers": computers, "rules": node.rules(),})}@@ -81,13 +74,11 @@ async fn add<T>(connector: Option<&str>,first: impl AsyncFnOnce(&Node) -> Result<T>,) -> Result<(Slot, T)> {+ let connector: Connector = connector.map_or(Ok(Connector::Public), str::parse)?;let _one = hub.network.changing.lock().await;- let mut all = saved::load(hub);- let connector = connector.unwrap_or("public");- connector.parse::<Connector>()?;+ let mut all = saved::load(&hub.store);let id = saved::new_id(&all);- let saved =- Saved { id: id.clone(), name: saved::free_name(&all, name)?, connector: connector.into(), rules: Vec::new() };+ let saved = Saved { id: id.clone(), name: saved::free_name(&all, name)?, connector, rules: Vec::new() };let (node, inbox) = start_node(&saved).await?;let made = match first(&node).await {Ok(it) => it,@@ -98,14 +89,15 @@ async fn add<T>(}};all.push(saved.clone());- saved::save(hub, &all)?;+ saved::save(&hub.store, &all)?;let slot = take_in(hub, &saved, node, inbox);emit(hub);Ok((slot, made))}/// `networkCreate`: a new network (`network`, its name) with this computer as its owner, under-/// `name`. Returns the recovery code: the apps show it once, and it is kept nowhere.+/// `name`. Returns its id and name, and the recovery code: the apps show it once, and it is kept+/// nowhere.pub async fn create(hub: &Arc<Hub>,network: Option<&str>,@@ -113,8 +105,9 @@ pub async fn create(connector: Option<&str>,) -> Result<Value> {let name = name.map_or_else(default_name, str::to_owned);- let (slot, code) = add(hub, network.unwrap_or("home"), connector, async |node: &Node| node.create(&name)).await?;- Ok(json!({"network": slot.id, "computer": slot.node.name(), "recoveryCode": code}))+ let network = network.unwrap_or(saved::DEFAULT_NAME);+ let (slot, code) = add(hub, network, connector, async |node: &Node| node.create(&name)).await?;+ Ok(json!({"network": slot.id, "name": slot.name, "computer": slot.node.name(), "recoveryCode": code}))}/// `networkJoin`: joins a network with an invite from its owner or an admin, under the name the@@ -130,7 +123,7 @@ pub async fn join(if let Some(slot) = hub.network.slots().iter().find(|s| s.node.network_id().as_ref() == Some(&ticket.network)) {bail!("this computer is already in that network ({})", slot.name);}- let network = network.or(ticket.name.as_deref()).unwrap_or("home");+ let network = network.or(ticket.name.as_deref()).unwrap_or(saved::DEFAULT_NAME);let name = name.map_or_else(default_name, str::to_owned);add(hub, network, connector, async |node: &Node| node.join(invite, &name).await).await?;Ok(status(hub))@@ -143,9 +136,9 @@ pub async fn leave(hub: &Arc<Hub>, network: Option<&str>) -> Result<Value> {let slot = hub.network.slot(network)?;hub.network.slots.locked().retain(|s| s.id != slot.id);slot.node.shutdown().await;- let mut all = saved::load(hub);+ let mut all = saved::load(&hub.store);all.retain(|s| s.id != slot.id);- saved::save(hub, &all)?;+ saved::save(&hub.store, &all)?;tokio::task::spawn_blocking(move || std::fs::remove_dir_all(saved::dir(&slot.id))).await?.context("couldn't delete the network's folder")?;@@ -202,11 +195,11 @@ pub fn set_rules(hub: &Hub, network: Option<&str>, rules: &Value) -> Result<Valuserde_json::from_value(rules.clone()).context("rules are {fromComputer, fromAgent, toAgent, access}")?;let slot = joined(hub, network)?;slot.node.set_rules(rules.clone())?;- let mut all = saved::load(hub);+ let mut all = saved::load(&hub.store);if let Some(saved) = all.iter_mut().find(|s| s.id == slot.id) {saved.rules = rules;}- saved::save(hub, &all)?;+ saved::save(&hub.store, &all)?;emit(hub);Ok(status(hub))}diff --git a/host/src/network/handles.rs b/host/src/network/handles.rsindex d2a9a9d4..3924f475 100644--- a/host/src/network/handles.rs+++ b/host/src/network/handles.rs@@ -21,6 +21,15 @@ pub fn handle(name: &str) -> String {if out.is_empty() { "bot".into() } else { out }}+/// `base`, or the first of `base-2`, `base-3`… that is `free`, when at most `taken` names aren't.+pub fn numbered(base: &str, taken: usize, free: impl Fn(&str) -> bool) -> String {+ std::iter::once(base.to_owned())+ // One more number than there are names taken: one of them is free.+ .chain((2..=taken + 2).map(|n| format!("{base}-{n}")))+ .find(|name| free(name))+ .expect("a number is free")+}+/// Address names both ways, for the bots this computer offers.#[derive(Default)]pub struct Handles {@@ -34,12 +43,7 @@ impl Handles {pub fn of(bots: impl IntoIterator<Item = (String, String)>, given: &mut HashMap<String, String>) -> Self {let mut handles = Self::default();for (id, name) in bots {- let base = handle(&name);- let free = std::iter::once(base.clone())- // One more number than there are names given: one of them is free.- .chain((2..=given.len() + 2).map(|n| format!("{base}-{n}")))- .find(|h| given.get(h).is_none_or(|bot| *bot == id))- .expect("a number is free");+ let free = numbered(&handle(&name), given.len(), |h| given.get(h).is_none_or(|bot| *bot == id));given.insert(free.clone(), id.clone());handles.to_bot.insert(free.clone(), id.clone());handles.to_handle.insert(id, free);diff --git a/host/src/network/mod.rs b/host/src/network/mod.rsindex d2b0562e..39c9d3ce 100644--- a/host/src/network/mod.rs+++ b/host/src/network/mod.rs@@ -46,6 +46,7 @@ pub struct Slot {pub id: String,/// What the user calls it (`home`), unique on this computer.pub name: String,+ pub connector: Connector,pub node: Arc<Node>,}@@ -58,6 +59,9 @@ pub struct Network {/// Names this computer sends letters as without offering them (`Node::set_senders`): the cloud/// assistant, and agents that aren't bots (`codync-host mcp network`).senders: Mutex<BTreeSet<String>>,+ /// The address names of the bots kept off the network (Offered to the network off): they+ /// still message the others and hear back.+ unoffered: Mutex<Vec<String>>,/// One create, join or leave at a time.changing: tokio::sync::Mutex<()>,}@@ -134,7 +138,7 @@ impl Network {.flat_map(|s| {s.node.directory().into_iter().filter(|p| !p.me).map(move |mut p| {if several {- p.name = format!("{}.{}", p.name, s.name);+ p.name = qualified(&p.name, &s.name);}p})@@ -159,16 +163,13 @@ impl Network {/// `[email protected]` names the network; a bare name one other computer offers is there./// Refuses a name that two networks would both take, naming the full addresses.pub fn recipient(&self, name: &str) -> Result<Recipient> {- let (handle, at) = name.rsplit_once('@').map_or((name, None), |(handle, at)| (handle, Some(at)));+ let (handle, at) = split_address(name);let here = self.handles.locked().bot(handle);let local = || Ok(Recipient::Here(here.clone().unwrap_or_else(|| name.to_owned())));if at.is_none() && here.is_some() {return local();}- let (computer, network) = match at.map(|at| at.split_once('.').map_or((at, None), |(c, n)| (c, Some(n)))) {- Some((computer, network)) => (Some(computer), network),- None => (None, None),- };+ let (computer, network) = at.map_or((None, None), |(computer, network)| (Some(computer), network));let slots = match network {Some(n) => vec![self.slot(Some(n))?],None => self.slots(),@@ -203,7 +204,7 @@ impl Network {/// `[email protected]`.fn full_address(&self, target: &Target) -> String {let network = self.slot(Some(&target.network)).map_or_else(|_| target.network.clone(), |s| s.name);- format!("{}.{network}", target.address)+ format!("{}@{}", target.address.agent, qualified(&target.address.computer, &network))}/// Lets this computer send letters as `name` without offering it, unless a bot goes by it.@@ -211,21 +212,43 @@ impl Network {if let Some(bot) = self.bot_for(name) {bail!("a bot here ({bot}) already goes by {name} on the network: give the agent another name");}- let mut senders = self.senders.locked();- if senders.insert(name.to_owned()) {- for slot in self.slots() {- slot.node.set_senders(senders.iter().cloned());- }+ if self.senders.locked().insert(name.to_owned()) {+ self.share_senders();}Ok(())}+ /// Tells every network's node who this computer sends as without offering: `send_as`'s names+ /// and the bots kept off the network.+ fn share_senders(&self) {+ let mut senders: Vec<String> = self.senders.locked().iter().cloned().collect();+ senders.extend(self.unoffered.locked().iter().cloned());+ for slot in self.slots() {+ slot.node.set_senders(senders.clone());+ }+ }+/// This computer's bot behind an address name, if any.pub fn bot_for(&self, handle: &str) -> Option<String> {self.handles.locked().bot(handle)}}+/// `computer.network`: a computer named with its network, while this computer is in several.+fn qualified(computer: &str, network: &str) -> String {+ format!("{computer}.{network}")+}++/// `desk.home` → (`desk`, `home`); a bare `desk` names no network.+pub fn split_computer(at: &str) -> (&str, Option<&str>) {+ at.split_once('.').map_or((at, None), |(computer, network)| (computer, Some(network)))+}++/// `name`, `name@computer` or `[email protected]`, in parts.+fn split_address(name: &str) -> (&str, Option<(&str, Option<&str>)>) {+ name.rsplit_once('@').map_or((name, None), |(handle, at)| (handle, Some(split_computer(at))))+}+/// `a, b and c`.fn list(names: &[impl AsRef<str>]) -> String {let names: Vec<&str> = names.iter().map(AsRef::as_ref).collect();@@ -238,7 +261,10 @@ fn list(names: &[impl AsRef<str>]) -> String {/// Starts the node of every network this computer is in.pub async fn start(hub: &Arc<Hub>) {- for saved in saved::load(hub) {+ if let Err(error) = saved::migrate(&hub.store, &crate::service::data_dir()) {+ tracing::warn!(error = format!("{error:#}"), "couldn't keep the network this computer was in");+ }+ for saved in saved::load(&hub.store) {let id = saved.id.clone();if let Err(error) = boot(hub, &saved).await {tracing::warn!(network = id, error = format!("{error:#}"), "couldn't start a network");@@ -253,12 +279,11 @@ async fn boot(hub: &Arc<Hub>, saved: &saved::Saved) -> Result<Slot> {}async fn start_node(saved: &saved::Saved) -> Result<(Node, tokio::sync::mpsc::Receiver<codync_network::Message>)> {- let connector: Connector = saved.connector.parse()?;- Node::start(&saved::dir(&saved.id), &connector).await.context("couldn't start the network")+ Node::start(&saved::dir(&saved.id), &saved.connector).await.context("couldn't start the network")}/// A started node becomes one of this computer's networks: its rules and name, what this computer-/// offers, and the letters that reach it.+/// offers and sends as, and the letters that reach it.fn take_in(hub: &Arc<Hub>,saved: &saved::Saved,@@ -269,8 +294,8 @@ fn take_in(tracing::warn!(error = format!("{error:#}"), "couldn't apply the network's rules; none apply");}node.set_network_name(Some(saved.name.clone()));- node.set_senders(hub.network.senders.locked().iter().cloned());- let slot = Slot { id: saved.id.clone(), name: saved.name.clone(), node: Arc::new(node) };+ let (id, name, connector) = (saved.id.clone(), saved.name.clone(), saved.connector.clone());+ let slot = Slot { id, name, connector, node: Arc::new(node) };hub.network.slots.locked().push(slot.clone());tokio::spawn(watch(hub.clone(), slot.node.changes()));publish(hub);@@ -287,8 +312,9 @@ async fn watch(hub: Arc<Hub>, mut changes: tokio::sync::watch::Receiver<()>) {}}-/// Offers this computer's visible bots to every network, under their address names. Called-/// after every change to a bot's name, description or visibility.+/// Offers this computer's visible bots to every network, under their address names, except those+/// kept off it, which only send. Called after every change to a bot's name, description,+/// visibility or network switch.pub fn publish(hub: &Hub) {let slots = hub.network.slots();if slots.is_empty() {@@ -313,15 +339,17 @@ pub fn publish(hub: &Hub) {{tracing::warn!(error = format!("{error:#}"), "couldn't save the bots' address names");}- let agents: Vec<(Agent, Reach)> = bots- .iter()- .filter(|b| b.offered_to_network)+ let (offered, kept_off): (Vec<_>, Vec<_>) = bots.iter().partition(|b| b.offered_to_network);+ let agents: Vec<(Agent, Reach)> = offered+ .into_iter().filter_map(|b| {let id = handles.handle(&b.id)?;Some((Agent { id, name: b.name.clone(), about: b.description.clone() }, Reach::App))}).collect();+ *hub.network.unoffered.locked() = kept_off.iter().filter_map(|b| handles.handle(&b.id)).collect();drop(handles);+ hub.network.share_senders();for slot in slots {slot.node.set_agents(agents.clone());}@@ -332,3 +360,58 @@ fn default_name() -> String {let host = gethostname::gethostname().to_string_lossy().into_owned();handle(host.split('.').next().unwrap_or("computer"))}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn addresses_split_into_their_parts() {+ assert_eq!(split_address("reviewer"), ("reviewer", None));+ assert_eq!(split_address("reviewer@desk"), ("reviewer", Some(("desk", None))));+ assert_eq!(split_address("[email protected]"), ("reviewer", Some(("desk", Some("home")))));+ assert_eq!(split_computer(&qualified("desk", "home")), ("desk", Some("home")));+ }++ #[tokio::test]+ async fn a_computer_in_two_networks_finds_bots_by_short_addresses() {+ let root = std::env::temp_dir().join(format!("codync-recipient-{}", uuid::Uuid::new_v4()));+ let start = async |folder: &str| Node::start(&root.join(folder), &Connector::Private).await.unwrap().0;+ let offer = |node: &Node, id: &str| {+ node.set_agents([(Agent { id: id.into(), name: id.into(), about: String::new() }, Reach::App)]);+ };+ // This computer is desk in home and in work; each has a computer called laptop.+ let (home, work) = (start("home").await, start("work").await);+ home.create("desk").unwrap();+ work.create("desk").unwrap();+ for (network, folder, agent) in [(&home, "laptop", "lead"), (&work, "other", "tester")] {+ let laptop = start(folder).await;+ offer(&laptop, agent);+ laptop.join(&network.invite().unwrap(), "laptop").await.unwrap();+ network.peers().await.unwrap();+ }+ let network = Network::default();+ let slot = |id: &str, node: Node| Slot {+ id: id.into(),+ name: id.into(),+ connector: Connector::Private,+ node: Arc::new(node),+ };+ network.slots.locked().extend([slot("home", home), slot("work", work)]);++ let there = |name: &str| match network.recipient(name).unwrap() {+ Recipient::There(t) => format!("{}.{}", t.address, t.network),+ Recipient::Here(bot) => format!("here: {bot}"),+ };+ let refused = network.recipient("lead@laptop").err().unwrap().to_string();+ assert!(refused.contains("[email protected] and [email protected]"), "{refused}");+ assert_eq!(there("[email protected]"), "[email protected]");+ assert_eq!(there("tester"), "[email protected]", "only work offers it");+ assert_eq!(there("[email protected]"), "here: [email protected]", "desk is this computer");+ assert_eq!(there("nobody"), "here: nobody", "no network offers it");+ for slot in network.slots() {+ slot.node.shutdown().await;+ }+ let _ = std::fs::remove_dir_all(root);+ }+}diff --git a/host/src/network/saved.rs b/host/src/network/saved.rsindex d73ff8af..e157b0ec 100644--- a/host/src/network/saved.rs+++ b/host/src/network/saved.rs@@ -1,23 +1,25 @@//! The networks this computer is in, as kept between runs: kv `networks`, each with its node's//! folder in the data directory.-use crate::hub::Hub;+use crate::store::Store;use anyhow::{Result, bail};-use codync_network::Rule;+use codync_network::{Connector, Rule};use serde::{Deserialize, Serialize};-use std::path::PathBuf;+use std::path::{Path, PathBuf};const KV: &str = "networks";-/// The folder of the network a computer joined before it could be in several.+/// The folder of the network a computer joined before it could be in several, and its connector.const FIRST: &str = "network";+const FIRST_CONNECTOR: &str = "network_connector";+/// What a network is called when nobody named it.+pub const DEFAULT_NAME: &str = "home";#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]pub struct Saved {/// Its node's folder, and its id in the API.pub id: String,pub name: String,- /// `public`, `private` or a relay URL.- pub connector: String,+ pub connector: Connector,#[serde(default)]pub rules: Vec<Rule>,}@@ -26,56 +28,55 @@ pub fn dir(id: &str) -> PathBuf {crate::service::data_dir().join(id)}-/// The networks to start: kv `networks`, or the one network a computer was in before.-pub fn load(hub: &Hub) -> Vec<Saved> {- if let Some(saved) = hub.store.kv_get(KV).and_then(|v| serde_json::from_str(&v).ok()) {- return saved;- }- if !dir(FIRST).join("network.json").exists() {- return Vec::new();- }- let first = Saved {- id: FIRST.into(),- name: "home".into(),- connector: hub.store.kv_get("network_connector").unwrap_or_else(|| "public".into()),- rules: hub.store.kv_get("network_rules").and_then(|v| serde_json::from_str(&v).ok()).unwrap_or_default(),- };- if let Err(error) = save(hub, std::slice::from_ref(&first)) {- tracing::warn!(error = format!("{error:#}"), "couldn't keep the network's settings");- }- vec![first]+/// The networks this computer is in.+pub fn load(store: &Store) -> Vec<Saved> {+ let Some(text) = store.kv_get(KV) else { return Vec::new() };+ serde_json::from_str(&text).unwrap_or_else(|error| {+ tracing::warn!(error = format!("{error:#}"), "couldn't read the saved networks");+ Vec::new()+ })+}++pub fn save(store: &Store, all: &[Saved]) -> Result<()> {+ store.kv_set(KV, &serde_json::to_string(all)?)}-pub fn save(hub: &Hub, all: &[Saved]) -> Result<()> {- hub.store.kv_set(KV, &serde_json::to_string(all)?)+/// Keeps the one network a computer was in before it could be in several (its folder in `data`,+/// and kv `network_connector`) as `home`. Once, before the first `load`.+pub fn migrate(store: &Store, data: &Path) -> Result<()> {+ if store.kv_get(KV).is_some() || !data.join(FIRST).join("network.json").exists() {+ return Ok(());+ }+ let connector = store.kv_get(FIRST_CONNECTOR).map_or(Ok(Connector::Public), |c| c.parse())?;+ save(store, &[Saved { id: FIRST.into(), name: DEFAULT_NAME.into(), connector, rules: Vec::new() }])?;+ store.kv_delete(FIRST_CONNECTOR)}-/// A folder no network uses yet: `network`, then `network-<random>`.+/// A folder no network uses yet, and no network's name (`Network::slot` takes either):+/// `network`, then `network-<random>`.pub fn new_id(all: &[Saved]) -> String {- if all.iter().all(|s| s.id != FIRST) && !dir(FIRST).exists() {+ let free = |id: &str| all.iter().all(|s| s.id != id && !s.name.eq_ignore_ascii_case(id)) && !dir(id).exists();+ if free(FIRST) {return FIRST.into();}loop {let id = format!("{FIRST}-{}", &uuid::Uuid::new_v4().simple().to_string()[..8]);- if !dir(&id).exists() {+ if free(&id) {return id;}}}/// `name` as a network name (like a computer's: no spaces, `@` or `.`, which addresses use),-/// numbered when another network here has it (`home-2`).+/// numbered when another network here has it, or has it as its id (`home-2`).pub fn free_name(all: &[Saved], name: &str) -> Result<String> {let name = super::handle(name.trim());if name.len() > 40 {bail!("a network's name is at most 40 characters");}- let taken = |n: &str| all.iter().any(|s| s.name.eq_ignore_ascii_case(n));- // One more number than there are networks: one of them is free.- Ok(std::iter::once(name.clone())- .chain((2..=all.len() + 2).map(|i| format!("{name}-{i}")))- .find(|n| !taken(n))- .expect("a number is free"))+ let taken = |n: &str| all.iter().any(|s| s.name.eq_ignore_ascii_case(n) || s.id == n);+ // Each network takes two: its name and its id.+ Ok(super::handles::numbered(&name, 2 * all.len(), |n| !taken(n)))}#[cfg(test)]@@ -83,7 +84,7 @@ mod tests {use super::*;fn saved(id: &str, name: &str) -> Saved {- Saved { id: id.into(), name: name.into(), connector: "public".into(), rules: Vec::new() }+ Saved { id: id.into(), name: name.into(), connector: Connector::Public, rules: Vec::new() }}#[test]@@ -92,5 +93,28 @@ mod tests {assert_eq!(free_name(&all, "Work").unwrap(), "work");assert_eq!(free_name(&all, "home").unwrap(), "home-3");assert_eq!(free_name(&all, "my.lab").unwrap(), "my-lab", "no dots: addresses use them");+ assert_eq!(free_name(&all, "network").unwrap(), "network-2", "another network's id");+ }++ #[test]+ fn the_network_a_computer_was_in_before_becomes_home() {+ let data = std::env::temp_dir().join(format!("codync-saved-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(data.join(FIRST)).unwrap();+ let store = Store::open(&data.join("test.db")).unwrap();+ migrate(&store, &data).unwrap();+ assert_eq!(load(&store), [], "no folder with a network in it yet");++ std::fs::write(data.join(FIRST).join("network.json"), "{}").unwrap();+ store.kv_set(FIRST_CONNECTOR, "private").unwrap();+ migrate(&store, &data).unwrap();+ let home = Saved { id: FIRST.into(), name: "home".into(), connector: Connector::Private, rules: Vec::new() };+ assert_eq!(load(&store), std::slice::from_ref(&home));+ assert_eq!(store.kv_get(FIRST_CONNECTOR), None, "kept with the network now");+ // Once: what the user changes later stays.+ save(&store, &[]).unwrap();+ migrate(&store, &data).unwrap();+ assert_eq!(load(&store), []);+ assert!(new_id(&[home]).starts_with("network-"), "the folder is taken");+ let _ = std::fs::remove_dir_all(data);}}diff --git a/host/src/network_cli.rs b/host/src/network_cli.rsindex 70c7d72c..f39fb29a 100644--- a/host/src/network_cli.rs+++ b/host/src/network_cli.rs@@ -110,10 +110,8 @@ fn print_status(v: &Value) {return;}for n in networks {- let me = n["computer"].as_str().unwrap_or_default();- let role = n["role"].as_str().unwrap_or_default();- let name = n["name"].as_str().unwrap_or_default();- println!("{name}: {me} ({role}) · connector {}", n["connector"].as_str().unwrap_or("public"));+ let text = |key: &str| n[key].as_str().unwrap_or_default();+ println!("{}: {} ({}) · connector {}", text("name"), text("computer"), text("role"), text("connector"));for c in n["computers"].as_array().into_iter().flatten() {let state = if c["me"] == true {"this computer"diff --git a/host/src/remote/relay.rs b/host/src/remote/relay.rsindex c51a988b..1ccdb67a 100644--- a/host/src/remote/relay.rs+++ b/host/src/remote/relay.rs@@ -204,6 +204,7 @@ async fn session(hub: &Arc<Hub>, address: &cloud::Address) -> Result<Option<u16>links: HashMap::new(),outs: StreamMap::new(),pulls: JoinSet::new(),+ assistant: JoinSet::new(),held: None,ready: false,retried: false,@@ -263,6 +264,7 @@ async fn session(hub: &Arc<Hub>, address: &cloud::Address) -> Result<Option<u16>// Also without an owner: a claim whose `cloud.changed` never arrived is picked up here._ = poll.tick() => s.pull(),Some(_) = s.pulls.join_next() => s.deliver_held().await?,+ Some(Ok(result)) = s.assistant.join_next() => s.send(&result).await?,}}}@@ -293,6 +295,9 @@ struct Session {outs: StreamMap<String, ReceiverStream<Out>>,/// State pulls in flight; dropped (aborted) with the connection.pulls: JoinSet<()>,+ /// Cloud assistant calls being answered (a listing may wait for the other computers), so+ /// they don't hold up the devices' messages; their `assistant.result` goes out when done.+ assistant: JoinSet<Value>,/// An account device's queued send that arrived before this connection's state pull/// succeeded. The relay sends the next item only after an ack, so there is at most one.held: Option<Value>,@@ -410,8 +415,8 @@ impl Session {}// A private relay has no accounts, so no cloud assistant (§7.9)."assistant.call" if self.address.kind == cloud::RelayKind::Codync => {- let result = crate::chat::team::assistant::answer(&self.hub, &v).await;- self.send(&result).await?;+ let hub = self.hub.clone();+ self.assistant.spawn(async move { crate::chat::team::assistant::answer(&hub, &v).await });}"cloud.changed" => self.pull(),"acl.ok" => {diff --git a/host/src/tui/manage/mod.rs b/host/src/tui/manage/mod.rsindex b5012eff..47a0ad4d 100644--- a/host/src/tui/manage/mod.rs+++ b/host/src/tui/manage/mod.rs@@ -14,6 +14,7 @@ mod market;mod memory;mod network;mod network_rules;+mod network_setup;mod pages;mod replies;mod routines;@@ -24,8 +25,9 @@ pub use analytics::AnalyticsSheet;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::{NetReply, NetworkSheet, Recovery, Step};pub use network_rules::{RuleField, RuleForm};+pub use network_setup::{CONNECTORS, Setup, SetupField};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.rsindex d1d55ab2..eb2b5578 100644--- a/host/src/tui/manage/network.rs+++ b/host/src/tui/manage/network.rs@@ -1,7 +1,7 @@//! 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.+//! inviting, creating or joining another (`network_setup.rs`), 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};use serde_json::{Value, json};@@ -10,14 +10,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.-pub const CONNECTORS: [(&str, &str, &str); 3] = [- ("Public relays", "public", "Direct when it can, through a shared relay otherwise."),- ("Private: direct only", "private", "Same network, Tailscale or a VPN."),- ("Your own relay", "", "An iroh-relay you run."),-];+use super::network_setup::Setup;#[derive(Default)]pub struct NetworkSheet {@@ -39,7 +32,7 @@ pub enum Step {Create(Setup),Join(Setup),/// The recovery code, shown once: only "I saved it" closes it.- Recovery(String),+ Recovery(Recovery),/// A one-time invite (`None` while it comes) and when it stops working.Invite(Option<(String, i64)>),Recover(Editor),@@ -53,65 +46,12 @@ pub enum Step {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,- pub field: SetupField,-}--#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]-pub enum SetupField {- Invite,- #[default]- Network,- Name,- Connector,- Relay,-}--impl Setup {- fn join() -> Self {- Self { field: SetupField::Invite, ..Self::default() }- }-- /// 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::Network, SetupField::Name, SetupField::Connector];- if join {- fields.insert(0, SetupField::Invite);- }- if CONNECTORS[self.connector].1.is_empty() {- fields.push(SetupField::Relay);- }- fields- }-- fn step(&mut self, join: bool, by: isize) {- let fields = self.fields(join);- let i = fields.iter().position(|f| *f == self.field).unwrap_or(0);- self.field = fields[super::super::app::cycle(i, by, fields.len())];- }-- fn connector(&self) -> String {- match CONNECTORS[self.connector].1 {- "" => self.relay.text.trim().to_owned(),- name => name.to_owned(),- }- }-- fn body(&self) -> Value {- 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(),- })- }+/// A new network's recovery code, and whose it is (named from the host's answer: the sheet may+/// not show the new network yet).+pub struct Recovery {+ pub code: String,+ pub network: String,+ pub computer: String,}/// What a network call's answer is for.@@ -164,6 +104,16 @@ impl NetworkSheet {self.view.as_ref().is_some_and(|v| v[flag] == true)}+ /// The shown network's name.+ pub fn name(&self) -> &str {+ self.current().and_then(|n| n["name"].as_str()).unwrap_or_default()+ }++ /// This computer's row in the shown network.+ pub fn me(&self) -> Option<&Value> {+ self.computers().iter().find(|c| c["me"] == true)+ }+pub fn computers(&self) -> &[Value] {self.current().and_then(|n| n["computers"].as_array()).map_or(&[], Vec::as_slice)}@@ -236,7 +186,12 @@ impl App {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());+ let text = |key: &str| v[key].as_str().unwrap_or_default().to_owned();+ n.step = Step::Recovery(Recovery {+ code: text("recoveryCode"),+ network: text("name"),+ computer: text("computer"),+ });}NetReply::Invite => {let code = v["invite"].as_str().unwrap_or_default().to_owned();@@ -264,7 +219,7 @@ impl App {Step::List => return self.network_list_key(n, k),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::Recovery(r) => self.recovery_key(r, 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),@@ -275,16 +230,16 @@ impl App {Some(Overlay::Network(n))}- fn recovery_key(&mut self, code: String, k: KeyEvent) -> Step {+ fn recovery_key(&mut self, r: Recovery, k: KeyEvent) -> Step {match k.code {KeyCode::Char('y') => {- copy(&code);+ copy(&r.code);self.flash("Recovery code copied");- Step::Recovery(code)+ Step::Recovery(r)}// Closed only once the user says they kept it.KeyCode::Char('s') => Step::List,- _ => Step::Recovery(code),+ _ => Step::Recovery(r),}}@@ -395,49 +350,6 @@ impl App {}Some(Overlay::Network(n))}-- /// Keys in the create or join form.- fn setup_key(&mut self, n: &mut NetworkSheet, mut s: Setup, join: bool, k: KeyEvent) -> Step {- match k.code {- KeyCode::Esc => return Step::List,- // Already sent: a second one would only be refused.- KeyCode::Enter if n.busy => {}- KeyCode::Tab | KeyCode::Down => s.step(join, 1),- KeyCode::BackTab | KeyCode::Up => s.step(join, -1),- KeyCode::Left | KeyCode::Right | KeyCode::Char(' ') if s.field == SetupField::Connector => {- let by = if k.code == KeyCode::Left { -1 } else { 1 };- s.connector = super::super::app::cycle(s.connector, by, CONNECTORS.len());- }- KeyCode::Enter => {- if join && s.invite.text.trim().is_empty() {- n.error = Some(tr("Paste the invite from the other computer.").into_owned());- } else if s.connector().is_empty() {- n.error = Some(tr("Enter your relay's address.").into_owned());- } else {- n.busy = true;- n.error = None;- if join {- self.net("networkJoin", s.body(), NetReply::View);- } else {- self.net("networkCreate", s.body(), NetReply::Created);- }- }- }- _ => {- 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,- };- if let Some(e) = editor {- e.key(k);- }- }- }- if join { Step::Join(s) } else { Step::Create(s) }- }}#[cfg(test)]@@ -489,7 +401,7 @@ pub(super) mod tests {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");- n.step = Step::Recovery("1234".into());+ n.step = Step::Recovery(Recovery { code: "1234".into(), network: "home".into(), computer: "desk".into() });let Some(Overlay::Network(n)) = app.network_key(n, key(KeyCode::Esc)) else { panic!("kept open") };assert!(matches!(n.step, Step::Recovery(_)), "esc doesn't skip saving it");let Some(Overlay::Network(n)) = app.network_key(n, key(KeyCode::Char('s'))) else { panic!("kept open") };@@ -499,9 +411,10 @@ pub(super) mod tests {#[tokio::test]async fn a_recovery_code_that_comes_after_the_sheet_closed_opens_it_again() {let mut app = test_app();- app.network_reply(NetReply::Created, Ok(json!({"recoveryCode": "1234"})));+ // Before the `network` event brings the new network: the step names it from the answer.+ app.network_reply(NetReply::Created, Ok(json!({"recoveryCode": "1234", "name": "work", "computer": "desk"})));let Some(Overlay::Network(n)) = app.overlays.last() else { panic!("the sheet is back") };- assert!(matches!(&n.step, Step::Recovery(code) if code == "1234"));+ assert!(matches!(&n.step, Step::Recovery(r) if (r.code.as_str(), r.network.as_str()) == ("1234", "work")));}#[tokio::test]@@ -519,19 +432,4 @@ pub(super) mod tests {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::Network, SetupField::Name, SetupField::Connector]);- s.connector = 2;- 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"], &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.rsindex 16e75489..6a3c8ddd 100644--- a/host/src/tui/manage/network_rules.rs+++ b/host/src/tui/manage/network_rules.rs@@ -67,7 +67,7 @@ impl NetworkSheet {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) {+ if let Some(me) = self.me() {mine.extend(agents_of(me));}Choices { computers, agents, mine }@@ -75,46 +75,34 @@ impl NetworkSheet {/// 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 (computer, agent) = (s(rule, "fromComputer"), s(rule, "fromAgent"));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 on = self+ .computers()+ .iter()+ .find(|c| c["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(computer)));+ let name = on.and_then(|c| agent_name(c, agent)).unwrap_or(agent);+ tr("{bot} on {computer}").replace("{bot}", name).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()- },- ),+ id => self.me().and_then(|me| agent_name(me, id)).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)}}+/// What one of `computer`'s agents is called, by its id.+fn agent_name<'a>(computer: &'a Value, id: &str) -> Option<&'a str> {+ computer["agents"].as_array()?.iter().find(|a| a["id"] == id)?["name"].as_str()+}+fn s(v: &Value, k: &str) -> String {v[k].as_str().unwrap_or_default().to_owned()}diff --git a/host/src/tui/manage/network_setup.rs b/host/src/tui/manage/network_setup.rsnew file mode 100644index 00000000..f0a3791d--- /dev/null+++ b/host/src/tui/manage/network_setup.rs@@ -0,0 +1,142 @@+//! The network sheet's form for creating a network or joining one with an invite.++use crossterm::event::{KeyCode, KeyEvent};+use serde_json::{Value, json};++use super::super::app::{App, Editor, cycle};+use super::super::l10n::tr;+use super::network::{NetReply, NetworkSheet, Step};++/// 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.+pub const CONNECTORS: [(&str, &str, &str); 3] = [+ ("Public relays", "public", "Direct when it can, through a shared relay otherwise."),+ ("Private: direct only", "private", "Same network, Tailscale or a VPN."),+ ("Your own relay", "", "An iroh-relay you run."),+];++/// 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,+ pub field: SetupField,+}++#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]+pub enum SetupField {+ Invite,+ #[default]+ Network,+ Name,+ Connector,+ Relay,+}++impl Setup {+ pub(super) fn join() -> Self {+ Self { field: SetupField::Invite, ..Self::default() }+ }++ /// 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::Network, SetupField::Name, SetupField::Connector];+ if join {+ fields.insert(0, SetupField::Invite);+ }+ if CONNECTORS[self.connector].1.is_empty() {+ fields.push(SetupField::Relay);+ }+ fields+ }++ fn step(&mut self, join: bool, by: isize) {+ let fields = self.fields(join);+ let i = fields.iter().position(|f| *f == self.field).unwrap_or(0);+ self.field = fields[cycle(i, by, fields.len())];+ }++ fn connector(&self) -> String {+ match CONNECTORS[self.connector].1 {+ "" => self.relay.text.trim().to_owned(),+ name => name.to_owned(),+ }+ }++ fn body(&self) -> Value {+ 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(),+ })+ }+}++impl App {+ /// Keys in the create or join form.+ pub(super) fn setup_key(&mut self, n: &mut NetworkSheet, mut s: Setup, join: bool, k: KeyEvent) -> Step {+ match k.code {+ KeyCode::Esc => return Step::List,+ // Already sent: a second one would only be refused.+ KeyCode::Enter if n.busy => {}+ KeyCode::Tab | KeyCode::Down => s.step(join, 1),+ KeyCode::BackTab | KeyCode::Up => s.step(join, -1),+ KeyCode::Left | KeyCode::Right | KeyCode::Char(' ') if s.field == SetupField::Connector => {+ let by = if k.code == KeyCode::Left { -1 } else { 1 };+ s.connector = cycle(s.connector, by, CONNECTORS.len());+ }+ KeyCode::Enter => {+ if join && s.invite.text.trim().is_empty() {+ n.error = Some(tr("Paste the invite from the other computer.").into_owned());+ } else if s.connector().is_empty() {+ n.error = Some(tr("Enter your relay's address.").into_owned());+ } else {+ n.busy = true;+ n.error = None;+ if join {+ self.net("networkJoin", s.body(), NetReply::View);+ } else {+ self.net("networkCreate", s.body(), NetReply::Created);+ }+ }+ }+ _ => {+ 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,+ };+ if let Some(e) = editor {+ e.key(k);+ }+ }+ }+ if join { Step::Join(s) } else { Step::Create(s) }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_relay_url_field_only_for_your_own_relay() {+ let mut s = Setup::join();+ assert_eq!(s.fields(true), [SetupField::Invite, SetupField::Network, SetupField::Name, SetupField::Connector]);+ s.connector = 2;+ 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"], &s.body()["network"]),+ (&Value::Null, &Value::Null),+ "the defaults when left empty"+ );+ }+}diff --git a/host/src/tui/view/network.rs b/host/src/tui/view/network.rsindex aaae8c89..f6519045 100644--- a/host/src/tui/view/network.rs+++ b/host/src/tui/view/network.rs@@ -8,7 +8,7 @@ use serde_json::Value;use super::super::app::Editor;use super::super::l10n::tr;-use super::super::manage::{CONNECTORS, NetworkSheet, Setup, SetupField, Step};+use super::super::manage::{CONNECTORS, NetworkSheet, Recovery, 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};@@ -30,7 +30,7 @@ pub(super) fn network(buf: &mut Buffer, area: Rect, n: &NetworkSheet) {Step::List => list(buf, body, n),Step::Create(s) => setup(buf, body, s, false),Step::Join(s) => setup(buf, body, s, true),- Step::Recovery(code) => recovery(buf, body, n, code),+ Step::Recovery(r) => recovery(buf, body, r),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),@@ -46,18 +46,17 @@ pub(super) fn network(buf: &mut Buffer, area: Rect, n: &NetworkSheet) {put(buf, inner.x, inner.bottom() - 1, inner.width, &format!(" {}", tr(keys)), t.dim.patch(t.panel));}-fn recovery(buf: &mut Buffer, body: Rect, n: &NetworkSheet, code: &str) -> &'static str {+fn recovery(buf: &mut Buffer, body: Rect, r: &Recovery) -> &'static str {let t = theme();let mut y = body.y;line(buf, body, &mut y, &tr("Save your recovery code"), t.bold);y += 1;- line(buf, body, &mut y, code, t.bold);+ line(buf, body, &mut y, &r.code, t.bold);y += 1;- 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, ¬e.replace("{network}", network).replace("{name}", &n.computer()), t.secondary);+ wrapped(buf, body, &mut y, ¬e.replace("{network}", &r.network).replace("{name}", &r.computer), t.secondary);"y copy · s I saved it"}@@ -94,7 +93,7 @@ fn recover(buf: &mut Buffer, body: Rect, code: &Editor) -> &'static str {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();+ let network = n.name();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.",diff --git a/host/src/tui/view/network_rules.rs b/host/src/tui/view/network_rules.rsindex 81b5105a..7ce3d889 100644--- a/host/src/tui/view/network_rules.rs+++ b/host/src/tui/view/network_rules.rs@@ -14,7 +14,8 @@ const FOOTER: &str = "The first rule that matches decides. Without rules, everypub(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);+ // Rules belong to one network: say which.+ line(buf, body, &mut y, &format!("{} · {}", tr("Who may message bots here"), n.name()), t.bold);y += 1;if n.rules().is_empty() {line(diff --git a/host/tests/network_e2e.rs b/host/tests/network_e2e.rsindex a3105b4a..d496c9b4 100644--- a/host/tests/network_e2e.rs+++ b/host/tests/network_e2e.rs@@ -258,6 +258,11 @@ async fn a_bot_kept_off_the_network_and_a_deny_rule_keep_letters_out() {assert!(failed["data"]["botMessage"]["detail"].as_str().unwrap().contains("doesn't take messages"), "{failed}");let history = desk.call("history", json!({"botId": reviewer})).await;assert!(!history.to_string().contains("review this"), "nothing reached the reviewer");++ // Kept off the network, Secret still asks the laptop's lead; the answer gets past the deny rule.+ desk.call("send", json!({"botId": secret, "text": "TRY lead@laptop status?"})).await;+ let answered = desk.wait_for(&secret, exchange("completed")).await;+ assert_eq!(answered["data"]["botMessage"]["reply"], "reply: status?", "{answered}");}#[tokio::test]diff --git a/web/content/docs/bots.mdx b/web/content/docs/bots.mdxindex 7ac23141..4f589ca9 100644--- a/web/content/docs/bots.mdx+++ b/web/content/docs/bots.mdx@@ -70,6 +70,8 @@ How approval cards work: [Conversations](/docs/conversations#approval-cards).- **Notifications:** notify you when this bot finishes, fails or needs you. Turn it off to keep the bot quiet.- **Use the computer:** let this bot see the screen and use the mouse and keyboard. The computer needs Computer access set up first. See [Computer use](/docs/computer-use).- **Manage the team:** let this bot create bots and change any bot's setup, its own included. Bots it creates can do the same, with no more access than it has: they take its approval setting, connectors and skills, and never get computer use. Only you can turn this on, and it's off by default. See [Teamwork](/docs/teamwork).+- **Offered to the network:** shows while the computer is in a network of your computers. Turn it off and your other computers don't list this bot and can't message it; it can still message bots there and get their replies. In the terminal UI it's **Network**. See [Teamwork](/docs/teamwork#choose-who-reaches-your-bots).+- **Reachable by cloud assistants:** shows while cloud assistants are on for the computer. Turn it off and ChatGPT or Claude don't list this bot and can't message it, also when they ask through another of your computers. In the terminal UI it's **Assistants**. See [Cloud assistants](/docs/cloud-assistants).## Connectors and skillsdiff --git a/web/content/docs/cloud-assistants.mdx b/web/content/docs/cloud-assistants.mdxindex 3f9ce723..f55c5447 100644--- a/web/content/docs/cloud-assistants.mdx+++ b/web/content/docs/cloud-assistants.mdx@@ -37,7 +37,7 @@ In the bot's chat, the request shows as a row saying **Message from Cloud assist- **The computer needs Codync 2.28.0 or later.** An older one doesn't answer the assistant.- **Turned on at the computer.** The desktop app, the terminal UI or `codync-host` changes it; phones only show it.-- **Only through computers in your Codync account that use the Codync relay.** A computer that uses your own relay can't be reached directly. Through one that can, the assistant also reaches the bots your other computers offer in your [network of computers](/docs/teamwork#bots-on-your-other-computers), as `name@computer`; each of those computers decides with its own rules whether it takes the message.+- **Only through computers in your Codync account that use the Codync relay.** A computer that uses your own relay can't be reached directly. Through one that can, the assistant also reaches the bots your other computers offer in your [network of computers](/docs/teamwork#bots-on-your-other-computers), as `name@computer`; each of those computers decides with its own rules, its Cloud assistants switch and each bot's **Reachable by cloud assistants** whether it takes the message.- **No hidden bots or group chats.** The assistant sees the same bots another bot can message.- **It can't be told when a reply is ready.** A hosted assistant only acts when you write to it, so ask it to check on the task later.- **Replies don't last.** The computer keeps the newest 50 requests, at most 16 of them running at once, and forgets them all when Codync restarts.diff --git a/web/content/docs/teamwork.mdx b/web/content/docs/teamwork.mdxindex 67a69afe..17fc6603 100644--- a/web/content/docs/teamwork.mdx+++ b/web/content/docs/teamwork.mdx@@ -84,8 +84,8 @@ Once your computers are in the network, nothing else changes for your bots. A boEach 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.+- **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. It can still message bots there and get their replies. 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. The answer to a request a bot here sent still gets in, from the computer it asked. Phones show the rules but don't change them.### Agents that aren't Codync bots