Skip to content

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

fix(apps): review fixes for the network screens

leepokai1a88de8d4106
diff --git a/apps/android/WhatsNew.md b/apps/android/WhatsNew.md
index 98748716..ace1bdd2 100644
--- a/apps/android/WhatsNew.md
+++ b/apps/android/WhatsNew.md
@@ -7,6 +7,14 @@ released version's section; a version without one gets the PRs' "What's New: And
else a generic "Bug fixes and improvements" line. Delete old sections.
-->
+## 2.29.0
+
+### zh-Hant
+- 設定裡每台電腦多了網路按鈕:看網路裡的電腦、是否在線、提供哪些 Bot,以及雲端助理是否開啟。
+
+### en-US
+- A network button on each computer in Settings shows your network's computers, whether each answers, its bots, and whether cloud assistants are on.
+
## 2.28.0
### zh-Hant
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt
index 8d5e27cf..7b4b90c9 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreConnection.kt
@@ -136,7 +136,6 @@ fun AppStore.connect() {
reconcileMailbox(active)
acknowledgeVisible()
syncPush()
- loadNetwork(active)
while (isActive) {
if (state.value.mismatch != null) { awaitUpdate(active); continue }
val cursor = withContext(Dispatchers.IO) { requireNotNull(database).revision() }
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreNetwork.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreNetwork.kt
index 54fa78e7..876b8636 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreNetwork.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreNetwork.kt
@@ -3,18 +3,29 @@ package com.codync.android
import com.codync.android.core.*
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
-// The computer's network as this phone sees it: read-only, fetched when the link is up, kept current by its event.
+// The computer's network as this phone sees it: read-only, from the stream's hello, kept current by its event.
-/** `networkView` once the link is up; a host that predates it (or can't answer) leaves it unset, so nothing shows. */
-internal suspend fun AppStore.loadNetwork(active: EncryptedChannel) {
- val view = try { NetworkView.decode(active.call("networkView")) }
- catch (cancelled: CancellationException) { throw cancelled }
- catch (_: Exception) { null }
- mutableState.update { it.copy(network = view) }
+/**
+ * Reads `networkView` again (the sheet opening): the host asks the other computers when what it heard is stale, and
+ * the `network` event brings what they answer. A failed read keeps what is shown.
+ */
+internal fun AppStore.refreshNetwork() {
+ val active = channel?.takeIf { it.state.value is LinkState.Ready } ?: return
+ contextScope.launch {
+ val view = try { NetworkView.decode(active.call("networkView")) }
+ catch (cancelled: CancellationException) { throw cancelled }
+ catch (error: Exception) { android.util.Log.i("Codync", "Network view failed: ${error.message}"); return@launch }
+ mutableState.update { it.copy(network = view) }
+ }
}
+/** The stream's hello carries the view (null from hosts before it); `network` events change it. */
internal fun AppStore.receiveNetwork(events: List<MirrorEvent>) {
- val view = events.filterIsInstance<MirrorEvent.Network>().lastOrNull()?.view ?: return
- mutableState.update { it.copy(network = view) }
+ when (val last = events.lastOrNull { it is MirrorEvent.Hello || it is MirrorEvent.Network }) {
+ is MirrorEvent.Hello -> mutableState.update { it.copy(network = last.network) }
+ is MirrorEvent.Network -> mutableState.update { it.copy(network = last.view) }
+ else -> {}
+ }
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/NetworkSheet.kt b/apps/android/app/src/main/kotlin/com/codync/android/NetworkSheet.kt
index 4969b799..071607c5 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
@@ -7,9 +7,12 @@ import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
@@ -24,15 +27,21 @@ import com.kyant.shapes.Capsule
* The paired computer's network, read-only (iOS `NetworkSheet`): the computers in it with the bots each offers, and
* whether cloud assistants may reach its bots. Who is in is changed on a computer.
*/
-@Composable internal fun NetworkSheet(view: NetworkView) {
+@Composable internal fun NetworkSheet(view: NetworkView, refresh: () -> Unit) {
AnalyticsOnAppear(AnalyticsEvent.ScreenViewed(AnalyticsScreen.Network))
+ // Presence as of now: the host asks the others when stale, and its event updates this.
+ LaunchedEffect(Unit) { refresh() }
Column(Modifier.fillMaxSize().background(Palette.background)) {
- ModalHeader("Network")
+ ModalHeader({
+ Symbol("point.3.connected.trianglepath.dotted", size = 24.dp, tint = Palette.text)
+ Spacer(Modifier.width(8.dp))
+ Text(tr("Network"), style = Type.body.semibold, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ })
CardForm {
if (view.joined) CardSection("Computers", "Changes are made on a computer: in Codync's settings there, or with codync-host network.") {
for (computer in view.computers) row { NetworkComputerRow(computer) }
}
- 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.") {
+ 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") }
}
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.kt b/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.kt
index b7fe84b5..aa36ab28 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/SettingsView.kt
@@ -154,7 +154,7 @@ import kotlinx.serialization.json.put
} }
}
CodyncSheet(voice, { voice = false }) { VoiceChatSettings(state, store) }
- CodyncSheet(network, { network = false }) { state.network?.let { NetworkSheet(it) } }
+ CodyncSheet(network, { network = false }) { state.network?.let { NetworkSheet(it, store::refreshNetwork) } }
SwatchPanel(coloring, paired?.color, { coloring = false }, store::setColor)
CodyncSheet(aboutAnalytics, { aboutAnalytics = false }) { AnalyticsSheet() }
CodyncDialog("Start over?", confirmStartOver, { confirmStartOver = false },
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt
index c5279c5c..fbd7e554 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt
@@ -149,7 +149,8 @@ data class PendingSend(
data class OutgoingFile(val path: String, val name: String, val size: Long)
sealed interface MirrorEvent {
- data class Hello(val hostId: String, val rev: Long, val usage: JsonObject, val screen: JsonObject?) : MirrorEvent
+ /** The stream's first event; `network` is null from hosts before the network view (or one this app can't read). */
+ data class Hello(val hostId: String, val rev: Long, val usage: JsonObject, val screen: JsonObject?, val network: NetworkView? = null) : MirrorEvent
data class BotChanged(val bot: Bot) : MirrorEvent
data class EntryChanged(val entry: Entry) : MirrorEvent
data class Usage(val value: JsonObject) : MirrorEvent
@@ -167,7 +168,8 @@ sealed interface MirrorEvent {
fun decode(value: JsonObject): MirrorEvent = when (value.text("type")) {
"hello" -> Hello(requireNotNull(value.text("hostId")),
requireNotNull(value["rev"]?.jsonPrimitive?.longOrNull),
- value["usage"]?.jsonObject ?: JsonObject(emptyMap()), value["screen"]?.takeUnless { it == JsonNull }?.jsonObject)
+ value["usage"]?.jsonObject ?: JsonObject(emptyMap()), value["screen"]?.takeUnless { it == JsonNull }?.jsonObject,
+ value["network"]?.takeUnless { it == JsonNull }?.let { runCatching { NetworkView.decode(it) }.getOrNull() })
"bot" -> BotChanged(HostClient.decode(value.getValue("bot").jsonObject))
"entry" -> EntryChanged(Entry.decode(value.getValue("entry").jsonObject))
"usage" -> Usage(value.getValue("usage").jsonObject)
@@ -175,7 +177,7 @@ sealed interface MirrorEvent {
// One this app can't read is passed over rather than fetching everything again: a card or the Library reads it again.
"artifact" -> runCatching { ArtifactChanged(Artifact.decode(value.getValue("artifact"))) }.getOrDefault(Ignored)
"call" -> CallCue.decode(value)?.let(::Call) ?: Ignored
- // One this app can't read is passed over: the sheet reads `networkView` when the link comes back.
+ // One this app can't read is passed over: the next stream's hello carries the view again.
"network" -> runCatching { Network(NetworkView.decode(value.getValue("network"))) }.getOrDefault(Ignored)
"resync" -> Resync
// Match the existing clients: unknown events do not advance the cursor.
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Network.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Network.kt
index 8fc543a5..479fd9a3 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
@@ -14,10 +14,12 @@ data class NetworkView(
/** This computer's name in the network. */
val computer: String? = null,
val assistants: Boolean = false,
+ /** Cloud assistants can reach this computer at all: it's in a Codync account. */
+ val assistantsAvailable: Boolean = false,
val computers: List<NetworkComputer> = emptyList(),
) {
- /** Something to show: the network, or cloud assistants turned on. */
- val shown: Boolean get() = joined || assistants
+ /** Something to show: the network, or cloud assistants that can reach this computer's bots. */
+ val shown: Boolean get() = joined || (assistantsAvailable && assistants)
companion object {
fun decode(value: JsonElement): NetworkView = WireJson.decodeFromJsonElement(value)
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/NetworkTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/NetworkTest.kt
index a91a7d66..4d3d5265 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/NetworkTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/NetworkTest.kt
@@ -6,11 +6,11 @@ import org.junit.Test
class NetworkTest {
private val view = WireJson.parseToJsonElement("""
- {"joined": true, "computer": "desk", "role": "owner", "connector": "public", "assistants": false,
+ {"joined": true, "computer": "desk", "role": "owner", "connector": "public", "assistants": false, "assistantsAvailable": true,
"computers": [
- {"name": "desk", "role": "owner", "me": true, "online": true, "bots": ["reviewer"],
+ {"name": "desk", "role": "owner", "me": true, "online": true,
"agents": [{"id": "reviewer", "name": "Reviewer"}], "canRemove": false, "canPromote": false},
- {"name": "laptop", "role": "admin", "me": false, "online": false, "bots": [], "agents": [],
+ {"name": "laptop", "role": "admin", "me": false, "online": false, "agents": [],
"canRemove": true, "canPromote": false, "later": 1}]}
""")
@@ -23,9 +23,20 @@ class NetworkTest {
assertEquals(listOf(NetworkAgent("reviewer", "Reviewer")), read.computers[0].agents)
}
- @Test fun `a computer in no network shows only when cloud assistants are on`() {
- assertFalse(NetworkView.decode(buildJsonObject { put("joined", false); put("assistants", false) }).shown)
- assertTrue(NetworkView.decode(buildJsonObject { put("joined", false); put("assistants", true) }).shown)
+ @Test fun `a computer in no network shows only when cloud assistants can reach it and are on`() {
+ fun alone(on: Boolean, available: Boolean) =
+ NetworkView.decode(buildJsonObject { put("joined", false); put("assistants", on); put("assistantsAvailable", available) })
+ assertFalse(alone(on = false, available = true).shown)
+ assertFalse("not in an account", alone(on = true, available = false).shown)
+ assertTrue(alone(on = true, available = true).shown)
+ }
+
+ @Test fun `the stream's hello carries the network, and hosts before it none`() {
+ fun hello(network: JsonElement?) = MirrorEvent.decode(buildJsonObject {
+ put("type", "hello"); put("hostId", "h"); put("rev", 1); network?.let { put("network", it) }
+ }) as MirrorEvent.Hello
+ assertEquals("desk", hello(view).network?.computer)
+ assertNull(hello(null).network)
}
@Test fun `the network event is live state, and one this app can't read is passed over`() {
diff --git a/apps/desktop/src/renderer/client/host-client.ts b/apps/desktop/src/renderer/client/host-client.ts
index 276e4031..cef2f5b4 100644
--- a/apps/desktop/src/renderer/client/host-client.ts
+++ b/apps/desktop/src/renderer/client/host-client.ts
@@ -5,7 +5,6 @@ import {
type AccessRequest,
type Bot,
type CloudStatus,
- type NetworkView,
type Entry,
type Hello,
type ScreenState,
@@ -13,6 +12,7 @@ import {
} from '@shared/models'
import type { Artifact, ArtifactChunk, LibraryItem } from '@shared/artifacts'
import { parseCallCue, type CallCue } from '@shared/calls'
+import type { NetworkView } from '@shared/network'
/** How a client reaches a host API. Only loopback today: the computer's own host or an SSH tunnel. */
export type HostRoute = 'loopback' | 'direct' | 'relay'
@@ -64,7 +64,8 @@ export class LoopbackTransport implements HostTransport {
}
export type HostEvent =
- | { type: 'hello'; hostId: string; rev: number; usage: Usage; screen: ScreenState | null }
+ /** `network` is null from hosts before the network view. */
+ | { type: 'hello'; hostId: string; rev: number; usage: Usage; screen: ScreenState | null; network: NetworkView | null }
| { type: 'bot'; bot: Bot }
| { type: 'botDeleted'; id: string; rev: number }
| { type: 'entry'; entry: Entry }
@@ -98,6 +99,7 @@ export function parseEvent(line: string): HostEvent | null {
rev: (raw.rev as number) ?? 0,
usage: (raw.usage as Usage) ?? { providers: [] },
screen: normalizeScreen(raw.screen as ScreenState | undefined),
+ network: (raw.network as NetworkView | undefined) ?? null,
}
case 'bot': {
const bot = raw.bot as (Bot & { deleted?: boolean }) | undefined
diff --git a/apps/desktop/src/renderer/lib/network-copy.test.ts b/apps/desktop/src/renderer/lib/network-copy.test.ts
index 39b9b41d..8c479fc1 100644
--- a/apps/desktop/src/renderer/lib/network-copy.test.ts
+++ b/apps/desktop/src/renderer/lib/network-copy.test.ts
@@ -1,7 +1,7 @@
import assert from 'node:assert/strict'
import test from 'node:test'
-import type { NetworkComputer } from '@shared/models'
-import { botsTemplate, canInvite, canRecover, connectorFor, presenceTitle } from './network-copy.ts'
+import type { NetworkComputer } from '@shared/network'
+import { botsTemplate, connectorFor, presenceTitle } from './network-copy.ts'
const computer = (c: Partial<NetworkComputer>): NetworkComputer => ({
name: 'laptop', role: 'member', me: false, online: false, agents: [], canRemove: false, canPromote: false, ...c,
@@ -21,8 +21,3 @@ test('rows say where each computer is and how many bots it offers', () => {
assert.equal(botsTemplate(computer({ agents: [{ id: 'a', name: 'A' }] })), '1 bot')
assert.equal(botsTemplate(computer({})), '{count} bots')
})
-
-test('the owner and admins invite; everyone but the owner may recover', () => {
- assert.deepEqual([canInvite('owner'), canInvite('admin'), canInvite('member')], [true, true, false])
- assert.deepEqual([canRecover('owner'), canRecover('admin'), canRecover(null)], [false, true, true])
-})
diff --git a/apps/desktop/src/renderer/lib/network-copy.ts b/apps/desktop/src/renderer/lib/network-copy.ts
index 6c52ea8e..cc3dbd9a 100644
--- a/apps/desktop/src/renderer/lib/network-copy.ts
+++ b/apps/desktop/src/renderer/lib/network-copy.ts
@@ -1,6 +1,6 @@
/** What the Network section says about this computer's network (codync-network). */
-import type { NetworkComputer, NetworkRole } from '@shared/models'
+import type { NetworkComputer, NetworkRole } from '@shared/network'
/** How computers reach each other without a direct path. */
export type ConnectorChoice = 'public' | 'private' | 'relay'
@@ -25,9 +25,5 @@ export const presenceTitle = (c: NetworkComputer) => (c.me ? 'This computer' : c
/** "3 bots", untranslated template first: the caller translates, then puts the count in. */
export const botsTemplate = (c: NetworkComputer) => (c.agents.length === 1 ? '1 bot' : '{count} bots')
-/** The owner and admins invite; whoever isn't the owner may take ownership with the recovery code. */
-export const canInvite = (role: NetworkRole | null | undefined) => role === 'owner' || role === 'admin'
-export const canRecover = (role: NetworkRole | null | undefined) => role !== 'owner'
-
/** "3:27 PM" for an invite's expiry (Unix ms). */
export const expiryTime = (expiresAt: number) => new Date(expiresAt).toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' })
diff --git a/apps/desktop/src/renderer/store/bot-mirror.ts b/apps/desktop/src/renderer/store/bot-mirror.ts
index 7e05a394..8a79e509 100644
--- a/apps/desktop/src/renderer/store/bot-mirror.ts
+++ b/apps/desktop/src/renderer/store/bot-mirror.ts
@@ -6,10 +6,10 @@ import {
type Computer,
type Entry,
type Hello,
- type NetworkView,
type ScreenState,
type Usage,
} from '@shared/models'
+import type { NetworkView } from '@shared/network'
import type { HostClient, HostRoute, HostTransport } from '../client/host-client'
import { rosterOrder } from '../lib/computer-roster'
import { offerHostUpdate, type HostUpdate, type HostUpdateOffer } from '../lib/host-update'
@@ -46,6 +46,8 @@ export class BotMirror extends Observable {
cloud: CloudStatus | null = null
/** This computer's network; null until known, and on hosts without `networkView`. */
network: NetworkView | null = null
+ /** A new network's recovery code until the user says they saved it: the host keeps it nowhere. */
+ recoveryCode: string | null = null
historyComplete = new Set<string>()
routineDrafts = new Map<string, string>()
readonly composerDrafts: ComposerDrafts
@@ -208,6 +210,11 @@ export class BotMirror extends Observable {
this.changed()
}
+ setRecoveryCode(code: string | null) {
+ this.recoveryCode = code
+ this.changed()
+ }
+
// MARK: cache (instant launch, offline reading)
private get cacheKey() {
diff --git a/apps/desktop/src/renderer/store/bot-sync.ts b/apps/desktop/src/renderer/store/bot-sync.ts
index f4883db0..31c2c8d9 100644
--- a/apps/desktop/src/renderer/store/bot-sync.ts
+++ b/apps/desktop/src/renderer/store/bot-sync.ts
@@ -1,4 +1,4 @@
-import { isChat, type AccessRequest, type CloudStatus, type Entry, type NetworkView } from '@shared/models'
+import { isChat, type AccessRequest, type CloudStatus, type Entry } from '@shared/models'
import { isOutsideLoadedWindow, snapshotFloors } from '@shared/mirror-window'
import { HostClient, HostError, type HostEvent } from '../client/host-client'
import { BotMirror, type Connection } from './bot-mirror'
@@ -134,12 +134,6 @@ export class BotSync extends BotMirror {
try {
this.cloud = await client.call<CloudStatus>('cloudStatus')
} catch {}
- try {
- this.network = await client.call<NetworkView>('networkView')
- } catch {
- // Hosts before the network screens don't have it: no Network section.
- this.network = null
- }
this.changed()
}
if (!alive()) return
@@ -208,6 +202,7 @@ export class BotSync extends BotMirror {
this.hostId = event.hostId
this.usage = event.usage
this.screen = event.screen
+ this.network = event.network
if (event.rev < this.rev) this.rev = 0
this.floors = snapshotFloors(this.entries, this.rev === 0 ? 0 : this.requestedSince)
break
diff --git a/apps/desktop/src/renderer/store/cloud.ts b/apps/desktop/src/renderer/store/cloud.ts
index 938c4300..602bbf16 100644
--- a/apps/desktop/src/renderer/store/cloud.ts
+++ b/apps/desktop/src/renderer/store/cloud.ts
@@ -302,6 +302,15 @@ export class CloudModel extends Observable {
}
}
+ /** Whether the user's cloud assistant may message this computer's bots (the host's `cloud` event follows). */
+ async setAssistants(store: BotStore, enabled: boolean) {
+ try {
+ await (await store.ready()).call<CloudStatus>('setAssistants', { enabled })
+ } catch (error) {
+ this.fail(error)
+ }
+ }
+
/** The host's cloud comes with its build; this only turns it on. */
private async enableCloud(store: BotStore) {
return (await store.ready()).call<CloudStatus>('setCloud', { enabled: true }, 30_000)
diff --git a/apps/desktop/src/renderer/store/network.ts b/apps/desktop/src/renderer/store/network.ts
index f593e420..995416d6 100644
--- a/apps/desktop/src/renderer/store/network.ts
+++ b/apps/desktop/src/renderer/store/network.ts
@@ -1,4 +1,4 @@
-import type { CloudStatus, NetworkView } from '@shared/models'
+import type { NetworkView } from '@shared/network'
import type { BotStore } from './bot-store'
/**
@@ -33,14 +33,16 @@ async function changing<T>(store: BotStore, work: () => Promise<T>): Promise<T>
export const network = {
/** Asks every computer now. */
peers: (store: BotStore) => changing(store, () => call(store, 'networkPeers', {}, SLOW)),
- /** Returns the recovery code: show it once, keep it nowhere. */
+ /** Keeps the recovery code on the store until the user says they saved it, wherever they went meanwhile. */
create: (store: BotStore, name: string, connector: string) =>
- changing(store, async () => (await call<{ recoveryCode: string }>(store, 'networkCreate', { name: name.trim() || null, connector }, SLOW)).recoveryCode),
+ changing(store, async () => {
+ const { recoveryCode } = await call<{ recoveryCode: string }>(store, 'networkCreate', { name: name.trim() || null, connector }, SLOW)
+ store.setRecoveryCode(recoveryCode)
+ }),
join: (store: BotStore, invite: string, name: string, connector: string) =>
changing(store, () => call(store, 'networkJoin', { invite: invite.trim(), name: name.trim() || null, connector }, SLOW)),
invite: (store: BotStore) => call<{ invite: string; expiresAt: number }>(store, 'networkInvite'),
promote: (store: BotStore, computer: string) => changing(store, () => call(store, 'networkPromote', { computer })),
remove: (store: BotStore, computer: string, cascade: boolean) => changing(store, () => call(store, 'networkRemove', { computer, cascade })),
recover: (store: BotStore, code: string) => changing(store, () => call(store, 'networkRecover', { code: code.trim() })),
- setAssistants: (store: BotStore, enabled: boolean) => changing(store, () => call<CloudStatus>(store, 'setAssistants', { enabled })),
}
diff --git a/apps/desktop/src/renderer/views/settings/ComputersView.tsx b/apps/desktop/src/renderer/views/settings/ComputersView.tsx
index 9ab33de0..149e869c 100644
--- a/apps/desktop/src/renderer/views/settings/ComputersView.tsx
+++ b/apps/desktop/src/renderer/views/settings/ComputersView.tsx
@@ -14,7 +14,7 @@ import { StoreContext, useApp } from '../../store/context'
import { ComputerBadge } from '../ComputerBadge'
import { PairingCode } from '../PairingCode'
import { AuthorizedDevicesSection } from './AuthorizedDevicesSection'
-import { AssistantsSwitch, NetworkSection } from './NetworkSection'
+import { NetworkSection } from './NetworkSection'
import { cloudStatusLine } from '../../lib/relay-copy'
import { useTr } from '../../lib/use-language'
import { errorText, liveClient, relativeDay, SectionHeader, statusText, thisMac } from './parts'
@@ -216,8 +216,21 @@ function ManagedComputerCard({ store, ssh: overSSH }: { store: BotStore; ssh: bo
</Text>
</span>
</Switch>,
- // Hosts before 2.28.0 have no cloud assistants.
- ...(cloud?.assistants != null ? [<AssistantsSwitch key="assistants" store={store} disabled={busy || !manageable} />] : []),
+ // Hosts before 2.28.0 have no cloud assistants. The cloud reads these calls, so the computer decides.
+ ...(cloud?.assistants != null
+ ? [
+ <Switch key="assistants" on={cloud.assistants} disabled={busy || !manageable} onChange={(on) => run(() => app.cloud.setAssistants(store, on))}>
+ <span className="settings-stack settings-appear">
+ <Text>{tr(`Cloud assistants`)}</Text>
+ <Text size="caption" tone={cloud.assistants ? 'attention' : 'secondary'}>
+ {cloud.assistants
+ ? tr(`ChatGPT or Claude in your Codync account can message this computer's bots. Codync's cloud can read these calls.`)
+ : tr(`Let ChatGPT or Claude message this computer's bots through your Codync account.`)}
+ </Text>
+ </span>
+ </Switch>,
+ ]
+ : []),
]
: []),
]}
diff --git a/apps/desktop/src/renderer/views/settings/NetworkSection.tsx b/apps/desktop/src/renderer/views/settings/NetworkSection.tsx
index 915a63fd..944a091a 100644
--- a/apps/desktop/src/renderer/views/settings/NetworkSection.tsx
+++ b/apps/desktop/src/renderer/views/settings/NetworkSection.tsx
@@ -1,11 +1,11 @@
import { useEffect, useState } from 'react'
-import type { NetworkComputer } from '@shared/models'
-import { Button, CardSection, IconButton, Switch } from '../../components/Controls'
+import type { NetworkComputer } from '@shared/network'
+import { Button, CardSection, IconButton } from '../../components/Controls'
import { Dialog, Sheet } from '../../components/Overlay'
import { HStack, VStack } from '../../components/Stack'
import { Text } from '../../components/Text'
import { useModel } from '../../lib/observable'
-import { botsTemplate, canInvite, canRecover, presenceTitle, roleTitle } from '../../lib/network-copy'
+import { botsTemplate, presenceTitle, roleTitle } from '../../lib/network-copy'
import { useTr } from '../../lib/use-language'
import type { BotStore } from '../../store/bot-store'
import { network, refreshNetwork } from '../../store/network'
@@ -24,7 +24,6 @@ export function NetworkSection({ store }: { store: BotStore }) {
const tr = useTr()
useModel(store)
const [open, setOpen] = useState<Open | null>(null)
- const [recoveryCode, setRecoveryCode] = useState<string | null>(null)
const [removing, setRemoving] = useState<NetworkComputer | null>(null)
const [busy, setBusy] = useState(false)
const view = store.network
@@ -46,8 +45,8 @@ export function NetworkSection({ store }: { store: BotStore }) {
const accessory = view.joined ? (
<HStack gap={2}>
- {canInvite(view.role) ? <IconButton title="Invite a computer" icon="person.crop.circle.badge.plus" disabled={!manageable} onClick={() => setOpen('invite')} /> : null}
- {canRecover(view.role) ? <IconButton title="Recover ownership" icon="key" disabled={!manageable} onClick={() => setOpen('recover')} /> : null}
+ {view.canInvite ? <IconButton title="Invite a computer" icon="person.crop.circle.badge.plus" disabled={!manageable} onClick={() => setOpen('invite')} /> : null}
+ {view.canRecover ? <IconButton title="Recover ownership" icon="key" disabled={!manageable} onClick={() => setOpen('recover')} /> : null}
<IconButton title="Refresh" icon="arrow.clockwise" disabled={busy || !manageable} onClick={() => run(() => network.peers(store))} />
</HStack>
) : null
@@ -77,7 +76,7 @@ export function NetworkSection({ store }: { store: BotStore }) {
</CardSection>
<Sheet open={open === 'create' || open === 'join'} onClose={() => setOpen(null)}>
- <NetworkSetupSheet key={open} store={store} joining={open === 'join'} created={setRecoveryCode} />
+ <NetworkSetupSheet key={open} store={store} joining={open === 'join'} />
</Sheet>
<Sheet open={open === 'invite'} onClose={() => setOpen(null)}>
<InviteSheet store={store} />
@@ -86,8 +85,8 @@ export function NetworkSection({ store }: { store: BotStore }) {
<RecoverSheet store={store} />
</Sheet>
{/* Escape and the dim don't close it: only "I saved it" does. */}
- <Sheet open={recoveryCode !== null} onClose={() => {}}>
- {recoveryCode ? <RecoveryCodeSheet code={recoveryCode} name={store.hostName} done={() => setRecoveryCode(null)} /> : null}
+ <Sheet open={store.recoveryCode !== null} onClose={() => {}}>
+ {store.recoveryCode ? <RecoveryCodeSheet code={store.recoveryCode} name={store.network?.computer ?? store.hostName} done={() => store.setRecoveryCode(null)} /> : null}
</Sheet>
<Dialog
open={removing !== null}
@@ -123,32 +122,3 @@ function ComputerRow({ computer: c, disabled, promote, remove }: { computer: Net
</HStack>
)
}
-
-/**
- * Whether the user's cloud assistant may message this computer's bots. The cloud reads these
- * calls, so the computer decides; shown only for a computer in the account (a private relay has none).
- */
-export function AssistantsSwitch({ store, disabled }: { store: BotStore; disabled: boolean }) {
- const tr = useTr()
- const on = store.cloud?.assistants === true
- const [busy, setBusy] = useState(false)
- const set = (enabled: boolean) => {
- setBusy(true)
- network
- .setAssistants(store, enabled)
- .catch((e: unknown) => store.setError(errorText(e)))
- .finally(() => setBusy(false))
- }
- return (
- <Switch on={on} disabled={disabled || busy} onChange={set}>
- <span className="settings-stack settings-appear">
- <Text>{tr(`Cloud assistants`)}</Text>
- <Text size="caption" tone={on ? 'attention' : 'secondary'}>
- {on
- ? tr(`ChatGPT or Claude in your Codync account can message this computer's bots. Codync's cloud can read these calls.`)
- : tr(`Let ChatGPT or Claude message this computer's bots through your Codync account.`)}
- </Text>
- </span>
- </Switch>
- )
-}
diff --git a/apps/desktop/src/renderer/views/settings/NetworkSheets.tsx b/apps/desktop/src/renderer/views/settings/NetworkSheets.tsx
index e77a8d39..bc4f722d 100644
--- a/apps/desktop/src/renderer/views/settings/NetworkSheets.tsx
+++ b/apps/desktop/src/renderer/views/settings/NetworkSheets.tsx
@@ -29,7 +29,7 @@ function Field({ label, value, set, placeholder, mono = false }: { label: string
}
/** Create a network (this computer its owner) or join one with an invite. */
-export function NetworkSetupSheet({ store, joining, created }: { store: BotStore; joining: boolean; created: (recoveryCode: string) => void }) {
+export function NetworkSetupSheet({ store, joining }: { store: BotStore; joining: boolean }) {
const tr = useTr()
const dismiss = useDismiss()
const [invite, setInvite] = useState('')
@@ -47,14 +47,9 @@ export function NetworkSetupSheet({ store, joining, created }: { store: BotStore
setBusy(true)
setProblem(null)
try {
- if (joining) {
- await network.join(store, invite, name, connector.connector)
- dismiss()
- } else {
- const code = await network.create(store, name, connector.connector)
- dismiss()
- created(code)
- }
+ if (joining) await network.join(store, invite, name, connector.connector)
+ else await network.create(store, name, connector.connector)
+ dismiss()
} catch (e) {
setProblem(errorText(e))
} finally {
@@ -139,7 +134,7 @@ export function InviteSheet({ store }: { store: BotStore }) {
<IconButton title="Copy invite" icon="doc.on.doc" onClick={() => window.codync.app.copy(invite.invite)} />
</HStack>
<Text size="callout" tone="secondary">
- {tr('One use. Works until {time} while {name} stays on.').replaceAll('{time}', expiryTime(invite.expiresAt)).replaceAll('{name}', store.hostName)}
+ {tr('One use. Works until {time} while {name} stays on.').replaceAll('{time}', expiryTime(invite.expiresAt)).replaceAll('{name}', store.network?.computer ?? store.hostName)}
</Text>
<Text size="callout" tone="secondary">{tr('On the other computer, choose Join with invite under Network.')}</Text>
</>
@@ -160,7 +155,7 @@ export function RecoverSheet({ store }: { store: BotStore }) {
setBusy(true)
try {
await network.recover(store, code)
- setResult({ ok: true, text: tr('{name} is the owner now. Remove the lost computer from the list.').replaceAll('{name}', store.hostName) })
+ setResult({ ok: true, text: tr('{name} is the owner now. Remove the lost computer from the list.').replaceAll('{name}', store.network?.computer ?? store.hostName) })
} catch (e) {
setResult({ ok: false, text: errorText(e) })
} finally {
diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.ts
index 4ae471e8..d718ae62 100644
--- a/apps/desktop/src/shared/models.ts
+++ b/apps/desktop/src/shared/models.ts
@@ -544,33 +544,6 @@ export interface CloudStatus {
assistants?: boolean | null
}
-export type NetworkRole = 'owner' | 'admin' | 'member'
-
-/** A computer in this computer's network (codync-network), as last heard. */
-export interface NetworkComputer {
- name: string
- role: NetworkRole
- /** This computer. */
- me: boolean
- online: boolean
- /** The bots it offers, by name. */
- agents: { id: string; name: string }[]
- /** What this computer may do to it; the host decides. */
- canRemove: boolean
- canPromote: boolean
-}
-
-/** `networkView` and the `network` event: this computer's network, and whether cloud assistants are on. */
-export interface NetworkView {
- joined: boolean
- assistants: boolean
- computer?: string | null
- role?: NetworkRole | null
- /** `public`, `private` or a relay URL. */
- connector?: string | null
- computers?: NetworkComputer[]
-}
-
export interface ClaimSignature {
computerId: string
signKey: string
diff --git a/apps/desktop/src/shared/network.ts b/apps/desktop/src/shared/network.ts
new file mode 100644
index 00000000..1ce43348
--- /dev/null
+++ b/apps/desktop/src/shared/network.ts
@@ -0,0 +1,33 @@
+/** This computer's network of the user's computers (codync-network), as the host describes it. */
+
+export type NetworkRole = 'owner' | 'admin' | 'member'
+
+/** A computer in this computer's network, as last heard. */
+export interface NetworkComputer {
+ name: string
+ role: NetworkRole
+ /** This computer. */
+ me: boolean
+ online: boolean
+ /** The bots it offers, by address name and display name. */
+ agents: { id: string; name: string }[]
+ /** What this computer may do to it; the host decides. */
+ canRemove: boolean
+ canPromote: boolean
+}
+
+/** `networkView`, the `network` event and the stream's hello: this computer's network, and cloud assistants. */
+export interface NetworkView {
+ joined: boolean
+ computer?: string | null
+ role?: NetworkRole | null
+ /** What this computer may do; the host decides. */
+ canInvite?: boolean
+ canRecover?: boolean
+ /** `public`, `private` or a relay URL. */
+ connector?: string | null
+ computers?: NetworkComputer[]
+ assistants: boolean
+ /** Cloud assistants can reach this computer at all: it's in a Codync account. */
+ assistantsAvailable: boolean
+}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift
index 56f97dc1..85842ac5 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift
@@ -1,7 +1,8 @@
import Foundation
public enum HostEvent: Sendable {
- case hello(hostId: String, rev: Int64, usage: Usage, screen: ScreenState?)
+ /// The stream's first event; `network` is nil from hosts before the network view.
+ case hello(hostId: String, rev: Int64, usage: Usage, screen: ScreenState?, network: NetworkView?)
case bot(Bot)
case botDeleted(id: String, rev: Int64)
case entry(Entry)
@@ -110,7 +111,8 @@ public struct HostClient: Sendable {
case "hello":
let usage = (try? d.decode(UsageWrap.self, from: data))?.usage ?? Usage()
let screen = (try? d.decode(ScreenWrap.self, from: data))?.screen
- return .hello(hostId: env.hostId ?? "", rev: env.rev ?? 0, usage: usage, screen: screen)
+ let network = (try? d.decode(NetworkWrap.self, from: data))?.network
+ return .hello(hostId: env.hostId ?? "", rev: env.rev ?? 0, usage: usage, screen: screen, network: network)
case "bot":
if let stub = try? d.decode(StubWrap.self, from: data), stub.bot.deleted == true {
return .botDeleted(id: stub.bot.id, rev: stub.bot.rev)
@@ -128,7 +130,7 @@ public struct HostClient: Sendable {
case "call":
return (try? d.decode(CallCue.self, from: data)).map { .call($0) }
case "network":
- // Not worth a rewind: the next connect asks for the view again.
+ // Not worth a rewind: the next stream's hello carries the view again.
return (try? d.decode(NetworkWrap.self, from: data)).map { .network($0.network) }
case "resync":
return .resync
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Network.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Network.swift
index d82a1d5b..03d160cd 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/Network.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Network.swift
@@ -9,6 +9,8 @@ public struct NetworkView: Codable, Hashable, Sendable {
public var role: Role?
/// The user's cloud assistant may message this computer's bots.
public var assistants: Bool?
+ /// Cloud assistants can reach this computer at all: it's in a Codync account.
+ public var assistantsAvailable: Bool?
public var computers: [Computer]?
public enum Role: String, Codable, Hashable, Sendable {
@@ -43,7 +45,6 @@ public struct NetworkView: Codable, Hashable, Sendable {
public var name: String
}
- public var isAssistantsOn: Bool { assistants ?? false }
- /// Worth showing: in a network, or cloud assistants are on.
- public var hasContent: Bool { joined || isAssistantsOn }
+ /// Worth showing: in a network, or cloud assistants can reach this computer's bots.
+ public var hasContent: Bool { joined || (assistantsAvailable == true && assistants == true) }
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
index 56c1f5a7..a1320919 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
@@ -1313,5 +1313,6 @@
"Only the owner makes plain members admins": "Nur der Eigentümer macht einfache Mitglieder zu Admins",
"Remove this computer from another one": "Entferne diesen Computer von einem anderen aus",
"Only the owner removes admins; admins remove members": "Nur der Eigentümer entfernt Admins; Admins entfernen Mitglieder",
- "Network: your other computers…": "Netzwerk: deine anderen Computer…"
+ "Network: your other computers…": "Netzwerk: deine anderen Computer…",
+ "a switches": "a umschalten"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
index 8e8c0039..53b5561c 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
@@ -1313,5 +1313,6 @@
"Only the owner makes plain members admins": "Solo la propietaria puede hacer administradores a los miembros",
"Remove this computer from another one": "Quita esta computadora desde otra",
"Only the owner removes admins; admins remove members": "Solo la propietaria quita administradores; los administradores quitan miembros",
- "Network: your other computers…": "Red: tus otras computadoras…"
+ "Network: your other computers…": "Red: tus otras computadoras…",
+ "a switches": "a cambiar"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
index e9538c16..118a975e 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
@@ -1313,5 +1313,6 @@
"Only the owner makes plain members admins": "Seul le propriétaire nomme des membres admins",
"Remove this computer from another one": "Retirez cet ordinateur depuis un autre",
"Only the owner removes admins; admins remove members": "Seul le propriétaire retire des admins ; les admins retirent des membres",
- "Network: your other computers…": "Réseau : vos autres ordinateurs…"
+ "Network: your other computers…": "Réseau : vos autres ordinateurs…",
+ "a switches": "a basculer"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
index 79f5d7d9..02bef8b6 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
@@ -1313,5 +1313,6 @@
"Only the owner makes plain members admins": "一般メンバーを管理者にできるのはオーナーだけです",
"Remove this computer from another one": "このコンピューターは別のコンピューターから削除してください",
"Only the owner removes admins; admins remove members": "管理者を削除できるのはオーナーだけで、管理者はメンバーを削除できます",
- "Network: your other computers…": "ネットワーク:ほかのコンピューター…"
+ "Network: your other computers…": "ネットワーク:ほかのコンピューター…",
+ "a switches": "a 切り替え"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
index fc16caea..d515fc07 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
@@ -1313,5 +1313,6 @@
"Only the owner makes plain members admins": "일반 멤버를 관리자로 지정할 수 있는 건 소유자뿐입니다",
"Remove this computer from another one": "이 컴퓨터는 다른 컴퓨터에서 제거하세요",
"Only the owner removes admins; admins remove members": "관리자는 소유자만 제거할 수 있고, 관리자는 멤버를 제거할 수 있습니다",
- "Network: your other computers…": "네트워크: 내 다른 컴퓨터…"
+ "Network: your other computers…": "네트워크: 내 다른 컴퓨터…",
+ "a switches": "a 전환"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
index ebfd4ba8..948d47d7 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
@@ -1313,5 +1313,6 @@
"Only the owner makes plain members admins": "只有所有者能把普通成员设为管理员",
"Remove this computer from another one": "请从另一台电脑移除这台电脑",
"Only the owner removes admins; admins remove members": "只有所有者能移除管理员;管理员能移除成员",
- "Network: your other computers…": "网络:你的其他电脑…"
+ "Network: your other computers…": "网络:你的其他电脑…",
+ "a switches": "a 切换"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
index 41832ea2..196e1fe0 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
@@ -1313,5 +1313,6 @@
"Only the owner makes plain members admins": "只有擁有者能把一般成員設為管理員",
"Remove this computer from another one": "請從另一臺電腦移除這臺電腦",
"Only the owner removes admins; admins remove members": "只有擁有者能移除管理員;管理員能移除成員",
- "Network: your other computers…": "網路:你的其他電腦…"
+ "Network: your other computers…": "網路:你的其他電腦…",
+ "a switches": "a 切換"
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/NetworkSheet.swift b/apps/ios/Kit/Sources/CodyncUI/NetworkSheet.swift
index 0f24dbb9..cb74998d 100644
--- a/apps/ios/Kit/Sources/CodyncUI/NetworkSheet.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/NetworkSheet.swift
@@ -23,13 +23,17 @@ public struct NetworkSheet: View {
ForEach(view.computers ?? []) { NetworkComputerRow(computer: $0) }
}
}
- 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?.isAssistantsOn == true ? "On" : "Off")
+ 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")
+ }
}
}
.animation(Motion.layout, value: store.network)
}
.background(Palette.background)
+ // Presence as of now: the host asks the others when stale, and its event updates this.
+ .task { await store.refreshNetwork() }
.tracked(.screenViewed(.network))
}
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift
index 1cae1bf6..e220ee53 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift
@@ -306,6 +306,13 @@ extension BotStore {
if let u = try? await client.usage(refresh: true), !Task.isCancelled { setUsage(u) }
}
+ /// Reads the network again; the host asks the other computers when what it heard is stale, and
+ /// the `network` event brings what they answer.
+ public func refreshNetwork() async {
+ guard !retired, let client else { return }
+ if let view = try? await client.networkView(), !Task.isCancelled { network = view }
+ }
+
public func loadOlder(_ botId: String) async {
guard let client, !historyComplete.contains(botId) else { return }
let first = chat(botId).first { $0.seq > 0 && $0.seq != Int64.max }?.seq ?? Int64.max
diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift
index 53a77e85..a316b88e 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift
@@ -19,10 +19,6 @@ extension BotStore {
try await Task.sleep(for: hostUpdateOffer() == .updating ? Self.updatingRecheck : Self.mismatchRecheck)
continue
}
- // Hosts before the network view answer "unknown method": nothing to show.
- let view = try? await client.networkView()
- guard !Task.isCancelled, !retired else { return }
- network = view
requestedSince = rev
windowFloors = [:]
for try await event in client.events(since: requestedSince, client: "ios") {
@@ -83,7 +79,7 @@ extension BotStore {
private func apply(_ event: HostEvent) {
switch event {
- case let .hello(id, hostRev, newUsage, newScreen):
+ case let .hello(id, hostRev, newUsage, newScreen, newNetwork):
if let hostId, hostId != id {
// Different host database: start over.
resetMirror()
@@ -91,6 +87,7 @@ extension BotStore {
hostId = id
setUsage(newUsage)
screen = newScreen
+ network = newNetwork
let hostRewound = hostRev < rev
if hostRewound { rev = 0 }
windowFloors = requestedSince > 0 && !hostRewound ? loadedFloors() : [:]
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/CodyncKitTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/CodyncKitTests.swift
index 3a54499c..f716d68c 100644
--- a/apps/ios/Kit/Tests/CodyncKitTests/CodyncKitTests.swift
+++ b/apps/ios/Kit/Tests/CodyncKitTests/CodyncKitTests.swift
@@ -7,8 +7,9 @@ import Testing
let lines = try String(contentsOf: url, encoding: .utf8).split(separator: "\n")
let events = lines.compactMap { HostClient.parseEvent(Data($0.dropFirst(5).utf8)) }
#expect(events.count == 6)
- guard case let .hello(hostId, rev, usage, _) = events[0] else { Issue.record("hello"); return }
+ guard case let .hello(hostId, rev, usage, _, network) = events[0] else { Issue.record("hello"); return }
#expect(hostId == "h1" && rev == 42 && usage.providers.first?.windows.first?.percent == 8)
+ #expect(network == nil, "a host before the network view")
guard case let .bot(bot) = events[1] else { Issue.record("bot"); return }
#expect(bot.name == "Rex" && bot.command == nil && !bot.isWorking)
guard case let .entry(perm) = events[2] else { Issue.record("perm"); return }
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/NetworkTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/NetworkTests.swift
index 6a3b3f0c..c894bfe6 100644
--- a/apps/ios/Kit/Tests/CodyncKitTests/NetworkTests.swift
+++ b/apps/ios/Kit/Tests/CodyncKitTests/NetworkTests.swift
@@ -3,9 +3,9 @@ import Testing
@testable import CodyncKit
@Test func decodesTheNetworkViewAndItsEvent() throws {
- let view = #"{"joined":true,"computer":"desk","role":"owner","connector":"public","assistants":true,"computers":[{"name":"desk","role":"owner","me":true,"online":true,"bots":["reviewer"],"agents":[{"id":"reviewer","name":"Reviewer"}],"canRemove":false,"canPromote":false},{"name":"laptop","role":"overlord","me":false,"online":false,"bots":[],"agents":[],"canRemove":true,"canPromote":true}]}"#
+ let view = #"{"joined":true,"computer":"desk","role":"owner","connector":"public","assistants":true,"assistantsAvailable":true,"computers":[{"name":"desk","role":"owner","me":true,"online":true,"agents":[{"id":"reviewer","name":"Reviewer"}],"canRemove":false,"canPromote":false},{"name":"laptop","role":"overlord","me":false,"online":false,"agents":[],"canRemove":true,"canPromote":true}]}"#
let decoded = try JSONDecoder().decode(NetworkView.self, from: Data(view.utf8))
- #expect(decoded.joined && decoded.isAssistantsOn && decoded.role == .owner)
+ #expect(decoded.joined && decoded.hasContent && decoded.role == .owner)
#expect(decoded.computers?.map(\.name) == ["desk", "laptop"])
#expect(decoded.computers?.first?.agents?.first?.name == "Reviewer")
#expect(decoded.computers?.last?.role == .member, "an unknown role reads as a member")
@@ -14,9 +14,11 @@ import Testing
Issue.record("network event"); return
}
#expect(event == decoded)
- // Outside a network, from a host that only says whether assistants are on.
- let alone = try JSONDecoder().decode(NetworkView.self, from: Data(#"{"joined":false,"assistants":false}"#.utf8))
- #expect(!alone.hasContent && alone.computers == nil)
+ // Outside a network: shown only while cloud assistants can reach this computer and are on.
+ let alone = { (json: String) in try JSONDecoder().decode(NetworkView.self, from: Data(json.utf8)) }
+ #expect(try !alone(#"{"joined":false,"assistants":false,"assistantsAvailable":true}"#).hasContent)
+ #expect(try !alone(#"{"joined":false,"assistants":true,"assistantsAvailable":false}"#).hasContent, "not in an account")
+ #expect(try alone(#"{"joined":false,"assistants":true,"assistantsAvailable":true}"#).hasContent)
// A network event this app can't read is skipped, never a rewind.
#expect(HostClient.parseEvent(Data(#"{"type":"network","network":{"joined":"yes"}}"#.utf8)) == nil)
}
diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.md
index 408477f1..76a352b0 100644
--- a/apps/ios/WhatsNew.md
+++ b/apps/ios/WhatsNew.md
@@ -10,6 +10,8 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o
### zh-Hant
- 評分邀請只會在你使用一段時間、看完 Bot 的成果並回到列表後出現,不會在開啟 App 時打擾你。也可以隨時從設定前往 App Store 評分。
+- 設定裡每台電腦多了網路按鈕:看你的電腦網路裡有哪些電腦、是否在線、各自提供哪些 Bot,以及雲端助理是否開啟。網路的建立與邀請要在電腦上的 Codync 進行。
### en-US
- Rating invitations wait until you have used Codync for a while, viewed a bot's result, and returned to the list. You can also rate Codync anytime from Settings.
+- A network button on each computer in Settings shows the computers in your network, whether each one answers, the bots it offers, and whether cloud assistants are on. You set up and invite computers in Codync on a computer.
diff --git a/docs/architecture/file-structure.md b/docs/architecture/file-structure.md
index ee858a72..be4f5b42 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 and its bots' address names), `host/src/network_cli.rs`; across-computer bot requests in `host/src/chat/team/remote.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` |
| 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` |
@@ -113,7 +113,7 @@ Codync/
| Desktop local host / SSH lifecycle | `apps/desktop/src/main/host-controller.ts`, `ssh.ts` |
| Desktop store, chat and controls | `apps/desktop/src/renderer/store/bot-store.ts` (actions; state in `bot-mirror.ts`, events stream in `bot-sync.ts`), `views/thread/`, `components/` |
| Cloud routes / authentication / relay | `cloud/src/index.ts`, `api.ts`, `routes/`, `auth.ts`, `relay.ts` |
-| Cloud assistants (the MCP connector at mcp.codync.dev) | `cloud/src/routes/assistant.ts` (MCP, OAuth metadata, routing to computers), `host-calls.ts` (the relay DO's calls to its host); `host/src/chat/team/assistant.rs` (the switch, the tools, the replies) |
+| Cloud assistants (the MCP connector at mcp.codync.dev) | `cloud/src/routes/assistant.ts` (MCP, OAuth metadata, routing to computers), `host-calls.ts` (the relay DO's calls to its host); `host/src/chat/team/assistant.rs` (the setting, the tools, the replies); the switch in desktop `apps/desktop/src/renderer/views/settings/ComputersView.tsx` (+ `store/cloud.ts`) and terminal `host/src/tui/manage/network.rs`; shown read-only in the iPhone and Android network sheets |
| Push encryption / APNs delivery / decryption | `host/src/remote/push.rs`, `relay/src/`, `apps/ios/NotificationService/` |
| Widget and activity rendering | `apps/ios/Kit/Sources/CodyncKit/Design/`, `apps/ios/Widgets/` |
| Android screens (one file per iOS view: `BotListView.kt`, `ChatScreen.kt`, `BotDetailsView.kt` (+ `BotSettingsForm.kt`, `BotTemplateView.kt`), `PairingView.kt`, `SettingsView.kt`, …) | `apps/android/app/src/main/kotlin/com/codync/android/` |
diff --git a/docs/features/cloud-assistants.md b/docs/features/cloud-assistants.md
index 3b2f9f9a..fea3a8d3 100644
--- a/docs/features/cloud-assistants.md
+++ b/docs/features/cloud-assistants.md
@@ -41,7 +41,9 @@ The cloud sees these calls in plain text, and a bot can run anything on its comp
app (Settings → Computers, beside the account rows, shown while the computer is in the account) and the terminal
UI's network sheet (`N`, then `a`), or `codync-host cloud --assistants on`. All go through the local API
`setAssistants`, loopback only. The setting is the `assistants` field of `cloudStatus` and of `networkView`, which
- phones read (they show it in the network sheet and can't change it); the `network` event carries a change.
+ phones read (they show it in the network sheet and can't change it); the `network` event carries a change. The
+ view's `assistantsAvailable` says whether the computer is in a Codync account: the terminal UI and the phones show
+ the switch only then, as the desktop app does.
- **Only the computer's own account.** The Worker routes a call only to computers the token's account owns, and
the host checks the call's account against its owner again.
- **Not on a private relay**: it has no accounts, so the host ignores `assistant.call` there.
diff --git a/docs/features/codync-network.md b/docs/features/codync-network.md
index 921b5cc3..2665744f 100644
--- a/docs/features/codync-network.md
+++ b/docs/features/codync-network.md
@@ -23,17 +23,22 @@ codync-host network peers | promote <computer> | remove <computer> [--cascade] |
The apps show the recovery code once, in a sheet that only "I saved it" closes; the host keeps it nowhere and the
apps never fetch it again. An invite shows when it stops working (`networkInvite` → `expiresAt`). Each computer row
offers only what this computer may do to it: the host says so per row (`canRemove`, `canPromote`, from
-`Role::removes` and `Role::promotes` in the crate), so the apps never work out the role rules themselves.
+`Role::removes` and `Role::promotes` in the crate) and for this computer (`canInvite` from `Role::invites`,
+`canRecover`), so the apps never work out the role rules themselves.
-The iPhone and Android apps read the network through `networkView` (allowed for paired devices over the encrypted
-channel): the computers with their roles, presence and offered bots, and whether cloud assistants are on. Never an
-invite or the recovery code. The network button on a computer's row in Settings opens it; it's hidden when the host
-is older (unknown method) or the computer is neither in a network nor has cloud assistants on.
+The iPhone and Android apps read the network from the event stream's hello and through `networkView` (allowed for
+paired devices over the encrypted channel): the computers with their roles, presence and offered bots, and whether
+cloud assistants are on (`assistants`) and can reach the computer at all (`assistantsAvailable`: it's in a Codync
+account). Never an invite or the recovery code. The network button on a computer's row in Settings opens it; it's
+hidden when the host is older (no `network` in the hello) or the computer is neither in a network nor has cloud
+assistants on that can reach it.
**Live**: the node ticks a change hook (`Node::changes`, a `watch` channel) when members, roles, names, presence or
offered agents change; the host sends a `network` event (`{"type":"network","network": <networkView>}`) to every
-client then and when cloud assistants are switched. `networkView` also asks the other computers in the background
-when what it heard is over a minute old, so opening the screen brings presence up to date through that event.
+client then and when cloud assistants are switched, and the stream's hello carries the view, so one sent before a
+client subscribed isn't lost. Every client reads `networkView` when its network screen opens; that asks the other
+computers in the background when what the host heard is over a minute old, so presence comes up to date through the
+event. The first ask after the host starts is left to bot listings (`list_bots`), which wait up to 5 s for it.
`create` prints the **recovery code** once: the network's root key, kept on no computer. The connector picks the
fallback when two computers can't connect directly: iroh's public relays (`public`, the default), the user's own
diff --git a/host/crates/network/src/node/mod.rs b/host/crates/network/src/node/mod.rs
index 9019d761..16935996 100644
--- a/host/crates/network/src/node/mod.rs
+++ b/host/crates/network/src/node/mod.rs
@@ -129,7 +129,7 @@ impl Node {
/// A one-time invite for another computer, good for an hour while this one stays on.
pub fn invite(&self) -> Result<String> {
let roster = self.inner.roster()?;
- if roster.role(&self.id()) < Some(Role::Admin) {
+ if !roster.role(&self.id()).is_some_and(Role::invites) {
bail!("only the owner and admins can invite computers");
}
let secret = wire::random_hex(16);
@@ -157,8 +157,11 @@ impl Node {
// Where this computer is; nothing to add when it knows no address yet.
let addr = self.inner.endpoint.addr();
let _ = roster.sign(self.inner.endpoint.secret_key(), wire::now_ms(), Change::Locate { addr });
+ // Held across saving and keeping it, so whoever `changes` wakes sees it.
+ let mut guard = locked(&self.inner.roster);
self.inner.save(&roster)?;
- *locked(&self.inner.roster) = Some(roster);
+ *guard = Some(roster);
+ drop(guard);
self.inner.clone().hello_all();
Ok(())
}
@@ -353,7 +356,8 @@ impl Inner {
self.save(roster)
}
- /// Keeps `roster` on disk and tells whoever watches [`Node::changes`].
+ /// 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<()> {
roster.save(&self.dir)?;
self.changed.send_replace(());
diff --git a/host/crates/network/src/roster.rs b/host/crates/network/src/roster.rs
index 93b6f6b4..2b4fa6f6 100644
--- a/host/crates/network/src/roster.rs
+++ b/host/crates/network/src/roster.rs
@@ -35,6 +35,11 @@ pub enum Role {
}
impl Role {
+ /// Whether a computer with this role may invite computers: the owner and admins.
+ pub fn invites(self) -> bool {
+ self >= Role::Admin
+ }
+
/// Whether a computer with this role may remove one with `other`: the owner removes anyone,
/// admins remove plain members.
pub fn removes(self, other: Role) -> bool {
diff --git a/host/crates/network/tests/two_computers.rs b/host/crates/network/tests/two_computers.rs
index fe678ed6..d63bfa8b 100644
--- a/host/crates/network/tests/two_computers.rs
+++ b/host/crates/network/tests/two_computers.rs
@@ -269,8 +269,9 @@ async fn changes_tick_when_who_is_in_or_around_changes() {
}
#[test]
-fn roles_decide_who_removes_and_promotes() {
+fn roles_decide_who_invites_removes_and_promotes() {
use Role::{Admin, Member, Owner};
+ assert!(Owner.invites() && Admin.invites() && !Member.invites());
assert!(Owner.removes(Admin) && Owner.removes(Member) && Admin.removes(Member));
assert!(!Admin.removes(Admin) && !Admin.removes(Owner) && !Member.removes(Member));
assert!(Owner.promotes(Member) && !Owner.promotes(Admin) && !Admin.promotes(Member));
diff --git a/host/src/api/devices.rs b/host/src/api/devices.rs
index d1de3e60..6e65c066 100644
--- a/host/src/api/devices.rs
+++ b/host/src/api/devices.rs
@@ -246,6 +246,7 @@ mod tests {
assert!(permit(&both, m).is_err(), "{m} is loopback only");
}
assert!(permit(&both, "send").is_ok());
+ assert!(permit(&both, "networkView").is_ok(), "phones read the network");
assert!(permit(&both, "screenOffer").is_ok());
assert!(permit(&both, "screenPrepare").is_ok());
assert!(permit(&control, "screenPrepare").is_err());
diff --git a/host/src/api/events.rs b/host/src/api/events.rs
index b3f2e932..acff56a6 100644
--- a/host/src/api/events.rs
+++ b/host/src/api/events.rs
@@ -75,6 +75,8 @@ pub fn events_stream(
"rev": hub.store.current_rev(),
"usage": hub.usage.locked().clone(),
"screen": hub.screen.state(),
+ // Live state like the two above: a `network` event sent before this stream began is in it.
+ "network": crate::network::status(hub),
});
catch_up.insert(0, hello);
// What the voice of a call this device holds should have heard while it was away.
diff --git a/host/src/chat/team/assistant.rs b/host/src/chat/team/assistant.rs
index 82b1fc48..c8944094 100644
--- a/host/src/chat/team/assistant.rs
+++ b/host/src/chat/team/assistant.rs
@@ -34,6 +34,12 @@ pub fn enabled(store: &Store) -> bool {
store.kv_get(KV).as_deref() == Some("on")
}
+/// Whether the cloud can bring the user's assistant here at all: this computer is in their Codync
+/// account (a private relay has none).
+pub fn available(hub: &Hub) -> bool {
+ hub.cloud.status().owner.is_some()
+}
+
/// `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)?;
diff --git a/host/src/chat/team/assistant/tests.rs b/host/src/chat/team/assistant/tests.rs
index 0fda7866..d7acad70 100644
--- a/host/src/chat/team/assistant/tests.rs
+++ b/host/src/chat/team/assistant/tests.rs
@@ -59,3 +59,25 @@ async fn read_replies_tells_a_failed_request_from_a_stopped_one() {
assert_eq!(read(&stopped)["detail"], STOPPED);
f.shutdown().await;
}
+
+#[tokio::test]
+async fn phones_hear_the_switch_through_the_network_view() {
+ let f = Fixture::new();
+ let hub = &f.hub;
+ let mut events = hub.events.subscribe();
+ let switched = |events: &mut tokio::sync::broadcast::Receiver<Value>| {
+ std::iter::from_fn(|| events.try_recv().ok()).find(|e| e["type"] == "network").expect("a network event")
+ };
+ set_enabled(hub, true).unwrap();
+ let view = &switched(&mut events)["network"];
+ assert_eq!(
+ (&view["assistants"], &view["assistantsAvailable"]),
+ (&json!(true), &json!(false)),
+ "not in an account yet"
+ );
+ cloud::update_status(hub, |s| s.owner = Some(Owner { user_id: "user_1".into(), email: None }));
+ set_enabled(hub, false).unwrap();
+ let view = &switched(&mut events)["network"];
+ assert_eq!((&view["assistants"], &view["assistantsAvailable"]), (&json!(false), &json!(true)));
+ f.shutdown().await;
+}
diff --git a/host/src/network/mod.rs b/host/src/network/mod.rs
index d9178f1a..96bab66d 100644
--- a/host/src/network/mod.rs
+++ b/host/src/network/mod.rs
@@ -26,6 +26,14 @@ const FRESH_FOR: Duration = Duration::from_mins(1);
/// How long a listing waits for computers it has never heard from.
const FIRST_LOOK: Duration = Duration::from_secs(5);
+/// Why what the other computers offer is to be asked again.
+enum Due {
+ /// Never asked since the host started: a listing waits for the answers.
+ First,
+ /// Asked more than `FRESH_FOR` ago.
+ Again,
+}
+
#[derive(Default)]
pub struct Network {
node: OnceLock<Arc<Node>>,
@@ -58,11 +66,11 @@ impl Network {
/// and waited for (briefly) the first time.
pub async fn directory(&self) -> Vec<Peer> {
let Some(node) = self.node() else { return Vec::new() };
- match self.stale() {
- Some(true) => {
+ match self.due() {
+ Some(Due::First) => {
let _ = tokio::time::timeout(FIRST_LOOK, node.peers()).await;
}
- Some(false) => {
+ Some(Due::Again) => {
let refresh = node.clone();
tokio::spawn(async move { refresh.peers().await });
}
@@ -71,16 +79,16 @@ impl Network {
node.directory().into_iter().filter(|p| !p.me).collect()
}
- /// Whether what the other computers offer is due to be asked again (now counted as asked), and
- /// if so whether it is the first time.
- fn stale(&self) -> Option<bool> {
+ /// Whether what the other computers offer is due to be asked again; counted as asked from now.
+ fn due(&self) -> Option<Due> {
let mut asked = self.asked.locked();
- let first = asked.is_none();
- if !asked.is_none_or(|at| at.elapsed() >= FRESH_FOR) {
- return None;
- }
+ let due = match *asked {
+ None => Due::First,
+ Some(at) if at.elapsed() >= FRESH_FOR => Due::Again,
+ Some(_) => return None,
+ };
*asked = Some(Instant::now());
- Some(first)
+ Some(due)
}
/// Where `name` points: a bot id, an address name, `name@` this computer or a bare name none of
@@ -143,7 +151,7 @@ async fn watch(hub: Arc<Hub>, mut changes: tokio::sync::watch::Receiver<()>) {
/// The `network` event: what `networkView` answers.
pub fn emit(hub: &Hub) {
- let _ = hub.events.send(json!({"type": "network", "network": view_of(hub)}));
+ let _ = hub.events.send(json!({"type": "network", "network": status(hub)}));
}
/// Offers this computer's visible bots to the network, under their address names. Called after
@@ -185,49 +193,49 @@ fn joined(hub: &Hub) -> Result<Arc<Node>> {
.ok_or_else(|| anyhow!("this computer isn't in a network: create one or join with an invite"))
}
-/// `networkStatus`: this computer and the others, as last heard, with what this computer may do
-/// to each (`canRemove`, `canPromote`).
+/// `networkStatus`, the `network` event and the stream's hello: this computer and the others, as
+/// last heard, with what this computer may do (`canInvite`, `canRecover`) and do to each
+/// (`canRemove`, `canPromote`); 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 assistants = crate::chat::team::assistant::enabled(&hub.store);
+ let available = crate::chat::team::assistant::available(hub);
let Some(node) = hub.network.node().filter(|n| n.name().is_some()) else {
- return json!({"joined": false});
+ return json!({"joined": false, "assistants": assistants, "assistantsAvailable": available});
};
let mine = node.role();
let computers: Vec<Value> = node
.directory()
.into_iter()
.map(|p| {
- let bots: Vec<&str> = p.agents.iter().map(|a| a.id.as_str()).collect();
let agents: Vec<Value> = p.agents.iter().map(|a| json!({"id": a.id, "name": a.name})).collect();
let may = |rule: fn(Role, Role) -> bool| !p.me && mine.is_some_and(|me| rule(me, p.role));
json!({
- "name": p.name, "role": p.role, "me": p.me, "online": p.online, "bots": bots, "agents": agents,
+ "name": p.name, "role": p.role, "me": p.me, "online": p.online, "agents": agents,
"canRemove": may(Role::removes), "canPromote": may(Role::promotes),
})
})
.collect();
json!({
"joined": true, "computer": node.name(), "role": mine,
+ "canInvite": mine.is_some_and(Role::invites), "canRecover": mine.is_some_and(|r| r != Role::Owner),
"connector": hub.store.kv_get(KV_CONNECTOR).unwrap_or_else(|| "public".into()),
- "computers": computers,
+ "computers": computers, "assistants": assistants, "assistantsAvailable": available,
})
}
-/// `networkView`: what phones may see of the network (status, never an invite), plus whether
-/// cloud assistants may reach this computer's bots. Asks the others in the background when
-/// stale; the `network` event brings what they answer.
+/// `networkView`: `status`, asking the others in the background when what they offer is stale;
+/// the `network` event brings what they answer. The first look since the host started is left to
+/// bot listings, which wait for it (`Network::directory`).
pub fn view(hub: &Hub) -> Value {
- if let Some(node) = hub.network.node()
- && hub.network.stale().is_some()
+ let looked = hub.network.asked.locked().is_some();
+ if looked
+ && let Some(node) = hub.network.node()
+ && hub.network.due().is_some()
{
tokio::spawn(async move { node.peers().await });
}
- view_of(hub)
-}
-
-fn view_of(hub: &Hub) -> Value {
- let mut v = status(hub);
- v["assistants"] = crate::chat::team::assistant::enabled(&hub.store).into();
- v
+ status(hub)
}
/// `networkCreate`: a new network with this computer as its owner; returns the recovery code.
@@ -257,7 +265,8 @@ pub async fn join(hub: &Arc<Hub>, invite: &str, name: Option<&str>, connector: O
/// `networkInvite`: a one-time invite and when it stops working (Unix ms).
pub fn invite(hub: &Hub) -> Result<Value> {
let invite = joined(hub)?.invite()?;
- let until = crate::store::now_ms() + i64::try_from(codync_network::INVITE_FOR.as_millis()).unwrap_or(i64::MAX);
+ let lasts = i64::try_from(codync_network::INVITE_FOR.as_millis()).expect("an invite lasts an hour");
+ let until = crate::store::now_ms().saturating_add(lasts);
Ok(json!({"invite": invite, "expiresAt": until}))
}
diff --git a/host/src/network_cli.rs b/host/src/network_cli.rs
index 862ffa70..d61f05f2 100644
--- a/host/src/network_cli.rs
+++ b/host/src/network_cli.rs
@@ -107,7 +107,7 @@ fn print_status(v: &Value) {
} else {
"away"
};
- let bots: Vec<&str> = c["bots"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
+ let bots: Vec<&str> = c["agents"].as_array().into_iter().flatten().filter_map(|a| a["id"].as_str()).collect();
let name = c["name"].as_str().unwrap_or_default();
let role = c["role"].as_str().unwrap_or_default();
println!(" {name:<20} {role:<7} {state:<14} {}", bots.join(", "));
diff --git a/host/src/tui/manage/network.rs b/host/src/tui/manage/network.rs
index a9ce1dd7..f38752dd 100644
--- a/host/src/tui/manage/network.rs
+++ b/host/src/tui/manage/network.rs
@@ -4,6 +4,7 @@
use crossterm::event::{KeyCode, KeyEvent};
use serde_json::{Value, json};
+use std::borrow::Cow;
use super::super::app::{After, App, Editor, Overlay, copy};
use super::super::l10n::tr;
@@ -123,6 +124,17 @@ impl NetworkSheet {
self.view.as_ref().and_then(|v| v["role"].as_str()).unwrap_or_default()
}
+ /// This computer's name in the network.
+ pub fn computer(&self) -> Cow<'_, str> {
+ self.view.as_ref().and_then(|v| v["computer"].as_str()).map_or_else(|| tr("this computer"), Cow::Borrowed)
+ }
+
+ /// What the host says this computer may do or has (`canInvite`, `canRecover`,
+ /// `assistantsAvailable`, `assistants`).
+ pub fn says(&self, flag: &str) -> bool {
+ self.view.as_ref().is_some_and(|v| v[flag] == true)
+ }
+
pub fn computers(&self) -> &[Value] {
self.view.as_ref().map_or(&[], rows)
}
@@ -153,6 +165,11 @@ impl App {
}
pub(in crate::tui) fn network_reply(&mut self, r: NetReply, res: Result<Value, String>) {
+ let open = self.overlays.iter().any(|o| matches!(o, Overlay::Network(_)));
+ if matches!(r, NetReply::Created) && res.is_ok() && !open {
+ // The recovery code is shown only once: bring back the sheet that was closed meanwhile.
+ self.open_network();
+ }
let Some(Overlay::Network(n)) = self.overlays.iter_mut().rev().find(|o| matches!(o, Overlay::Network(_)))
else {
return;
@@ -169,14 +186,8 @@ impl App {
let mut flash = None;
match r {
NetReply::View => {
- // `networkStatus` and `networkPeers` don't carry the assistants switch: keep it.
- let assistants = n.view.as_ref().map(|old| old["assistants"].clone());
- let mut view = v;
- if view.get("assistants").is_none() {
- view["assistants"] = assistants.unwrap_or(Value::Bool(false));
- }
- n.cursor = n.cursor.min(rows(&view).len().saturating_sub(1));
- n.view = Some(view);
+ n.cursor = n.cursor.min(rows(&v).len().saturating_sub(1));
+ n.view = Some(v);
if matches!(n.step, Step::Join(_)) {
n.step = Step::List;
}
@@ -210,58 +221,73 @@ 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) => match k.code {
- KeyCode::Char('y') => {
- copy(&code);
- self.flash("Recovery code copied");
- Step::Recovery(code)
- }
- // Closed only once the user says they kept it.
- KeyCode::Char('s') => Step::List,
- _ => Step::Recovery(code),
- },
- Step::Invite(invite) => match (k.code, invite) {
- (KeyCode::Esc | KeyCode::Char('q'), _) => Step::List,
- (KeyCode::Char('y'), Some((code, until))) => {
- copy(&code);
- self.flash("Invite copied");
- Step::Invite(Some((code, until)))
- }
- (KeyCode::Char('n'), _) => {
- self.net("networkInvite", json!({}), NetReply::Invite);
- Step::Invite(None)
- }
- (_, invite) => Step::Invite(invite),
- },
- Step::Recover(mut code) => match k.code {
- KeyCode::Esc => Step::List,
- KeyCode::Enter if !code.text.trim().is_empty() => {
- n.busy = true;
- let done =
- NetReply::Done("This computer is the owner now. Remove the lost computer from the list.");
- self.net("networkRecover", json!({"code": code.text.trim()}), done);
- Step::Recover(code)
- }
- _ => {
- code.key(k);
- Step::Recover(code)
- }
- },
- Step::Remove { computer, cascade } => match k.code {
- KeyCode::Esc | KeyCode::Char('q') => Step::List,
- KeyCode::Char('c' | ' ') => Step::Remove { computer, cascade: !cascade },
- KeyCode::Enter => {
- n.busy = true;
- let body = json!({"computer": computer, "cascade": cascade});
- self.net("networkRemove", body, NetReply::Done("Removed from the network"));
- Step::Remove { computer, cascade }
- }
- _ => Step::Remove { computer, cascade },
- },
+ Step::Recovery(code) => self.recovery_key(code, k),
+ Step::Invite(invite) => self.invite_key(invite, k),
+ Step::Recover(code) => self.recover_key(&mut n, code, k),
+ Step::Remove { computer, cascade } => self.remove_key(&mut n, computer, cascade, k),
};
Some(Overlay::Network(n))
}
+ fn recovery_key(&mut self, code: String, k: KeyEvent) -> Step {
+ match k.code {
+ KeyCode::Char('y') => {
+ copy(&code);
+ self.flash("Recovery code copied");
+ Step::Recovery(code)
+ }
+ // Closed only once the user says they kept it.
+ KeyCode::Char('s') => Step::List,
+ _ => Step::Recovery(code),
+ }
+ }
+
+ fn invite_key(&mut self, invite: Option<(String, i64)>, k: KeyEvent) -> Step {
+ match (k.code, invite) {
+ (KeyCode::Esc | KeyCode::Char('q'), _) => Step::List,
+ (KeyCode::Char('y'), Some((code, until))) => {
+ copy(&code);
+ self.flash("Invite copied");
+ Step::Invite(Some((code, until)))
+ }
+ (KeyCode::Char('n'), _) => {
+ self.net("networkInvite", json!({}), NetReply::Invite);
+ Step::Invite(None)
+ }
+ (_, invite) => Step::Invite(invite),
+ }
+ }
+
+ fn recover_key(&mut self, n: &mut NetworkSheet, mut code: Editor, k: KeyEvent) -> Step {
+ match k.code {
+ KeyCode::Esc => Step::List,
+ KeyCode::Enter if !code.text.trim().is_empty() => {
+ n.busy = true;
+ let done = NetReply::Done("This computer is the owner now. Remove the lost computer from the list.");
+ self.net("networkRecover", json!({"code": code.text.trim()}), done);
+ Step::Recover(code)
+ }
+ _ => {
+ code.key(k);
+ Step::Recover(code)
+ }
+ }
+ }
+
+ fn remove_key(&mut self, n: &mut NetworkSheet, computer: String, cascade: bool, k: KeyEvent) -> Step {
+ match k.code {
+ KeyCode::Esc | KeyCode::Char('q') => Step::List,
+ KeyCode::Char('c' | ' ') => Step::Remove { computer, cascade: !cascade },
+ KeyCode::Enter => {
+ n.busy = true;
+ let body = json!({"computer": computer, "cascade": cascade});
+ self.net("networkRemove", body, NetReply::Done("Removed from the network"));
+ Step::Remove { computer, cascade }
+ }
+ _ => Step::Remove { computer, cascade },
+ }
+ }
+
fn network_list_key(&mut self, mut n: Box<NetworkSheet>, k: KeyEvent) -> Option<Overlay> {
let last = n.computers().len().saturating_sub(1);
let selected = n.selected().cloned();
@@ -270,9 +296,8 @@ impl App {
KeyCode::Esc | KeyCode::Char('q' | 'N') => return None,
KeyCode::Down | KeyCode::Char('j') => n.cursor = (n.cursor + 1).min(last),
KeyCode::Up | KeyCode::Char('k') => n.cursor = n.cursor.saturating_sub(1),
- KeyCode::Char('a') if n.view.is_some() => {
- let on = n.view.as_ref().is_some_and(|v| v["assistants"] == true);
- self.net("setAssistants", json!({"enabled": !on}), NetReply::Assistants);
+ KeyCode::Char('a') if n.says("assistantsAvailable") => {
+ self.net("setAssistants", json!({"enabled": !n.says("assistants")}), NetReply::Assistants);
}
KeyCode::Char('c') if n.view.is_some() && !n.joined() => n.step = Step::Create(Setup::default()),
KeyCode::Char('J') if n.view.is_some() && !n.joined() => n.step = Step::Join(Setup::join()),
@@ -280,11 +305,11 @@ impl App {
n.busy = true;
self.net("networkPeers", json!({}), NetReply::View);
}
- KeyCode::Char('i') if n.joined() && n.role() != "member" => {
+ KeyCode::Char('i') if n.says("canInvite") => {
self.net("networkInvite", json!({}), NetReply::Invite);
n.step = Step::Invite(None);
}
- KeyCode::Char('o') if n.joined() && n.role() != "owner" => n.step = Step::Recover(Editor::default()),
+ KeyCode::Char('o') if n.says("canRecover") => n.step = Step::Recover(Editor::default()),
KeyCode::Char('p') => match selected {
Some(c) if c["canPromote"] == true => {
self.net("networkPromote", json!({"computer": name(&c)}), NetReply::Done("Made an admin"));
@@ -307,6 +332,8 @@ impl App {
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 => {
@@ -355,7 +382,8 @@ mod tests {
}
fn joined(role: &str) -> Value {
- json!({"joined": true, "computer": "desk", "role": role, "assistants": false, "computers": [
+ json!({"joined": true, "computer": "desk", "role": role, "canInvite": role != "member", "canRecover": role != "owner",
+ "assistants": false, "assistantsAvailable": true, "computers": [
{"name": "desk", "role": role, "me": true, "online": true, "agents": [], "canRemove": false, "canPromote": false},
{"name": "laptop", "role": "member", "me": false, "online": true, "agents": [{"id": "coder", "name": "Coder"}],
"canRemove": role != "member", "canPromote": role == "owner"},
@@ -393,6 +421,14 @@ mod tests {
assert!(matches!(n.step, Step::List));
}
+ #[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"})));
+ let Some(Overlay::Network(n)) = app.overlays.last() else { panic!("the sheet is back") };
+ assert!(matches!(&n.step, Step::Recovery(code) if code == "1234"));
+ }
+
#[test]
fn a_relay_url_field_only_for_your_own_relay() {
let mut s = Setup::join();
diff --git a/host/src/tui/view/network.rs b/host/src/tui/view/network.rs
index 1d969e05..d10cffcd 100644
--- a/host/src/tui/view/network.rs
+++ b/host/src/tui/view/network.rs
@@ -6,6 +6,7 @@ use ratatui::style::Style;
use ratatui::text::Span;
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::md;
@@ -23,64 +24,14 @@ pub(super) fn network(buf: &mut Buffer, area: Rect, n: &NetworkSheet) {
}
hline(buf, inner.x, inner.bottom() - 2, inner.width, t.dim.patch(t.panel));
let body = Rect::new(inner.x, inner.y, inner.width, inner.height - 2);
- let mut y = body.y;
let keys = match &n.step {
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) => {
- let name = n.view.as_ref().and_then(|v| v["computer"].as_str()).unwrap_or("this computer");
- line(buf, body, &mut y, &tr("Save your recovery code"), t.bold);
- y += 1;
- line(buf, body, &mut y, code, t.bold);
- y += 1;
- let note = tr(
- "It makes another computer the owner if {name} is lost. It's shown only once and kept on no computer.",
- );
- wrapped(buf, body, &mut y, &note.replace("{name}", name), t.secondary);
- "y copy · s I saved it"
- }
- Step::Invite(invite) => {
- line(buf, body, &mut y, &tr("Invite a computer"), t.bold);
- y += 1;
- match invite {
- None => line(buf, body, &mut y, &tr("Getting an invite…"), t.dim),
- Some((code, until)) => {
- wrapped(buf, body, &mut y, code, t.bold);
- y += 1;
- let name = n.view.as_ref().and_then(|v| v["computer"].as_str()).unwrap_or("this computer");
- let note = tr("One use. Works until {time} while {name} stays on.")
- .replace("{time}", &clock(*until))
- .replace("{name}", name);
- line(buf, body, &mut y, &note, t.secondary);
- line(
- buf,
- body,
- &mut y,
- &tr("On the other computer, choose Join with invite under Network."),
- t.secondary,
- );
- }
- }
- "y copy · n new invite · esc back"
- }
- Step::Recover(code) => {
- line(buf, body, &mut y, &tr("Recover ownership"), t.bold);
- let note = tr("For when the owner is lost: this computer becomes the owner.");
- wrapped(buf, body, &mut y, &note, t.secondary);
- y += 1;
- input_line(buf, Rect::new(body.x, y, body.width, 1), y, code, "Recovery code", true, false);
- "↵ recover · esc back"
- }
- Step::Remove { computer, cascade } => {
- line(buf, body, &mut y, &tr("Remove {name} from the network?").replace("{name}", computer), t.red);
- line(buf, body, &mut y, &tr("It can't come back with its current key."), t.text);
- y += 1;
- let mark = if *cascade { "◉" } else { "○" };
- line(buf, body, &mut y, &format!("{mark} {}", tr("Also remove the computers it invited")), t.text);
- line(buf, body, &mut y, &format!(" {}", tr("For a stolen computer.")), t.secondary);
- "↵ remove · c switches · esc cancel"
- }
+ Step::Recovery(code) => recovery(buf, body, n, code),
+ 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),
};
if let Some(e) = &n.error {
put(buf, inner.x, inner.bottom() - 3, inner.width, e, t.red.patch(t.panel));
@@ -90,6 +41,61 @@ 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 {
+ 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);
+ y += 1;
+ let note =
+ tr("It makes another computer the owner if {name} is lost. It's shown only once and kept on no computer.");
+ wrapped(buf, body, &mut y, &note.replace("{name}", &n.computer()), t.secondary);
+ "y copy · s I saved it"
+}
+
+fn invite_step(buf: &mut Buffer, body: Rect, n: &NetworkSheet, invite: Option<&(String, i64)>) -> &'static str {
+ let t = theme();
+ let mut y = body.y;
+ line(buf, body, &mut y, &tr("Invite a computer"), t.bold);
+ y += 1;
+ match invite {
+ None => line(buf, body, &mut y, &tr("Getting an invite…"), t.dim),
+ Some((code, until)) => {
+ wrapped(buf, body, &mut y, code, t.bold);
+ y += 1;
+ let note = tr("One use. Works until {time} while {name} stays on.")
+ .replace("{time}", &clock(*until))
+ .replace("{name}", &n.computer());
+ line(buf, body, &mut y, &note, t.secondary);
+ line(buf, body, &mut y, &tr("On the other computer, choose Join with invite under Network."), t.secondary);
+ }
+ }
+ "y copy · n new invite · esc back"
+}
+
+fn recover(buf: &mut Buffer, body: Rect, code: &Editor) -> &'static str {
+ let t = theme();
+ let mut y = body.y;
+ line(buf, body, &mut y, &tr("Recover ownership"), t.bold);
+ wrapped(buf, body, &mut y, &tr("For when the owner is lost: this computer becomes the owner."), t.secondary);
+ y += 1;
+ input_line(buf, Rect::new(body.x, y, body.width, 1), y, code, "Recovery code", true, false);
+ "↵ recover · esc back"
+}
+
+fn remove(buf: &mut Buffer, body: Rect, computer: &str, cascade: bool) -> &'static str {
+ let t = theme();
+ let mut y = body.y;
+ line(buf, body, &mut y, &tr("Remove {name} from the network?").replace("{name}", computer), t.red);
+ line(buf, body, &mut y, &tr("It can't come back with its current key."), t.text);
+ y += 1;
+ let mark = if cascade { "◉" } else { "○" };
+ line(buf, body, &mut y, &format!("{mark} {}", tr("Also remove the computers it invited")), t.text);
+ line(buf, body, &mut y, &format!(" {}", tr("For a stolen computer.")), t.secondary);
+ "↵ remove · c switches · esc cancel"
+}
+
/// The computers, or how to start; then the cloud assistants switch. Returns the key hints.
fn list(buf: &mut Buffer, body: Rect, n: &NetworkSheet) -> &'static str {
let t = theme();
@@ -99,7 +105,7 @@ fn list(buf: &mut Buffer, body: Rect, n: &NetworkSheet) -> &'static str {
return "esc close";
};
if n.joined() {
- let me = view["computer"].as_str().unwrap_or_default();
+ let me = n.computer();
let role = role_name(n.role());
let connector = view["connector"].as_str().unwrap_or("public");
put(buf, body.x, y, body.width, &format!("{me} · {role} · {connector}"), t.secondary.patch(t.panel));
@@ -116,22 +122,33 @@ fn list(buf: &mut Buffer, body: Rect, n: &NetworkSheet) -> &'static str {
let note = tr("Connect your computers so bots on one can message bots on another.");
wrapped(buf, body, &mut y, &note, t.secondary);
}
- y += 1;
- let on = view["assistants"] == true;
+ if n.says("assistantsAvailable") {
+ assistants(buf, body, y + 1, n.says("assistants"));
+ }
+ match (n.joined(), n.says("canInvite"), n.says("canRecover")) {
+ (false, ..) => "c create network · J join with invite · esc close",
+ (true, true, false) => "i invite · p make admin · x remove · r refresh · esc close",
+ (true, true, true) => "i invite · x remove · o recover ownership · r refresh · esc close",
+ (true, false, _) => "o recover ownership · r refresh · esc close",
+ }
+}
+
+/// The cloud assistants switch, for a computer in a Codync account (only there can they reach it).
+fn assistants(buf: &mut Buffer, body: Rect, mut y: u16, on: bool) {
+ let t = theme();
put(buf, body.x, y, body.width, &tr("Cloud assistants"), t.text.patch(t.panel));
- let x = rput(buf, body.right(), y, " a switches", t.dim.patch(t.panel));
- rput(buf, x, y, if on { "◉ On" } else { "○ Off" }, if on { t.text } else { t.secondary }.patch(t.panel));
+ let x = rput(buf, body.right(), y, &format!(" {}", tr("a switches")), t.dim.patch(t.panel));
+ let state = if on { format!("◉ {}", tr("On")) } else { format!("○ {}", tr("Off")) };
+ rput(buf, x, y, &state, if on { t.text } else { t.secondary }.patch(t.panel));
y += 1;
- let about = tr(
- "ChatGPT or Claude in your Codync account can message this computer's bots. Codync's cloud can read these calls.",
- );
+ let about = if on {
+ tr(
+ "ChatGPT or Claude in your Codync account can message this computer's bots. Codync's cloud can read these calls.",
+ )
+ } else {
+ tr("Let ChatGPT or Claude message this computer's bots through your Codync account.")
+ };
wrapped(buf, body, &mut y, &about, t.secondary);
- match (n.joined(), n.role()) {
- (false, _) => "c create network · J join with invite · esc close",
- (true, "owner") => "i invite · p make admin · x remove · r refresh · esc close",
- (true, "admin") => "i invite · x remove · o recover ownership · r refresh · esc close",
- (true, _) => "o recover ownership · r refresh · esc close",
- }
}
fn computer_row(buf: &mut Buffer, body: Rect, y: u16, c: &Value, sel: bool) {
diff --git a/host/tests/fixtures/wire-shape.json b/host/tests/fixtures/wire-shape.json
index b31e0496..a0806071 100644
--- a/host/tests/fixtures/wire-shape.json
+++ b/host/tests/fixtures/wire-shape.json
@@ -178,6 +178,10 @@
"event:hello": "object",
"event:hello.computerId": "string",
"event:hello.hostId": "string",
+ "event:hello.network": "object",
+ "event:hello.network.assistants": "bool",
+ "event:hello.network.assistantsAvailable": "bool",
+ "event:hello.network.joined": "bool",
"event:hello.rev": "number",
"event:hello.type": "string",
"hello": "object",
diff --git a/host/tests/network_e2e.rs b/host/tests/network_e2e.rs
index 44601019..7468c030 100644
--- a/host/tests/network_e2e.rs
+++ b/host/tests/network_e2e.rs
@@ -111,7 +111,7 @@ async fn a_bot_messages_a_bot_on_another_computer_and_relays_its_reply() {
let desk_row = peers["computers"].as_array().unwrap().iter().find(|c| c["name"] == "desk").unwrap().clone();
assert_eq!((desk_row["online"].as_bool(), desk_row["role"].as_str()), (Some(true), Some("owner")));
// Every visible bot goes by its address name (the host's own lead bot too).
- assert!(desk_row["bots"].as_array().unwrap().contains(&json!("reviewer")), "{desk_row}");
+ assert!(desk_row["agents"].as_array().unwrap().iter().any(|a| a["id"] == "reviewer"), "{desk_row}");
// The lead lists the reviewer by its address and messages it; its turn ends at once.
laptop.call("send", json!({"botId": lead, "text": "DELEGATE reviewer@desk"})).await;
@@ -199,6 +199,7 @@ async fn the_network_view_says_who_may_do_what_and_changes_reach_the_apps() {
desk.call("networkPeers", json!({})).await;
let view = desk.call("networkView", json!({})).await;
assert_eq!((view["joined"].as_bool(), view["assistants"].as_bool()), (Some(true), Some(false)));
+ assert_eq!((&view["canInvite"], &view["canRecover"]), (&json!(true), &json!(false)), "the owner invites");
let row = computer(&view, "laptop");
assert_eq!((row["canRemove"].as_bool(), row["canPromote"].as_bool()), (Some(true), Some(true)));
assert!(row["agents"].as_array().unwrap().iter().any(|a| a["name"] == "Lead"), "{row}");
@@ -212,6 +213,7 @@ async fn the_network_view_says_who_may_do_what_and_changes_reach_the_apps() {
(computer(&theirs, "desk")["canRemove"].as_bool(), theirs["role"].as_str()),
(Some(false), Some("member"))
);
+ assert_eq!((&theirs["canInvite"], &theirs["canRecover"]), (&json!(false), &json!(true)));
// The owner promotes the laptop: both computers' apps hear of it without asking.
let there = tokio::spawn(network_event(laptop.base.clone(), laptop.token.clone(), |v| v["role"] == "admin"));
diff --git a/web/content/docs/cloud-assistants.mdx b/web/content/docs/cloud-assistants.mdx
index cb58e3fb..912be8b5 100644
--- a/web/content/docs/cloud-assistants.mdx
+++ b/web/content/docs/cloud-assistants.mdx
@@ -5,7 +5,7 @@ You can give a task to your Codync bots from an assistant you already use on the
Cloud assistants are off on every computer until you turn them on there, at the computer whose bots the assistant may use:
- **Desktop:** Settings → **Computers**, the **Cloud assistants** switch under the computer's account rows.
-- **Terminal UI:** `N` opens the network sheet; `a` switches **Cloud assistants**.
+- **Terminal UI:** `N` opens the network sheet; `a` switches **Cloud assistants** (shown once the computer is in your Codync account).
- **Command line:** `codync-host cloud --assistants on` (`off` turns it off; `codync-host cloud` shows it as `assistants: on`). On a Mac where you installed the app from the disk image rather than with Homebrew, `codync-host` is inside the app: `/Applications/Codync.app/Contents/Resources/codync-host`.
The switch carries the same warning as [Privacy](#privacy) below: Codync's cloud can read these calls. Phones show whether it's on (the network button on a computer's row in **Settings**) but can't change it. The computer has to be in your Codync account (signed in) and use the Codync relay.