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: tighten the open-issue fixes after review

leepokaibb242a7df4a9
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/ChannelIntegrationTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/ChannelIntegrationTest.kt
index f1f2745f..746055b5 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/ChannelIntegrationTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/ChannelIntegrationTest.kt
@@ -15,7 +15,9 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.booleanOrNull
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.jsonObject
@@ -45,7 +47,7 @@ class ChannelIntegrationTest {
private fun identity(): DeviceIdentity = DeviceIdentity(ByteArray(32) { 3 }, ByteArray(32) { 12 })
private fun enqueueHost(forgeSignature: Boolean = false, holdCalls: Boolean = false, burst: Int = 0, welcomeDelay: Long = 0,
- snapshotHead: Int = 5, reject: String? = null, screenBurst: Int = 0) {
+ snapshotHead: Int = 5, reject: String? = null, screenBurst: Int = 0, helloUrls: List<String> = emptyList()) {
server.enqueue(MockResponse().withWebSocketUpgrade(object : WebSocketListener() {
private lateinit var opener: FrameOpener
private lateinit var sealer: FrameSealer
@@ -108,7 +110,10 @@ class ChannelIntegrationTest {
send(webSocket, buildJsonObject { put("id", id); put("ok", buildJsonObject { put("computerId", cid); put("name", "Paired computer") }) })
webSocket.close(4100, "paired")
} else {
- send(webSocket, buildJsonObject { put("id", id); put("ok", buildJsonObject { put("computerId", cid); put("signKey", hostKey.base64Url()) }) })
+ send(webSocket, buildJsonObject { put("id", id); put("ok", buildJsonObject {
+ put("computerId", cid); put("signKey", hostKey.base64Url())
+ if (helloUrls.isNotEmpty()) put("urls", JsonArray(helloUrls.map { JsonPrimitive(it) }))
+ }) })
}
}
private fun send(socket: WebSocket, inner: JsonObject) {
@@ -182,6 +187,13 @@ class ChannelIntegrationTest {
} finally { connected.close() }
}
+ @Test fun `a hello from a computer with many networks keeps its best sixteen addresses`() = runBlocking {
+ val urls = (1..30).map { "http://172.${it + 1}.0.1:19222" }
+ enqueueHost(helloUrls = urls)
+ val connected = withTimeout(5_000) { HostConnector.connect(computer(), identity()) }
+ try { assertEquals(urls.take(16), HostClient.hello(connected, computer()).urls) } finally { connected.close() }
+ }
+
@Test fun `a forged welcome never permits an encrypted request`() = runBlocking {
enqueueHost(forgeSignature = true)
var rejected = false
diff --git a/apps/desktop/src/main/files.ts b/apps/desktop/src/main/files.ts
index 0a9647d7..f48312f5 100644
--- a/apps/desktop/src/main/files.ts
+++ b/apps/desktop/src/main/files.ts
@@ -2,9 +2,10 @@ import { promises as fs } from 'node:fs'
import { basename } from 'node:path'
import { fileURLToPath } from 'node:url'
import { clipboard } from 'electron'
+import type { PickedFile } from '../shared/ipc'
export async function readFiles(paths: string[]) {
- const out: { name: string; data: Uint8Array }[] = []
+ const out: PickedFile[] = []
for (const path of paths) {
try {
out.push({ name: basename(path), data: new Uint8Array(await fs.readFile(path)) })
@@ -27,7 +28,7 @@ export async function readClipboardFiles() {
}
}
if (urls.length) return readFiles(urls.map((u) => fileURLToPath(u.replace(/\0+$/, ''))))
- const out: { name: string; data: Uint8Array }[] = []
+ const out: PickedFile[] = []
for (const item of items) {
const image = item.types.find((t) => t === 'image/png' || t === 'image/jpeg')
if (image && !item.types.includes('text/plain')) {
diff --git a/apps/desktop/src/renderer/views/settings/ComputersView.tsx b/apps/desktop/src/renderer/views/settings/ComputersView.tsx
index b7dd9642..4ca37e0d 100644
--- a/apps/desktop/src/renderer/views/settings/ComputersView.tsx
+++ b/apps/desktop/src/renderer/views/settings/ComputersView.tsx
@@ -35,8 +35,8 @@ export function ComputersView() {
const sshState = useSSH()
const cloud = useModel(app.cloud)
const [editing, setEditing] = useState<{ profile: SSHProfile; isNew: boolean } | null>(null)
- const [removingCopy, setRemovingCopy] = useState<CloudComputer | null>(null)
- const removingOlder = removingCopy !== null && cloud.isOlderCopy(removingCopy)
+ const [removing, setRemoving] = useState<CloudComputer | null>(null)
+ const removingOlder = removing !== null && cloud.isOlderCopy(removing)
const managed = app.managedStores
// Every computer in the account but this one, the SSH computers too: their cards above are about managing them.
const others = cloud.computers.filter((c) => c.computerId !== app.local?.computer.id)
@@ -78,7 +78,7 @@ export function ComputersView() {
<Text as="div" size="callout" tone="secondary">{tr(`No other computers in your account yet.`)}</Text>
) : null}
{others.map((computer) => (
- <AccountComputerRow key={computer.computerId} computer={computer} olderCopy={cloud.isOlderCopy(computer)} onRemove={() => setRemovingCopy(computer)} />
+ <AccountComputerRow key={computer.computerId} computer={computer} olderCopy={cloud.isOlderCopy(computer)} onRemove={() => setRemoving(computer)} />
))}
</div>
</VStack>
@@ -87,13 +87,14 @@ export function ComputersView() {
{editing ? <SSHProfileEditor key={editing.profile.id} profile={editing.profile} isNew={editing.isNew} /> : null}
</Sheet>
<Dialog
- open={removingCopy !== null}
- title={tr(removingOlder ? 'Remove the older {name}?' : 'Remove {name} from your account?').replaceAll('{name}', removingCopy?.name ?? 'computer')}
+ open={removing !== null}
+ title={tr(removingOlder ? 'Remove the older {name}?' : 'Remove {name} from the account?').replaceAll('{name}', removing?.name ?? 'computer')}
message={tr(removingOlder
? "It's an earlier identity of {name} and can't be reached anymore. Removing it only cleans up your account."
- : "It's offline. Removing it only cleans up your account.").replaceAll('{name}', removingCopy?.name ?? 'a computer')}
- actions={removingCopy ? [{ title: 'Remove', destructive: true, action: () => void cloud.removeFromAccount(removingCopy.computerId) }] : []}
- onClose={() => setRemovingCopy(null)}
+ // Offline may only mean asleep: removal unclaims it, and its own app won't add it back by itself.
+ : 'Devices that were approved through the account lose access to {name}. It comes back only when you add it to the account again on {name} itself.').replaceAll('{name}', removing?.name ?? 'a computer')}
+ actions={removing ? [{ title: 'Remove', destructive: true, action: () => void cloud.removeFromAccount(removing.computerId) }] : []}
+ onClose={() => setRemoving(null)}
/>
</div>
)
diff --git a/apps/desktop/src/renderer/views/thread/Composer.tsx b/apps/desktop/src/renderer/views/thread/Composer.tsx
index b3280971..972c2c48 100644
--- a/apps/desktop/src/renderer/views/thread/Composer.tsx
+++ b/apps/desktop/src/renderer/views/thread/Composer.tsx
@@ -2,6 +2,7 @@ import { useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, typ
import { groupFastMode } from '@shared/fast-mode'
import { artifactDraftKey, artifactQuote, type Artifact } from '@shared/artifacts'
import { isGroup, isWorkingIn, quoteOf, type Bot, type Entry } from '@shared/models'
+import type { PickedFile } from '@shared/ipc'
import { BotAvatar } from '../../components/Avatar'
import { Icon } from '../../components/Icon'
import { IconButton } from '../../components/Controls'
@@ -15,7 +16,7 @@ import { useTr } from '../../lib/use-language'
import { useStore } from '../../store/context'
import { MAX_FILE_SIZE, type OutgoingFile } from '../../store/bot-store'
import { pluginsFor } from '../marketplace/plugins'
-import { pastedFiles, readPicked, type PickedFile } from './composer-files'
+import { pastedFiles, readPicked } from './composer-files'
import { composerEnter } from './composer-keyboard'
import { CommandMenu, useCommandMenu } from './CommandMenu'
import { ComposerAttachment } from './ComposerAttachment'
diff --git a/apps/desktop/src/renderer/views/thread/composer-files.ts b/apps/desktop/src/renderer/views/thread/composer-files.ts
index 6ad85d1b..a9f5bf51 100644
--- a/apps/desktop/src/renderer/views/thread/composer-files.ts
+++ b/apps/desktop/src/renderer/views/thread/composer-files.ts
@@ -1,5 +1,4 @@
-/** A dropped, pasted or picked file, read for the draft. */
-export type PickedFile = { name: string; data: Uint8Array }
+import type { PickedFile } from '@shared/ipc'
/** The files' contents; one that can't be read (a copied folder) is left out instead of failing the rest. */
export async function readPicked(files: File[]): Promise<PickedFile[]> {
diff --git a/apps/desktop/src/shared/ipc.ts b/apps/desktop/src/shared/ipc.ts
index 4a6f9b84..fdf8fe80 100644
--- a/apps/desktop/src/shared/ipc.ts
+++ b/apps/desktop/src/shared/ipc.ts
@@ -143,6 +143,9 @@ export type SpeechEvent =
| { type: 'stopped' }
| { type: 'error'; message: string }
+/** A dropped, pasted or picked file: its name and bytes. */
+export type PickedFile = { name: string; data: Uint8Array }
+
export interface CodyncBridge {
platform: 'darwin' | 'linux' | 'win32'
appName: string
@@ -247,10 +250,10 @@ export interface CodyncBridge {
openExternal(url: string): void
copy(text: string): void
/** Files picked in the system dialog: name and bytes. */
- pickFiles(): Promise<{ name: string; data: Uint8Array }[]>
+ pickFiles(): Promise<PickedFile[]>
/** A bot export (.zip) picked in the system dialog: its path on this computer, or null. */
pickExport(): Promise<string | null>
- readClipboardFiles(): Promise<{ name: string; data: Uint8Array }[]>
+ readClipboardFiles(): Promise<PickedFile[]>
setTraySummary(summary: TraySummary): void
onCommand(cb: (command: WindowCommand) => void): () => void
resetAllData(): Promise<void>
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
index f11a2ad1..1bcdc48b 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
@@ -1146,8 +1146,7 @@
"Revoke {name}?": "{name} den Zugriff entziehen?",
"Remove the older {name}?": "Das ältere {name} entfernen?",
"It's an earlier identity of {name} and can't be reached anymore. Removing it only cleans up your account.": "Es ist eine frühere Identität von {name}, die nicht mehr erreichbar ist. Das Entfernen räumt nur dein Konto auf.",
- "Remove {name} from your account?": "{name} aus dem Konto entfernen?",
- "It's offline. Removing it only cleans up your account.": "Es ist offline. Das Entfernen räumt nur dein Konto auf.",
+ "Devices that were approved through the account lose access to {name}. It comes back only when you add it to the account again on {name} itself.": "Über das Konto genehmigte Geräte verlieren den Zugriff auf {name}. Es kehrt erst zurück, wenn du es auf {name} selbst wieder zum Konto hinzufügst.",
"Any device signed in to your account gets full control of {name}: its files, terminals and bots, with no check here. If someone gets into your account, or Codync's cloud is ever compromised, they could add their own device and you'd have no chance to stop it. Devices paired with a QR code aren't affected.": "Jedes in deinem Konto angemeldete Gerät erhält ohne weitere Prüfung hier volle Kontrolle über {name}: Dateien, Terminals und Bots. Falls jemand in dein Konto eindringt oder die Codync-Cloud kompromittiert wird, könnte er ein eigenes Gerät hinzufügen, ohne dass du es verhindern kannst. Per QR-Code gekoppelte Geräte sind nicht betroffen.",
"Pair iPhone with {name}": "iPhone mit {name} koppeln",
"Waiting for your OK on the computer · {code}": "Warten auf deine Bestätigung am Computer · {code}",
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
index c47be62d..d9d2351b 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
@@ -1146,8 +1146,7 @@
"Revoke {name}?": "¿Revocar {name}?",
"Remove the older {name}?": "¿Eliminar el antiguo {name}?",
"It's an earlier identity of {name} and can't be reached anymore. Removing it only cleans up your account.": "Es una identidad anterior de {name} que ya no está accesible. Eliminarla solo limpia tu cuenta.",
- "Remove {name} from your account?": "¿Eliminar {name} de la cuenta?",
- "It's offline. Removing it only cleans up your account.": "Está sin conexión. Eliminarlo solo limpia tu cuenta.",
+ "Devices that were approved through the account lose access to {name}. It comes back only when you add it to the account again on {name} itself.": "Los dispositivos aprobados mediante la cuenta pierden el acceso a {name}. Solo vuelve cuando lo añades de nuevo a la cuenta desde el propio {name}.",
"Any device signed in to your account gets full control of {name}: its files, terminals and bots, with no check here. If someone gets into your account, or Codync's cloud is ever compromised, they could add their own device and you'd have no chance to stop it. Devices paired with a QR code aren't affected.": "Cualquier dispositivo que inicie sesión en tu cuenta obtiene control total de {name}: sus archivos, terminales y bots, sin comprobación aquí. Si alguien accede a tu cuenta o la nube de Codync se ve comprometida, podría añadir su dispositivo sin que puedas impedirlo. Los dispositivos vinculados por QR no se ven afectados.",
"Pair iPhone with {name}": "Vincular iPhone con {name}",
"Waiting for your OK on the computer · {code}": "Esperando tu aprobación en la computadora · {code}",
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
index d3768767..c5c10b3d 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
@@ -1146,8 +1146,7 @@
"Revoke {name}?": "Révoquer {name} ?",
"Remove the older {name}?": "Supprimer l’ancien {name} ?",
"It's an earlier identity of {name} and can't be reached anymore. Removing it only cleans up your account.": "Il s’agit d’une ancienne identité de {name}, désormais inaccessible. La supprimer ne fait que nettoyer votre compte.",
- "Remove {name} from your account?": "Supprimer {name} du compte ?",
- "It's offline. Removing it only cleans up your account.": "Il est hors ligne. Le supprimer ne fait que nettoyer votre compte.",
+ "Devices that were approved through the account lose access to {name}. It comes back only when you add it to the account again on {name} itself.": "Les appareils approuvés via le compte perdent l’accès à {name}. Il ne revient que lorsque vous l’ajoutez de nouveau au compte depuis {name} lui-même.",
"Any device signed in to your account gets full control of {name}: its files, terminals and bots, with no check here. If someone gets into your account, or Codync's cloud is ever compromised, they could add their own device and you'd have no chance to stop it. Devices paired with a QR code aren't affected.": "Tout appareil connecté à votre compte obtient le contrôle total de {name} : fichiers, terminaux et bots, sans vérification ici. Si quelqu’un accède à votre compte ou si le cloud Codync est compromis, il pourrait ajouter son appareil sans que vous puissiez l’arrêter. Les appareils associés par QR code ne sont pas concernés.",
"Pair iPhone with {name}": "Associer l’iPhone à {name}",
"Waiting for your OK on the computer · {code}": "En attente de votre accord sur l’ordinateur · {code}",
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
index 36b7f9fb..ea0a5e87 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
@@ -1146,8 +1146,7 @@
"Revoke {name}?": "{name} を取り消しますか?",
"Remove the older {name}?": "古い {name} を削除しますか?",
"It's an earlier identity of {name} and can't be reached anymore. Removing it only cleans up your account.": "これは {name} の以前のアイデンティティであり、もうアクセスできません。削除してもアカウントがクリーンアップされるだけです。",
- "Remove {name} from your account?": "{name} をアカウントから削除しますか?",
- "It's offline. Removing it only cleans up your account.": "オフラインです。削除してもアカウントが整理されるだけです。",
+ "Devices that were approved through the account lose access to {name}. It comes back only when you add it to the account again on {name} itself.": "アカウントを通じて承認されたデバイスは {name} にアクセスできなくなります。{name} 自体で再びアカウントに追加するまで戻りません。",
"Any device signed in to your account gets full control of {name}: its files, terminals and bots, with no check here. If someone gets into your account, or Codync's cloud is ever compromised, they could add their own device and you'd have no chance to stop it. Devices paired with a QR code aren't affected.": "アカウントにサインインしているデバイスは、ここにチェックを入れなくても、{name} (そのファイル、端末、ボット) を完全に制御できます。誰かがあなたのアカウントに侵入したり、Codync のクラウドが侵害されたりした場合、彼らは自分のデバイスを追加する可能性があり、あなたにはそれを止める機会がありません。 QR コードとペアリングされたデバイスは影響を受けません。",
"Pair iPhone with {name}": "iPhone と {name} をペアリングする",
"Waiting for your OK on the computer · {code}": "コンピューターであなたの OK を待っています · {code}",
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
index 768a3840..2d7d0527 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
@@ -1146,8 +1146,7 @@
"Revoke {name}?": "{name}의 접근 권한을 취소할까요?",
"Remove the older {name}?": "이전 {name}을 제거할까요?",
"It's an earlier identity of {name} and can't be reached anymore. Removing it only cleans up your account.": "더 이상 접근할 수 없는 {name}의 이전 식별 정보입니다. 제거해도 계정만 정리됩니다.",
- "Remove {name} from your account?": "{name}을 계정에서 제거할까요?",
- "It's offline. Removing it only cleans up your account.": "오프라인 상태입니다. 제거해도 계정만 정리됩니다.",
+ "Devices that were approved through the account lose access to {name}. It comes back only when you add it to the account again on {name} itself.": "계정을 통해 승인된 기기는 {name}에 대한 접근 권한을 잃습니다. {name}에서 직접 계정에 다시 추가해야 돌아옵니다.",
"Any device signed in to your account gets full control of {name}: its files, terminals and bots, with no check here. If someone gets into your account, or Codync's cloud is ever compromised, they could add their own device and you'd have no chance to stop it. Devices paired with a QR code aren't affected.": "계정에 로그인한 모든 기기는 여기서 별도의 확인 없이 {name}의 파일, 터미널, 봇을 완전히 제어할 수 있습니다. 누군가 계정에 침입하거나 Codync 클라우드가 침해되면 자신의 기기를 추가할 수 있으며 이를 막을 기회가 없습니다. QR 코드로 페어링한 기기는 영향을 받지 않습니다.",
"Pair iPhone with {name}": "{name}에 iPhone 페어링",
"Waiting for your OK on the computer · {code}": "컴퓨터에서 승인 대기 중 · {code}",
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 b8cb22b1..18bc4531 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
@@ -1146,8 +1146,7 @@
"Revoke {name}?": "撤销 {name} 的访问?",
"Remove the older {name}?": "移除较早的 {name}?",
"It's an earlier identity of {name} and can't be reached anymore. Removing it only cleans up your account.": "这是 {name} 较早的身份,已经连不上了。移除它只是清理你的账户。",
- "Remove {name} from your account?": "从账户移除 {name}?",
- "It's offline. Removing it only cleans up your account.": "它已离线。移除它只是清理你的账户。",
+ "Devices that were approved through the account lose access to {name}. It comes back only when you add it to the account again on {name} itself.": "通过账户批准的设备会失去对 {name} 的访问。只有在 {name} 本机上重新加入账户,它才会回来。",
"Any device signed in to your account gets full control of {name}: its files, terminals and bots, with no check here. If someone gets into your account, or Codync's cloud is ever compromised, they could add their own device and you'd have no chance to stop it. Devices paired with a QR code aren't affected.": "登录了你账户的任何设备都能完全控制 {name}:它的文件、终端和 Bot,这里不会再核对。如果有人进入你的账户,或 Codync 的云被攻破,对方可以自己加一台设备,你没有机会拦住。用二维码配对的设备不受影响。",
"Pair iPhone with {name}": "让 iPhone 与 {name} 配对",
"Waiting for your OK on the computer · {code}": "等你在电脑上确认 · {code}",
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 312455f6..88fece85 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
@@ -1146,8 +1146,7 @@
"Revoke {name}?": "撤銷 {name} 的訪問?",
"Remove the older {name}?": "移除較早的 {name}?",
"It's an earlier identity of {name} and can't be reached anymore. Removing it only cleans up your account.": "這是 {name} 較早的身份,已經連不上了。移除它只是清理你的賬戶。",
- "Remove {name} from your account?": "從賬戶移除 {name}?",
- "It's offline. Removing it only cleans up your account.": "它已離線。移除它只是清理你的賬戶。",
+ "Devices that were approved through the account lose access to {name}. It comes back only when you add it to the account again on {name} itself.": "透過賬戶批准的裝置會失去對 {name} 的訪問。只有在 {name} 本機上重新加入賬戶,它才會回來。",
"Any device signed in to your account gets full control of {name}: its files, terminals and bots, with no check here. If someone gets into your account, or Codync's cloud is ever compromised, they could add their own device and you'd have no chance to stop it. Devices paired with a QR code aren't affected.": "登入了你賬戶的任何裝置都能完全控制 {name}:它的檔案、終端和 Bot,這裡不會再核對。如果有人進入你的賬戶,或 Codync 的雲被攻破,對方可以自己加一臺裝置,你沒有機會攔住。用二維碼配對的裝置不受影響。",
"Pair iPhone with {name}": "讓 iPhone 與 {name} 配對",
"Waiting for your OK on the computer · {code}": "等你在電腦上確認 · {code}",
diff --git a/docs/architecture/conversation-runtime.md b/docs/architecture/conversation-runtime.md
index 7f579a66..f24b933c 100644
--- a/docs/architecture/conversation-runtime.md
+++ b/docs/architecture/conversation-runtime.md
@@ -8,4 +8,4 @@
- **Lead bot**: the host makes the first one per computer (`chat/lead.rs`), and the user may pick another (`setLead`) or delete it; on top of every roster, never hidden; its instructions ask for initiative, the *Check in* routine made with the first runs twice a day, and it opens a call with a turn of its own (`Cmd::Prompt`, no user message): [docs/features/lead-bot.md](../features/lead-bot.md).
- Bot collaboration: built-in `team` MCP (`chat/team.rs`) lists visible bots and sends one a request through its actor queue (`message_bot`); nothing waits, and the reply comes back to the sender as a turn of its own in its main chat. Requests and replies are separate turns, bounded by the chain's hop count; native subagents stay with the harness. See [docs/features/bot-collaboration.md](../features/bot-collaboration.md).
- **Context & memory**: frozen instruction snapshot per session + compaction epoch (Claude gets it as a system prompt), profile edits as update blocks, memory in the host (a layer shared by all bots and one per bot, written by the user, the bots' tools and dreaming), busy-time messages folded into one turn, interrupted turns resumed: [docs/features/context-and-memory.md](../features/context-and-memory.md).
-- **Chat shows only**: user messages, the bot's messages (`data.final`: each `send_message` call from the built-in `chat` MCP, Grok Bot's way, also between turns from work the agent goes on with in the background, into the bot's own chat with a *done* alert, unless the user stopped the bot since; a turn that sent none falls back to its last text, unless it reacted to the user's message instead or passed), permission cards, notices. Nothing streams into a bubble; narration, thoughts, tool calls, plans are trace entries (Full conversation sheet; with [Show thinking details](../features/chat-messages.md#while-it-works) on (Settings › Chat), the live activity also unfolds the running turn's steps, without the bot's `bookkeeping` tool calls): [docs/features/chat-messages.md](../features/chat-messages.md).
+- **Chat shows only**: user messages, the bot's messages (`data.final`: each `send_message` call from the built-in `chat` MCP, Grok Bot's way, also between turns from work the agent goes on with in the background, into the bot's own chat with a *done* alert, unless the user stopped its last turn; a turn that sent none falls back to its last text, unless it reacted to the user's message instead or passed), permission cards, notices. Nothing streams into a bubble; narration, thoughts, tool calls, plans are trace entries (Full conversation sheet; with [Show thinking details](../features/chat-messages.md#while-it-works) on (Settings › Chat), the live activity also unfolds the running turn's steps, without the bot's `bookkeeping` tool calls): [docs/features/chat-messages.md](../features/chat-messages.md).
diff --git a/docs/architecture/desktop-app.md b/docs/architecture/desktop-app.md
index 3164f357..08f46dd7 100644
--- a/docs/architecture/desktop-app.md
+++ b/docs/architecture/desktop-app.md
@@ -104,8 +104,9 @@ The TUI connects to one host at a time, so it keeps its single roster.
as an SMAppService agent; Linux starts its helper from the host, as before.
- **Other computers in the account** are reached through this computer's own host and SSH
tunnels only. The encrypted channel to account computers (`ChannelTransport`) wasn't ported:
- the product targets one computer, so "Ask for access" rows show status only. An older copy of a
- computer the app uses shows *Older copy · last seen …* with *Remove from account* (confirmed first).
+ the product targets one computer, so "Ask for access" rows show status only. Every offline row
+ has *Remove from account* (confirmed first); an older copy of a computer the app uses also reads
+ *Older copy · last seen …*.
- **Updates**: electron-updater reads the release GitHub marks latest, and only the release gate
(`tools/release-gate.py`) sets that mark
([holding releases](../reference/compatibility.md#holding-releases-for-the-app-store)).
diff --git a/docs/features/chat-messages.md b/docs/features/chat-messages.md
index c2591b22..8ac85008 100644
--- a/docs/features/chat-messages.md
+++ b/docs/features/chat-messages.md
@@ -25,6 +25,12 @@ it has no pointer tooltip or link-opening action.
same way; see [artifacts](artifacts.md).
- Group room turns, bot requests (`message_bot`) and routines reject `send_message` and `send_file`: their reply
is the turn's last text, as before (`chat/group.rs`, `chat/team.rs`, `routines`).
+- Between turns, work the agent goes on with in the background (a subagent's result) can still `send_message`
+ (`send_between_turns`): a final entry in the bot's main lane, numbered with its latest turn, plus a *done* push;
+ refused when the user stopped the last turn. `send_file` and `publish_artifact` need a running turn, and say to
+ use `send_message` instead. The host can't tell a background call from the running turn's own (the `chat` MCP
+ call names no session), so one that lands during a room, request or routine turn is refused like that turn's
+ and told to send again once it ends.
- A bot request's reply stays in the recipient's trace and the request notice; it does
not also become a message to the user. It goes back to the requesting bot as a turn of its own in
that bot's main chat, and that turn's reply is an ordinary message to the user.
diff --git a/docs/guides/accounts-and-ssh.md b/docs/guides/accounts-and-ssh.md
index a75ee382..2d5bd78f 100644
--- a/docs/guides/accounts-and-ssh.md
+++ b/docs/guides/accounts-and-ssh.md
@@ -209,7 +209,10 @@ directly (the encrypted channel wasn't ported to the desktop app), so their
"Ask for access" rows show status only. An older copy of a computer the app uses shows
*Older copy · last seen …*. Every offline row has *Remove from account* (`DELETE /v1/computers/{id}`,
confirmed first), so a computer that was reset or given away can be cleaned up even when its
-name changed. See [desktop app](../architecture/desktop-app.md).
+name changed. Offline may only mean asleep, so the dialog says what removal does: account-approved
+devices lose access, and the computer's own app doesn't add it back by itself. The phones have no
+such action: adding a computer to the account or removing it is desktop-only, and phones manage
+only their own access (pair or forget, revoke, ask). See [desktop app](../architecture/desktop-app.md).
**Computers & devices** (Settings) shows, for this computer and each SSH computer:
*Reach from anywhere* (`setCloud`, on/off; the host's build decides which cloud),
diff --git a/docs/reference/remote-relay.md b/docs/reference/remote-relay.md
index 0bbe9bac..9aa1c928 100644
--- a/docs/reference/remote-relay.md
+++ b/docs/reference/remote-relay.md
@@ -134,7 +134,7 @@ codync://pair?v=3&name=<pct>&id=<computerId>&sk=<signPub>&bk=<boxPub>&code=<pair
| `id` | 是 | 必須等於 `computerId(sk)`,否則拒絕 |
| `sk`, `bk` | 是 | host 公鑰 |
| `code` | 是 | 16 random bytes,b64url;一次性、10 分鐘;host 最多同時 5 組(新的擠掉最舊的) |
-| `urls` | 否 | 直連候選(`service::addresses`):先 `CODYNC_EXTERNAL_URL` 設的網址(`https://host` 等,只能是 host 根路徑),再 Tailscale,再 LAN(`http://ip:port`,略過 Docker、Podman、Kubernetes、libvirt、LXD 的容器橋接介面);最多 16 個(手機只留前 16 個);可為空 |
+| `urls` | 否 | 直連候選(`service::addresses`):先 `CODYNC_EXTERNAL_URL` 設的網址(`https://host` 等,只能是 host 根路徑),再 Tailscale,再 LAN(`http://ip:port`,略過 Docker、Podman、Kubernetes、libvirt、LXD 的容器橋接介面;依 192.168、10、172.16/12 排序);最多 16 個(手機只留前 16 個);可為空 |
| `cloud` | 否 | host 使用的 cloud base URL(`https://…`;DEBUG build 另允許 `http://127.0.0.1:*`/`http://localhost:*`);缺 = host 關閉雲端 |
| `name` | 否 | 顯示名稱 |
diff --git a/host/src/agent/acp.rs b/host/src/agent/acp.rs
index 7579095b..ceb0ec64 100644
--- a/host/src/agent/acp.rs
+++ b/host/src/agent/acp.rs
@@ -340,6 +340,14 @@ pub async fn stopped() {
futures::future::join_all(tasks).await;
}
+/// The result for a `session/request_permission`: the option picked, or `cancelled` without one.
+pub fn permission_answer(option_id: Option<&str>) -> Value {
+ match option_id {
+ Some(id) => json!({"outcome": {"outcome": "selected", "optionId": id}}),
+ None => json!({"outcome": {"outcome": "cancelled"}}),
+ }
+}
+
/// Plain-text rendering of an ACP content block list / tool-call content list.
pub fn content_text(v: &Value) -> String {
match v {
diff --git a/host/src/agent/bot/files.rs b/host/src/agent/bot/files.rs
index 4a510f2b..94b6573a 100644
--- a/host/src/agent/bot/files.rs
+++ b/host/src/agent/bot/files.rs
@@ -84,7 +84,7 @@ impl Actor {
self.active_group.is_none() && self.active_request.is_none() && self.active_routine.is_none(),
"send_file and artifact cards are only available in the bot's own chat"
);
- self.turn.ok_or_else(|| anyhow!("no turn is running"))
+ self.turn.ok_or_else(|| anyhow!("no turn is running: between turns, tell the user with send_message"))
}
/// A published artifact's card (`chat::artifacts`, its entry's `data`): a message of the turn, like a shared file.
diff --git a/host/src/agent/bot/mod.rs b/host/src/agent/bot/mod.rs
index 17807b70..eeb5d3d4 100644
--- a/host/src/agent/bot/mod.rs
+++ b/host/src/agent/bot/mod.rs
@@ -437,13 +437,16 @@ impl Actor {
/// `notice` with more fields than its text and style.
fn notice_data(&self, data: Value) {
let Some(turn) = self.turn else {
- let main = Lane::main(&self.cfg.id);
- let turn = self.hub.store.max_turn(&self.cfg.id);
- self.hub.add_entry(&main, EntryKind::Notice, turn, &data);
+ self.add_between_turns(EntryKind::Notice, &data);
return;
};
self.add(EntryKind::Notice, turn, data);
}
+
+ /// An entry while no turn runs: in the bot's own chat, numbered with its latest turn.
+ fn add_between_turns(&self, kind: EntryKind, data: &Value) -> Option<Entry> {
+ self.hub.add_entry(&Lane::main(&self.cfg.id), kind, self.hub.store.max_turn(&self.cfg.id), data)
+ }
}
/// Told to a bot whose turn the previous host process cut off (Grok Bot's upgrade resume).
diff --git a/host/src/agent/bot/turn.rs b/host/src/agent/bot/turn.rs
index 6208d8a3..e09849f5 100644
--- a/host/src/agent/bot/turn.rs
+++ b/host/src/agent/bot/turn.rs
@@ -206,17 +206,11 @@ impl Actor {
if self.session_fresh {
tokio::time::sleep(Duration::from_millis(400)).await;
}
- let mut waiting = vec![];
- if let Some(conn) = self.conn.as_mut() {
- while let Ok(inc) = conn.rx.try_recv() {
- if let Incoming::Request { id, method, params } = inc {
- waiting.push((id, method, params));
- }
- }
- }
// Requests that came in before this turn: a permission gets the answer it would have had a moment ago.
- for (id, method, params) in waiting {
- self.answer_outside_turn(id, &method, &params).await;
+ while let Some(inc) = self.conn.as_mut().and_then(|c| c.rx.try_recv().ok()) {
+ if let Incoming::Request { id, method, params } = inc {
+ self.answer_outside_turn(id, &method, &params).await;
+ }
}
let sid = self.turn_session.clone().ok_or_else(|| anyhow!("no session"))?;
let prompt =
@@ -419,15 +413,15 @@ impl Actor {
self.files.cancel();
self.flush(true);
self.seg = Seg::None;
- let acp = self.conn.as_ref().map(|c| c.acp.clone());
+ let client = self.conn.as_ref().map(|c| c.acp.clone());
for (id, answer) in self.perms.drain() {
if let Some(mut e) = self.hub.store.entry(&id) {
e.data["status"] = "expired".into();
self.hub.set_entry(&id, &e.data);
}
// The agent would wait on a card no one can answer any more.
- if let (super::updates::Answer::Agent(rpc_id), Some(acp)) = (answer, acp.clone()) {
- tokio::spawn(async move { acp.respond(rpc_id, json!({"outcome": {"outcome": "cancelled"}})).await });
+ if let (super::updates::Answer::Agent(rpc_id), Some(client)) = (answer, client.clone()) {
+ tokio::spawn(async move { client.respond(rpc_id, acp::permission_answer(None)).await });
}
}
for entry_id in self.tools.values() {
diff --git a/host/src/agent/bot/updates.rs b/host/src/agent/bot/updates.rs
index af64c58d..9aed9239 100644
--- a/host/src/agent/bot/updates.rs
+++ b/host/src/agent/bot/updates.rs
@@ -6,7 +6,7 @@ use super::{Actor, Reacted, Seg, SegKind};
use crate::agent::acp::{self, Incoming};
use crate::hub::BotStatus;
use crate::remote::push::{self, AlertKind};
-use crate::store::{EntryKind, Lane, Permission};
+use crate::store::{EntryKind, Permission};
use serde_json::{Value, json};
use std::time::{Duration, Instant};
use tokio::sync::oneshot;
@@ -167,9 +167,9 @@ impl Actor {
let options = params["options"].as_array().cloned().unwrap_or_default();
let tool = &params["toolCall"];
if self.cfg.permission == Permission::Auto
- && let (Some(answer), Some(conn)) = (auto_answer(&options), &self.conn)
+ && let (Some(option), Some(conn)) = (auto_pick(&options), &self.conn)
{
- let _ = conn.acp.respond(rpc_id, answer).await;
+ let _ = conn.acp.respond(rpc_id, acp::permission_answer(Some(option))).await;
return;
}
let title = tool["title"]
@@ -203,16 +203,16 @@ impl Actor {
/// A permission request from work the agent goes on with after its turn ended (a background subagent): no turn
/// shows a card for it, so it gets what a turn would answer without asking, under the bot's Approve automatically,
- /// for one of this bot's own sessions, unless the user stopped the bot since. Anything else is declined.
+ /// for one of this bot's own sessions, unless the user stopped its last turn. Anything else is declined.
pub(super) async fn answer_background(&self, rpc_id: Value, params: &Value) {
let Some(conn) = &self.conn else { return };
let own = params["sessionId"].as_str().is_some_and(|sid| conn.loaded.contains_key(sid));
let options = params["options"].as_array().cloned().unwrap_or_default();
- let answer = (self.cfg.permission == Permission::Auto && own && !self.stop_requested)
- .then(|| auto_answer(&options))
+ let pick = (self.cfg.permission == Permission::Auto && own && !self.stop_requested)
+ .then(|| auto_pick(&options))
.flatten();
- tracing::info!(bot = %self.id(), approved = answer.is_some(), title = params["toolCall"]["title"].as_str(), "permission asked outside a turn");
- let _ = conn.acp.respond(rpc_id, answer.unwrap_or_else(|| json!({"outcome": {"outcome": "cancelled"}}))).await;
+ tracing::info!(bot = %self.id(), approved = pick.is_some(), title = params["toolCall"]["title"].as_str(), "permission asked outside a turn");
+ let _ = conn.acp.respond(rpc_id, acp::permission_answer(pick)).await;
}
/// `Cmd::Approve`: Allow or Deny on a card, with what the tool will do in its details.
@@ -270,12 +270,8 @@ impl Actor {
let mut status = if option_id.is_some() { "answered" } else { "cancelled" };
match answer {
Answer::Agent(rpc_id) => {
- let outcome = match &option_id {
- Some(o) => json!({"outcome": {"outcome": "selected", "optionId": o}}),
- None => json!({"outcome": {"outcome": "cancelled"}}),
- };
if let Some(conn) = &self.conn {
- let _ = conn.acp.respond(rpc_id, outcome).await;
+ let _ = conn.acp.respond(rpc_id, acp::permission_answer(option_id.as_deref())).await;
}
}
Answer::Codync(reply) => {
@@ -302,13 +298,14 @@ impl Actor {
/// bot's own chat; a room, a bot request or a routine reads the turn's reply.
pub(super) fn send_to_user(&mut self, text: String) -> anyhow::Result<()> {
let Some(turn) = self.turn else { return self.send_between_turns(&text) };
+ // A background result can't be told from this turn's own send (no session in the call): it may try again later.
if self.active_request.is_some() {
anyhow::bail!(
- "send_message isn't available in a bot request: your final reply goes to the requesting bot, so put your answer there"
+ "send_message isn't available in a bot request: your final reply goes to the requesting bot, so put your answer there {LATER}"
);
}
if self.active_group.is_some() || self.active_routine.is_some() {
- anyhow::bail!("send_message isn't available in this turn: write your answer as your reply");
+ anyhow::bail!("send_message isn't available in this turn: write your answer as your reply {LATER}");
}
self.close_seg();
self.add(EntryKind::Agent, turn, json!({"text": text, "final": true}))
@@ -319,14 +316,11 @@ impl Actor {
}
/// A `send_message` from work the agent goes on with after its turn ended (a background subagent's result): a
- /// message in the bot's own chat, with the alert a finished turn sends, unless the user stopped the bot since.
+ /// message in the bot's own chat, with the alert a finished turn sends, unless the user stopped its last turn.
fn send_between_turns(&self, text: &str) -> anyhow::Result<()> {
anyhow::ensure!(self.conn.is_some(), "no turn is running");
anyhow::ensure!(!self.stop_requested, "the user stopped you: send nothing until they write again");
- let data = json!({"text": text, "final": true, "author": self.cfg.id});
- let turn = self.hub.store.max_turn(&self.cfg.id);
- self.hub
- .add_entry(&Lane::main(&self.cfg.id), EntryKind::Agent, turn, &data)
+ self.add_between_turns(EntryKind::Agent, &json!({"text": text, "final": true, "author": self.cfg.id}))
.ok_or_else(|| anyhow::anyhow!("couldn't save the message"))?;
push::notify(&self.hub, &self.cfg, None, &self.cfg.name, text, AlertKind::Done);
Ok(())
@@ -409,11 +403,14 @@ impl Actor {
}
}
-/// What Approve automatically answers a permission request: allow once, else allow always, else its first option.
-fn auto_answer(options: &[Value]) -> Option<Value> {
- let pick = ["allow_once", "allow_always"]
+/// The option Approve automatically picks for a permission request: allow once, else allow always, else its first.
+fn auto_pick(options: &[Value]) -> Option<&str> {
+ ["allow_once", "allow_always"]
.iter()
.find_map(|k| options.iter().find(|o| o["kind"] == *k))
- .or_else(|| options.first())?;
- Some(json!({"outcome": {"outcome": "selected", "optionId": pick["optionId"]}}))
+ .or_else(|| options.first())?["optionId"]
+ .as_str()
}
+
+/// Told with a `send_message` refused in a room, request or routine turn, in case it came from earlier work.
+const LATER: &str = "(a result of earlier background work: send it again once this turn ends)";
diff --git a/host/src/chat/oneshot.rs b/host/src/chat/oneshot.rs
index 96818c25..a067433c 100644
--- a/host/src/chat/oneshot.rs
+++ b/host/src/chat/oneshot.rs
@@ -103,7 +103,7 @@ async fn collect(acp: &Acp, inc: Option<Incoming>, out: &mut String) -> bool {
}
Some(Incoming::Request { id, method, .. }) => {
let _ = if method == "session/request_permission" {
- acp.respond(id, json!({"outcome": {"outcome": "cancelled"}})).await
+ acp.respond(id, acp::permission_answer(None)).await
} else {
acp.respond_error(id, -32601, "not supported").await
};
diff --git a/host/src/service/addresses.rs b/host/src/service/addresses.rs
index 7055570c..aeaf5a3b 100644
--- a/host/src/service/addresses.rs
+++ b/host/src/service/addresses.rs
@@ -4,7 +4,7 @@ use serde_json::Value;
use std::process::Command;
use std::sync::LazyLock;
-/// Phones keep at most this many addresses, best first (the Android app refuses a longer list).
+/// The most addresses sent, best first: a phone keeps at most this many, and a longer list is cut to it.
const MAX_ADDRESSES: usize = 16;
/// Addresses the phone can try, best first: the ones set in `CODYNC_EXTERNAL_URL`, Tailscale, then LAN.
@@ -24,7 +24,7 @@ pub fn addresses(port: u16) -> Vec<String> {
if o[0] == 100 && (64..128).contains(&o[1]) {
tailscale.push(format!("http://{ip}:{port}"));
} else if ip.is_private() {
- lan.push(format!("http://{ip}:{port}"));
+ lan.push(ip);
}
}
}
@@ -39,11 +39,22 @@ pub fn addresses(port: u16) -> Vec<String> {
}
tailscale.sort();
tailscale.dedup();
- lan.sort();
+ lan.sort_by_key(|ip| (lan_rank(*ip), *ip));
lan.dedup();
+ let lan = lan.into_iter().map(|ip| format!("http://{ip}:{port}"));
EXTERNAL.iter().cloned().chain(tailscale).chain(lan).take(MAX_ADDRESSES).collect()
}
+/// Home networks first, then office ones, so the cap drops the private ranges container and VM networks favor.
+// ponytail: guesses by range; ask the OS for the default route's interface if a LAN address still gets cut.
+fn lan_rank(ip: std::net::Ipv4Addr) -> u8 {
+ match ip.octets() {
+ [192, 168, ..] => 0,
+ [10, ..] => 1,
+ _ => 2,
+ }
+}
+
/// A bridge that containers or VMs on this computer sit behind (Docker, Podman, Kubernetes, libvirt, LXD).
/// No phone reaches the host through one, and a server with many Docker networks has dozens.
fn is_container_bridge(name: &str) -> bool {
@@ -97,6 +108,15 @@ mod tests {
assert_eq!(external_urls(""), [] as [String; 0]);
}
+ #[test]
+ fn home_networks_rank_before_the_cap() {
+ let mut ips: Vec<std::net::Ipv4Addr> =
+ ["172.20.0.1", "10.0.0.10", "192.168.1.20", "10.0.0.9"].iter().map(|s| s.parse().unwrap()).collect();
+ ips.sort_by_key(|ip| (lan_rank(*ip), *ip));
+ let sorted: Vec<String> = ips.iter().map(ToString::to_string).collect();
+ assert_eq!(sorted, ["192.168.1.20", "10.0.0.9", "10.0.0.10", "172.20.0.1"]);
+ }
+
#[test]
fn container_bridges_are_not_addresses() {
for name in
diff --git a/host/tests/background_work_e2e.rs b/host/tests/background_work_e2e.rs
index 09c0bd7b..a5d00c27 100644
--- a/host/tests/background_work_e2e.rs
+++ b/host/tests/background_work_e2e.rs
@@ -1,6 +1,6 @@
//! Work an agent goes on with after its turn ended (like Hermes' background subagents), through a real host and a
//! fixture agent: a permission request it makes then gets the answer the bot's permission setting gives without a
-//! card, and only for the bot's own session.
+//! card, only for the bot's own session and not after the user stopped the turn.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
@@ -13,6 +13,11 @@ use std::time::{Duration, Instant};
/// The host's answer to the permission request the agent makes after answering `text`, the `nth` it got.
async fn answer_after(host: &Host, bot: &str, text: &str, nth: usize) -> Value {
host.reply(bot, text).await;
+ nth_answer(host, bot, nth).await
+}
+
+/// The `nth` permission answer the agent got, once it comes.
+async fn nth_answer(host: &Host, bot: &str, nth: usize) -> Value {
let file = host.home.join("bots").join(bot).join("workspace").join("responses.jsonl");
let deadline = Instant::now() + Duration::from_secs(20);
loop {
@@ -33,12 +38,28 @@ async fn a_permission_asked_after_the_turn_gets_the_bots_automatic_answer() {
// A bot that asks first: no card waits for it, so it's declined (the way ACP says it), not refused as unsupported.
let asked = answer_after(&host, &bot, "write the notes", 0).await;
assert_eq!(asked["result"]["outcome"]["outcome"], "cancelled", "{asked}");
+ // Asked just before the turn ends: whether its card or the end of the turn answers it, the agent isn't left waiting.
+ let early = answer_after(&host, &bot, "write the notes EARLY", 1).await;
+ assert_eq!(early["result"]["outcome"]["outcome"], "cancelled", "{early}");
host.call("updateBot", json!({"id": bot, "permission": "auto"})).await;
- let approved = answer_after(&host, &bot, "write the notes", 1).await;
+ let approved = answer_after(&host, &bot, "write the notes", 2).await;
assert_eq!(approved["result"]["outcome"], json!({"outcome": "selected", "optionId": "yes"}), "{approved}");
// Never for a session the host didn't open for this bot.
- let elsewhere = answer_after(&host, &bot, "write the notes elsewhere", 2).await;
+ let elsewhere = answer_after(&host, &bot, "write the notes elsewhere", 3).await;
assert_eq!(elsewhere["result"]["outcome"]["outcome"], "cancelled", "{elsewhere}");
+
+ // Nor after the user stopped the turn that started the work, which can't message them either.
+ host.call("send", json!({"botId": bot, "text": "write the notes SLOW", "clientNonce": "slow"})).await;
+ let deadline = Instant::now() + Duration::from_secs(20);
+ while common::bot(&host.snapshot().await, &bot)["status"] == "idle" {
+ assert!(Instant::now() < deadline, "the turn never started");
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ host.call("stop", json!({"botId": bot})).await;
+ let stopped = nth_answer(&host, &bot, 4).await;
+ assert_eq!(stopped["result"]["outcome"]["outcome"], "cancelled", "{stopped}");
+ let send = json!({"botId": bot, "name": "send_message", "arguments": {"text": "Done in the background."}});
+ assert!(host.refused("chatCall", send).await.contains("stopped"));
}
diff --git a/host/tests/e2e.rs b/host/tests/e2e.rs
index 20617c06..2c51d948 100644
--- a/host/tests/e2e.rs
+++ b/host/tests/e2e.rs
@@ -202,7 +202,7 @@ async fn sent_messages_are_the_reply() {
.to_owned();
let send = |text: &str| json!({"botId": bot, "name": "send_message", "arguments": {"text": text}});
- // Between turns there's no one to talk to.
+ // Before its agent ever ran there's no one to talk to.
let idle = reqwest::Client::new()
.post(format!("{}/api/chatCall", host.base))
.bearer_auth(&host.token)
diff --git a/host/tests/fixtures/late_permission_agent.py b/host/tests/fixtures/late_permission_agent.py
index 6f309ba8..3eaccec9 100644
--- a/host/tests/fixtures/late_permission_agent.py
+++ b/host/tests/fixtures/late_permission_agent.py
@@ -1,18 +1,30 @@
"""ACP agent whose work goes on after its turn (like Hermes' background subagents): it answers each prompt, ends the
turn, then asks permission to edit a file, for its own session `s1`, or for a session the host never opened when the
-prompt says "elsewhere". It logs each answer the host gives to responses.jsonl in its folder."""
+prompt says "elsewhere". A prompt saying EARLY asks before its turn ends instead; one saying SLOW ends only when
+the host cancels it, and asks after that. It logs each answer the host gives to responses.jsonl in its folder."""
import json
import sys
import time
asked = 900
+slow = None # the id of the prompt that waits for session/cancel
def send(value):
print(json.dumps({"jsonrpc": "2.0", **value}), flush=True)
+def ask(session):
+ global asked
+ asked += 1
+ options = [{"optionId": "yes", "name": "Allow", "kind": "allow_once"},
+ {"optionId": "no", "name": "Reject", "kind": "reject_once"}]
+ tool = {"toolCallId": f"t{asked}", "title": "Write notes.md", "kind": "edit"}
+ send({"id": asked, "method": "session/request_permission",
+ "params": {"sessionId": session, "toolCall": tool, "options": options}})
+
+
for line in sys.stdin:
message = json.loads(line)
method, rid = message.get("method"), message.get("id")
@@ -20,6 +32,12 @@ for line in sys.stdin:
with open("responses.jsonl", "a", encoding="utf-8") as f:
f.write(json.dumps(message) + "\n")
continue
+ if method == "session/cancel" and slow is not None:
+ send({"id": slow, "result": {"stopReason": "cancelled"}})
+ slow = None
+ time.sleep(0.5)
+ ask("s1")
+ continue
if method is None or rid is None:
continue
params = message.get("params", {})
@@ -31,14 +49,14 @@ for line in sys.stdin:
text = " ".join(b.get("text", "") for b in params.get("prompt", []))
update = {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "Started it in the background."}}
send({"method": "session/update", "params": {"sessionId": "s1", "update": update}})
+ if "SLOW" in text:
+ slow = rid
+ continue
+ if "EARLY" in text:
+ ask("s1")
send({"id": rid, "result": {"stopReason": "end_turn"}})
- time.sleep(0.5) # the background work takes a while
- asked += 1
- session = "s9" if "elsewhere" in text else "s1"
- options = [{"optionId": "yes", "name": "Allow", "kind": "allow_once"},
- {"optionId": "no", "name": "Reject", "kind": "reject_once"}]
- tool = {"toolCallId": f"t{asked}", "title": "Write notes.md", "kind": "edit"}
- send({"id": asked, "method": "session/request_permission",
- "params": {"sessionId": session, "toolCall": tool, "options": options}})
+ if "EARLY" not in text:
+ time.sleep(0.5) # the background work takes a while
+ ask("s9" if "elsewhere" in text else "s1")
else:
send({"id": rid, "result": {}})
diff --git a/web/content/docs/conversations.mdx b/web/content/docs/conversations.mdx
index 75c7fa2e..b2852b90 100644
--- a/web/content/docs/conversations.mdx
+++ b/web/content/docs/conversations.mdx
@@ -75,7 +75,7 @@ The agent waits for your answer. If the turn ends before you answer, for example
With **Approve automatically**, no cards appear: Codync allows each request for you. Your agent's own permission rules still apply under any setting. To change the setting, see [Bots](/docs/bots#permissions).
-Some agents keep working after their reply, for example a background helper that finishes a long job. With **Approve automatically**, what that work asks is allowed too, until you stop the bot; under any other setting it's declined, since no card can wait for you. When that work is done, the bot can still send you its result as a message in its chat.
+Some agents keep working after their reply, for example a background helper that finishes a long job. With **Approve automatically**, what that work asks is allowed too, unless you stopped the bot's latest reply; under any other setting it's declined, since no card can wait for you. Once the bot is idle there's no **Stop**: to stop approving that work, switch the bot to **Ask me**. When that work is done, the bot can still send you its result as a message in its chat, unless you stopped its latest reply.
## Stopping a turn
diff --git a/web/content/docs/remote-access.mdx b/web/content/docs/remote-access.mdx
index f8f151af..3813e6eb 100644
--- a/web/content/docs/remote-access.mdx
+++ b/web/content/docs/remote-access.mdx
@@ -138,4 +138,4 @@ Webhook deliveries are **not** end-to-end encrypted. The relay receives them ove
- **On the computer:** in **Settings → Computers**, the list **Devices that can use** the computer has **Revoke access** for each device. Without the desktop app, use `codync-host devices` to list devices and `codync-host devices revoke <key>` to remove one. The device disconnects right away and has to pair or ask again.
- **On the iPhone:** in **Manage computers**, remove a paired computer, or revoke this phone's account access to one. The computer keeps its bots and chats.
- **Remove from account** on a computer's card disconnects devices approved through the account. Devices paired with a QR code keep their access.
-- **A computer that's gone** (reset, reinstalled or given away) stays offline in your account. In the desktop app, **Settings → Computers** lists it under **Other computers in your account**; choose **Remove from account** on its row. On your phone, remove it from its computers list.
+- **A computer that's gone** (reset, reinstalled or given away) stays offline in your account. In the desktop app, **Settings → Computers** lists it under **Other computers in your account**; choose **Remove from account** on its row. Any offline computer has it, so first make sure it's gone rather than asleep: devices approved through the account lose access, and it rejoins only when you add it again on that computer. Only the desktop app removes a computer from the account; on a phone you can only forget a computer you paired with a QR code.