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: keep every bot in the mode the user picked

leepokai775f1e92c737
diff --git a/apps/android/app/src/androidTest/kotlin/com/codync/android/BotEditorTest.kt b/apps/android/app/src/androidTest/kotlin/com/codync/android/BotEditorTest.kt
index 2c7809b7..7571a2e3 100644
--- a/apps/android/app/src/androidTest/kotlin/com/codync/android/BotEditorTest.kt
+++ b/apps/android/app/src/androidTest/kotlin/com/codync/android/BotEditorTest.kt
@@ -110,7 +110,10 @@ class BotEditorTest {
compose.onNodeWithContentDescription("Workspace").performClick()
compose.onNodeWithText("Personal workspace").performClick()
compose.onNodeWithText("This bot has its own space for files. It can work in other folders when you ask.").assertIsDisplayed()
- compose.onNodeWithContentDescription("Permissions: Approve automatically").performScrollTo().performClick()
+ // A new bot works in the agent's Auto mode; while the agent's modes load, Auto, Ask me and Approve automatically.
+ compose.onNodeWithText("The agent decides what's safe and asks you about the rest.").performScrollTo().assertIsDisplayed()
+ compose.onNodeWithContentDescription("Permissions: Auto").performClick()
+ compose.onNodeWithText("Approve automatically").assertIsDisplayed()
compose.onNodeWithText("Ask me").performClick()
compose.onNodeWithText("You'll get an approval card and a notification whenever the agent asks.").assertIsDisplayed()
toggle("Notifications").performScrollTo().assertIsOn().performClick().assertIsOff()
@@ -123,6 +126,19 @@ class BotEditorTest {
compose.onNodeWithText("Choose workspace").assertIsDisplayed()
}
+ @Test fun permissionsListTheAgentsOwnModesWithTheirWords() {
+ val claude = AgentModels(emptyList(), modes = listOf(AgentMode("auto", "Auto", "Claude handles permission decisions"),
+ AgentMode("default", "Manual", "Always ask before making changes"), AgentMode("plan", "Plan")))
+ var draft by mutableStateOf(scout)
+ compose.setContent { Hosted { ApprovalRow(fixture(), { claude }, draft, { draft = it }) } }
+ compose.onNodeWithText("Claude handles permission decisions", substring = true).assertIsDisplayed()
+ compose.onNodeWithContentDescription("Permissions: Auto").performClick()
+ compose.onNodeWithText("Approve automatically").assertIsDisplayed()
+ compose.onNodeWithText("Manual").performClick()
+ compose.onNodeWithText("Always ask before making changes", substring = true).assertIsDisplayed()
+ assertEquals("ask" to "default", draft.permission to draft.mode)
+ }
+
@Test fun offlineSettingsDisableSavingButKeepTheModelEditable() {
render(scout.copy(model = "old-model"), fixture().copy(actualConnection = LinkState.Connecting))
compose.onNodeWithContentDescription("Save").assertIsNotEnabled()
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ApprovalRow.kt b/apps/android/app/src/main/kotlin/com/codync/android/ApprovalRow.kt
index 6ffbe2a8..bd62486e 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/ApprovalRow.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ApprovalRow.kt
@@ -29,9 +29,8 @@ import kotlinx.coroutines.CancellationException
// The model picker says why; Auto, Ask me and Approve automatically stay on offer meanwhile.
catch (error: Exception) { Log.i("Codync", "no agent modes for ${draft.backend}: ${error.message}") }
}
- val choices = ApprovalChoice.all(catalog)
- val selected = ApprovalChoice.selected(draft, choices, catalog)
- ValueRow("Permissions", detail = selected?.let { listOfNotNull(it.note, tr(it.detail)).joinToString(" ") }) {
- ChoicePicker(selected?.id.orEmpty(), choices.map { it.id to it.label }, { change(draft.withApproval(it)) }, label = "Permissions")
+ val (choices, selected) = ApprovalChoice.choices(draft, catalog)
+ ValueRow("Permissions", detail = listOfNotNull(selected.note, tr(selected.detail)).joinToString(" ")) {
+ ChoicePicker(selected.id, choices.map { it.id to it.label }, { change(draft.withApproval(it)) }, label = "Permissions")
}
}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/AgentSettings.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/AgentSettings.kt
index 3818abfb..3b08b605 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/AgentSettings.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/AgentSettings.kt
@@ -9,9 +9,9 @@ import kotlinx.serialization.Serializable
@Serializable data class ModelOptionValue(val id: String, val name: String)
@Serializable data class AgentModel(val id: String, val name: String, val description: String? = null, val options: List<ModelOption>? = null, val optionsError: String? = null)
/** `fastMode`: the agent offers Fast mode (absent on older hosts). `modes`: its modes, Auto first and listed as `auto`
- * (absent on older hosts); `currentModeId`: the one its sessions start in. */
+ * (absent on older hosts). */
@Serializable data class AgentModels(val models: List<AgentModel>, val currentModelId: String? = null, val fastMode: Boolean? = null, val defaultModelOptions: Boolean? = null,
- val modes: List<AgentMode>? = null, val currentModeId: String? = null) {
+ val modes: List<AgentMode>? = null) {
val agentDefault: AgentModel? get() = models.firstOrNull { it.name.lowercase().startsWith("default") }
fun options(selected: String?): List<ModelChoice> {
val default = agentDefault
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Approvals.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Approvals.kt
index ca78fd7a..b3408697 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Approvals.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Approvals.kt
@@ -15,27 +15,35 @@ data class ApprovalChoice(val id: String, val label: String, val note: String?,
companion object {
const val ASK = "ask"
const val APPROVE = "approve"
+ private const val ASKS = "Anything the agent still asks about comes to you as an approval card."
+ private val askMe = ApprovalChoice(ASK, "Ask me", null, "You'll get an approval card and a notification whenever the agent asks.")
private fun modeId(mode: String) = "mode:$mode"
/**
- * The agent's modes, its Auto mode first, then Codync approving everything. An agent without modes offers Ask me
- * instead; while its list loads (or from an older host), Auto and Ask me.
+ * The choices for [draft] on an agent with this model list (null while it loads), and the one its setting shows
+ * as: the agent's modes, its Auto mode first, then Codync approving everything. An agent without modes offers
+ * Ask me instead; while its list loads (or from an older host), Auto and Ask me. A bot without a mode (or in
+ * Auto on an agent without one) shows as Ask me, and one in a mode the list lacks as that mode's id: never as
+ * more careful than it is.
*/
- fun all(catalog: AgentModels?): List<ApprovalChoice> {
- val ask = ApprovalChoice(ASK, "Ask me", null, "You'll get an approval card and a notification whenever the agent asks.")
+ fun choices(draft: BotDraft, catalog: AgentModels?): Pair<List<ApprovalChoice>, ApprovalChoice> {
val approve = ApprovalChoice(APPROVE, "Approve automatically", null,
"Tool requests are approved automatically. Your agent's own settings (like Claude Code's permission rules) still apply.")
val modes = catalog?.modes
- ?: return listOf(ApprovalChoice(modeId(AgentMode.AUTO), "Auto", null, "The agent decides what's safe and asks you about the rest."), ask, approve)
- if (modes.isEmpty()) return listOf(ask, approve)
- return modes.map { ApprovalChoice(modeId(it.id), it.name, it.description, "Anything the agent still asks about comes to you as an approval card.") } + approve
- }
-
- /** The choice a bot's setting shows as: an unset mode is the one the agent starts in. */
- fun selected(draft: BotDraft, choices: List<ApprovalChoice>, catalog: AgentModels?): ApprovalChoice? {
- if (draft.permission == "auto") return choices.firstOrNull { it.id == APPROVE }
- val mode = draft.mode ?: catalog?.currentModeId
- return mode?.let { m -> choices.firstOrNull { it.id == modeId(m) } } ?: choices.firstOrNull { it.id == ASK } ?: choices.firstOrNull()
+ val all = when {
+ modes == null -> mutableListOf(ApprovalChoice(modeId(AgentMode.AUTO), "Auto", null, "The agent decides what's safe and asks you about the rest."), askMe)
+ modes.isEmpty() -> mutableListOf(askMe)
+ else -> modes.mapTo(mutableListOf()) { ApprovalChoice(modeId(it.id), it.name, it.description, ASKS) }
+ }
+ all += approve
+ if (draft.permission == "auto") return all to approve
+ val mode = draft.mode
+ // Unlisted: Auto on an agent without it is its default, like no mode; any other mode is itself.
+ val unlisted = if (mode != null && mode != AgentMode.AUTO) ApprovalChoice(modeId(mode), mode, null, ASKS) else askMe
+ val found = all.firstOrNull { it.id == (mode?.let(::modeId) ?: ASK) } ?: all.firstOrNull { it.id == unlisted.id }
+ if (found != null) return all to found
+ all.add(all.size - 1, unlisted)
+ return all to unlisted
}
}
}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/ApprovalsTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/ApprovalsTest.kt
index 748905fa..a513f529 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/ApprovalsTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/ApprovalsTest.kt
@@ -7,8 +7,9 @@ import org.junit.Test
class ApprovalsTest {
private val codex = AgentModels(emptyList(), modes = listOf(
- AgentMode("auto", "Auto review", "Only ask for actions detected as potentially unsafe"), AgentMode("read-only", "Read-only")),
- currentModeId = "auto")
+ AgentMode("auto", "Auto review", "Only ask for actions detected as potentially unsafe"), AgentMode("read-only", "Read-only")))
+
+ private fun labels(draft: BotDraft, catalog: AgentModels?) = ApprovalChoice.choices(draft, catalog).first.map { it.label }
@Test fun newBotsStartInTheAgentsAutoModeAndAsk() {
val draft = BotDraft(name = "New")
@@ -17,27 +18,35 @@ class ApprovalsTest {
}
@Test fun approvalsListTheAgentsModesThenApproveAutomatically() {
- val choices = ApprovalChoice.all(codex)
- assertEquals(listOf("Auto review", "Read-only", "Approve automatically"), choices.map { it.label })
- assertEquals("Only ask for actions detected as potentially unsafe", choices.first().note)
var draft = BotDraft(name = "Bot", backend = "codex")
- assertEquals("Auto review", ApprovalChoice.selected(draft, choices, codex)?.label)
- assertEquals("Auto review", ApprovalChoice.selected(draft.copy(mode = null), choices, codex)?.label)
+ val (choices, selected) = ApprovalChoice.choices(draft, codex)
+ assertEquals(listOf("Auto review", "Read-only", "Approve automatically"), choices.map { it.label })
+ assertEquals("Auto review" to "Only ask for actions detected as potentially unsafe", selected.label to selected.note)
draft = draft.withApproval(choices[1].id)
assertEquals("ask" to "read-only", draft.permission to draft.mode)
draft = draft.withApproval(ApprovalChoice.APPROVE)
assertEquals("auto" to null, draft.permission to draft.mode)
// Approve automatically clears the mode on the host too.
assertEquals(JsonNull, draft.copy(id = "b").body()["mode"])
- assertEquals("Approve automatically", ApprovalChoice.selected(draft, choices, codex)?.label)
+ assertEquals("Approve automatically", ApprovalChoice.choices(draft, codex).second.label)
+ }
+
+ @Test fun aBotNeverShowsAsMoreCarefulThanItIs() {
+ // Without a mode it works in the agent's default, and asks.
+ val unset = BotDraft(name = "Bot", mode = null)
+ assertEquals(listOf("Auto review", "Read-only", "Ask me", "Approve automatically"), labels(unset, codex))
+ assertEquals("Ask me", ApprovalChoice.choices(unset, codex).second.label)
+ // A mode the list lacks (or that hasn't loaded) shows as itself.
+ val bypass = BotDraft(name = "Bot", mode = "bypassPermissions")
+ assertEquals(listOf("Auto", "Ask me", "bypassPermissions", "Approve automatically"), labels(bypass, null))
+ assertEquals("bypassPermissions", ApprovalChoice.choices(bypass, null).second.label)
}
@Test fun anAgentWithoutAutoAsksAndOneStillLoadingOffersAuto() {
val plain = AgentModels(emptyList(), modes = emptyList())
- val choices = ApprovalChoice.all(plain)
- assertEquals(listOf("Ask me", "Approve automatically"), choices.map { it.label })
- assertEquals("Ask me", ApprovalChoice.selected(BotDraft(name = "Bot"), choices, plain)?.label)
- assertEquals(listOf("Auto", "Ask me", "Approve automatically"), ApprovalChoice.all(null).map { it.label })
+ assertEquals(listOf("Ask me", "Approve automatically"), labels(BotDraft(name = "Bot"), plain))
+ assertEquals("Ask me", ApprovalChoice.choices(BotDraft(name = "Bot"), plain).second.label)
+ assertEquals(listOf("Auto", "Ask me", "Approve automatically"), labels(BotDraft(name = "Bot"), null))
// Another agent's ids mean nothing: a picked mode becomes its Auto mode.
assertEquals("auto", BotDraft(name = "Bot", mode = "plan").withAgent("codex").mode)
assertEquals(null, BotDraft(name = "Bot", mode = null).withAgent("codex").mode)
diff --git a/apps/desktop/src/renderer/views/bots/ApprovalRow.tsx b/apps/desktop/src/renderer/views/bots/ApprovalRow.tsx
index 6e686f8c..ba05c6c7 100644
--- a/apps/desktop/src/renderer/views/bots/ApprovalRow.tsx
+++ b/apps/desktop/src/renderer/views/bots/ApprovalRow.tsx
@@ -1,4 +1,4 @@
-import { approvalChoices, selectedApproval, withApproval, type ModeCatalog } from '@shared/approvals'
+import { approvals, withApproval, type ModeCatalog } from '@shared/approvals'
import type { BotDraft } from '@shared/models'
import { ChoicePicker, ValueRow } from '../../components/Controls'
import { useTr } from '../../lib/use-language'
@@ -10,13 +10,12 @@ export function ApprovalRow({ draft, catalog, onChange }: {
onChange: (update: (d: BotDraft) => BotDraft) => void
}) {
const tr = useTr()
- const choices = approvalChoices(catalog)
- const selected = selectedApproval(draft, choices, catalog)
- const detail = selected ? [selected.note, tr(selected.detail)].filter(Boolean).join(' ') : null
+ const { choices, selected } = approvals(draft, catalog)
+ const detail = [selected.note, tr(selected.detail)].filter(Boolean).join(' ')
return (
<ValueRow label="Permissions" detail={detail}>
<ChoicePicker
- selection={selected?.id ?? ''}
+ selection={selected.id}
options={choices.map((c) => ({ id: c.id, label: c.label }))}
onChange={(id) => onChange((d) => withApproval(d, id))}
/>
diff --git a/apps/desktop/src/renderer/views/bots/agent-models.ts b/apps/desktop/src/renderer/views/bots/agent-models.ts
index c90e7645..d8cc6997 100644
--- a/apps/desktop/src/renderer/views/bots/agent-models.ts
+++ b/apps/desktop/src/renderer/views/bots/agent-models.ts
@@ -21,8 +21,6 @@ export interface AgentModels {
defaultModelOptions?: boolean
/** The agent's modes, its Auto mode first and listed as `auto` (absent on older hosts). */
modes?: AgentMode[]
- /** The mode its sessions start in. */
- currentModeId?: string | null
}
/** What the agent behind `backend` offers, loaded from the selected computer. */
diff --git a/apps/desktop/src/shared/approvals.test.ts b/apps/desktop/src/shared/approvals.test.ts
index bcdf3c4d..d03501cd 100644
--- a/apps/desktop/src/shared/approvals.test.ts
+++ b/apps/desktop/src/shared/approvals.test.ts
@@ -1,34 +1,42 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
-import { approvalChoices, selectedApproval, withApproval } from './approvals.ts'
+import { approvals, withApproval } from './approvals.ts'
import { withBackend } from './fallbacks.ts'
import type { BotDraft } from './models.ts'
const codex = {
modes: [{ id: 'auto', name: 'Auto review', description: 'Only ask for actions detected as potentially unsafe' }, { id: 'read-only', name: 'Read-only' }],
- currentModeId: 'auto',
}
+const labels = (draft: Pick<BotDraft, 'permission' | 'mode'>, catalog: typeof codex | { modes: [] } | null) =>
+ approvals(draft, catalog).choices.map((c) => c.label)
test("approvals list the agent's modes, Auto first, then approve automatically", () => {
- const choices = approvalChoices(codex)
- assert.deepEqual(choices.map((c) => c.label), ['Auto review', 'Read-only', 'Approve automatically'])
- assert.equal(choices[0]!.note, 'Only ask for actions detected as potentially unsafe')
const draft = { permission: 'ask', mode: 'auto' as string | null }
- assert.equal(selectedApproval(draft, choices, codex)?.label, 'Auto review')
- assert.equal(selectedApproval({ permission: 'ask', mode: null }, choices, codex)?.label, 'Auto review', "an unset mode is the agent's start")
+ const { choices, selected } = approvals(draft, codex)
+ assert.deepEqual(choices.map((c) => c.label), ['Auto review', 'Read-only', 'Approve automatically'])
+ assert.equal(selected.label, 'Auto review')
+ assert.equal(selected.note, 'Only ask for actions detected as potentially unsafe')
assert.deepEqual(withApproval(draft, choices[1]!.id), { permission: 'ask', mode: 'read-only' })
const approve = withApproval(draft, choices[2]!.id)
assert.deepEqual(approve, { permission: 'auto', mode: null })
assert.equal(JSON.stringify(approve), '{"permission":"auto","mode":null}', 'null reaches the host and clears it')
- assert.equal(selectedApproval(approve, choices, codex)?.label, 'Approve automatically')
+ assert.equal(approvals(approve, codex).selected.label, 'Approve automatically')
+})
+
+test('a bot never shows as more careful than it is', () => {
+ // Without a mode it works in the agent's default, and asks.
+ assert.equal(approvals({ permission: 'ask', mode: null }, codex).selected.label, 'Ask me')
+ assert.deepEqual(labels({ permission: 'ask', mode: null }, codex), ['Auto review', 'Read-only', 'Ask me', 'Approve automatically'])
+ // A mode the list lacks (or that hasn't loaded) shows as itself.
+ assert.deepEqual(labels({ permission: 'ask', mode: 'bypassPermissions' }, null), ['Auto', 'Ask me', 'bypassPermissions', 'Approve automatically'])
+ assert.equal(approvals({ permission: 'ask', mode: 'bypassPermissions' }, null).selected.label, 'bypassPermissions')
})
test('an agent without Auto asks, and one still loading offers Auto', () => {
- const plain = { modes: [] }
- const choices = approvalChoices(plain)
- assert.deepEqual(choices.map((c) => c.label), ['Ask me', 'Approve automatically'])
- assert.equal(selectedApproval({ permission: 'ask', mode: 'auto' }, choices, plain)?.label, 'Ask me')
- assert.deepEqual(approvalChoices(null).map((c) => c.label), ['Auto', 'Ask me', 'Approve automatically'])
+ const plain = { modes: [] as [] }
+ assert.deepEqual(labels({ permission: 'ask', mode: 'auto' }, plain), ['Ask me', 'Approve automatically'])
+ assert.equal(approvals({ permission: 'ask', mode: 'auto' }, plain).selected.label, 'Ask me')
+ assert.deepEqual(labels({ permission: 'ask', mode: 'auto' }, null), ['Auto', 'Ask me', 'Approve automatically'])
})
test("another agent's mode ids mean nothing: a picked mode becomes its Auto mode", () => {
diff --git a/apps/desktop/src/shared/approvals.ts b/apps/desktop/src/shared/approvals.ts
index 58fef625..f0778343 100644
--- a/apps/desktop/src/shared/approvals.ts
+++ b/apps/desktop/src/shared/approvals.ts
@@ -13,7 +13,6 @@ export interface AgentMode {
/** What an agent's model list says about its modes (`agentModels`); null while it loads. */
export interface ModeCatalog {
modes?: AgentMode[] | null
- currentModeId?: string | null
}
/** A bot's Approvals choice. `note` is the agent's own words, untranslated; `detail` is Codync's, to translate. */
@@ -26,32 +25,36 @@ export interface ApprovalChoice {
const ASK = 'ask'
const APPROVE = 'approve'
+const ASKS = 'Anything the agent still asks about comes to you as an approval card.'
const modeId = (mode: string) => `mode:${mode}`
+const ask: ApprovalChoice = { id: ASK, label: 'Ask me', note: null, detail: "You'll get an approval card and a notification whenever the agent asks." }
/**
- * The agent's modes, its Auto mode first, then Codync approving everything. An agent without modes offers Ask me
- * instead; while its list loads (or from an older host), Auto and Ask me.
+ * The Approvals choices for a bot and the one its setting shows as: the agent's modes, its Auto mode first, then
+ * Codync approving everything. An agent without modes offers Ask me instead; while its list loads (or from an older
+ * host), Auto and Ask me. A bot without a mode (or in Auto on an agent without one) shows as Ask me, and one in a mode
+ * the list lacks as that mode's id: never as more careful than it is.
*/
-export function approvalChoices(catalog: ModeCatalog | null): ApprovalChoice[] {
- const ask = { id: ASK, label: 'Ask me', note: null, detail: "You'll get an approval card and a notification whenever the agent asks." }
- const approve = {
+export function approvals(draft: Pick<BotDraft, 'permission' | 'mode'>, catalog: ModeCatalog | null) {
+ const approve: ApprovalChoice = {
id: APPROVE, label: 'Approve automatically', note: null,
detail: "Tool requests are approved automatically. Your agent's own settings (like Claude Code's permission rules) still apply.",
}
const modes = catalog?.modes
- if (!modes) {
- return [{ id: modeId(AUTO_MODE), label: 'Auto', note: null, detail: "The agent decides what's safe and asks you about the rest." }, ask, approve]
+ const choices: ApprovalChoice[] = !modes
+ ? [{ id: modeId(AUTO_MODE), label: 'Auto', note: null, detail: "The agent decides what's safe and asks you about the rest." }, ask]
+ : !modes.length ? [ask] : modes.map((m) => ({ id: modeId(m.id), label: m.name, note: m.description ?? null, detail: ASKS }))
+ choices.push(approve)
+ const find = (id: string) => choices.find((c) => c.id === id)
+ const mode = draft.mode ?? null
+ // Unlisted: Auto on an agent without it is its default, like no mode; any other mode is itself.
+ const unlisted = mode && mode !== AUTO_MODE ? { id: modeId(mode), label: mode, note: null, detail: ASKS } : ask
+ let selected = draft.permission === 'auto' ? approve : find(mode ? modeId(mode) : ASK) ?? find(unlisted.id)
+ if (!selected) {
+ selected = unlisted
+ choices.splice(choices.length - 1, 0, selected)
}
- if (!modes.length) return [ask, approve]
- const asks = 'Anything the agent still asks about comes to you as an approval card.'
- return [...modes.map((m) => ({ id: modeId(m.id), label: m.name, note: m.description ?? null, detail: asks })), approve]
-}
-
-/** The choice a bot's setting shows as: an unset mode is the one the agent starts in. */
-export function selectedApproval(draft: Pick<BotDraft, 'permission' | 'mode'>, choices: ApprovalChoice[], catalog: ModeCatalog | null) {
- if (draft.permission === 'auto') return choices.find((c) => c.id === APPROVE) ?? null
- const mode = draft.mode ?? catalog?.currentModeId
- return (mode ? choices.find((c) => c.id === modeId(mode)) : undefined) ?? choices.find((c) => c.id === ASK) ?? choices[0] ?? null
+ return { choices, selected }
}
/** The draft with an Approvals choice picked. */
diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.ts
index eab4f9cd..86d6b2c7 100644
--- a/apps/desktop/src/shared/models.ts
+++ b/apps/desktop/src/shared/models.ts
@@ -99,7 +99,7 @@ export function normalizeBot(raw: Partial<Bot> & { id: string }): Bot {
command: raw.command ?? null,
cwd: raw.cwd ?? '',
managedWorkspace: raw.managedWorkspace ?? false,
- permission: raw.permission ?? 'auto',
+ permission: raw.permission ?? 'ask',
mode: raw.mode ?? null,
model: raw.model ?? null,
modelOptions: raw.modelOptions ?? {},
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/AgentMode.swift b/apps/ios/Kit/Sources/CodyncKit/Models/AgentMode.swift
index 98234eac..d40f5e29 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/AgentMode.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/AgentMode.swift
@@ -16,6 +16,7 @@ public struct AgentMode: Decodable, Hashable, Sendable {
public struct ApprovalChoice: Identifiable, Hashable, Sendable {
public static let ask = "ask"
public static let approve = "approve"
+ static let asks = "Anything the agent still asks about comes to you as an approval card."
public let id: String
public let label: String
@@ -24,29 +25,31 @@ public struct ApprovalChoice: Identifiable, Hashable, Sendable {
/// What Codync does, to translate.
public let detail: String
- /// The choices for an agent, from its model list (nil while it loads).
- public static func all(_ catalog: AgentModels?) -> [ApprovalChoice] {
- let ask = ApprovalChoice(id: ask, label: "Ask me", note: nil,
- detail: "You'll get an approval card and a notification whenever the agent asks.")
+ static let askMe = ApprovalChoice(id: ask, label: "Ask me", note: nil,
+ detail: "You'll get an approval card and a notification whenever the agent asks.")
+
+ /// The choices for a bot on an agent with this model list (nil while it loads), and the one its setting shows as.
+ /// A bot without a mode (or in Auto on an agent without one) shows as Ask me, and one in a mode the list lacks as
+ /// that mode's id: never as more careful than it is.
+ public static func choices(permission: String, mode: String?, catalog: AgentModels?) -> (all: [ApprovalChoice], selected: ApprovalChoice) {
let approve = ApprovalChoice(id: approve, label: "Approve automatically", note: nil,
detail: "Tool requests are approved automatically. Your agent's own settings (like Claude Code's permission rules) still apply.")
- guard let modes = catalog?.modes else {
- let auto = ApprovalChoice(id: modeId(AgentMode.auto), label: "Auto", note: nil,
- detail: "The agent decides what's safe and asks you about the rest.")
- return [auto, ask, approve]
+ var all: [ApprovalChoice]
+ if let modes = catalog?.modes {
+ all = modes.isEmpty ? [askMe] : modes.map { ApprovalChoice(id: modeId($0.id), label: $0.name, note: $0.description, detail: asks) }
+ } else {
+ all = [ApprovalChoice(id: modeId(AgentMode.auto), label: "Auto", note: nil,
+ detail: "The agent decides what's safe and asks you about the rest."), askMe]
}
- if modes.isEmpty { return [ask, approve] }
- return modes.map {
- ApprovalChoice(id: modeId($0.id), label: $0.name, note: $0.description,
- detail: "Anything the agent still asks about comes to you as an approval card.")
- } + [approve]
- }
-
- /// The choice a bot's setting shows as: an unset mode is the one the agent starts in.
- public static func selected(permission: String, mode: String?, in choices: [ApprovalChoice], catalog: AgentModels?) -> ApprovalChoice? {
- if permission == "auto" { return choices.first { $0.id == approve } }
- if let mode = mode ?? catalog?.currentModeId, let match = choices.first(where: { $0.id == modeId(mode) }) { return match }
- return choices.first { $0.id == ask } ?? choices.first
+ all.append(approve)
+ if permission == "auto" { return (all, approve) }
+ // Unlisted: Auto on an agent without it is its default, like no mode; any other mode is itself.
+ let unlisted = mode.flatMap { $0 == AgentMode.auto ? nil : ApprovalChoice(id: modeId($0), label: $0, note: nil, detail: asks) } ?? askMe
+ if let found = all.first(where: { $0.id == mode.map(modeId) ?? ask }) ?? all.first(where: { $0.id == unlisted.id }) {
+ return (all, found)
+ }
+ all.insert(unlisted, at: all.count - 1)
+ return (all, unlisted)
}
static func modeId(_ mode: String) -> String { "mode:\(mode)" }
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/AgentModels.swift b/apps/ios/Kit/Sources/CodyncKit/Models/AgentModels.swift
index 106f4358..222a2da8 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/AgentModels.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/AgentModels.swift
@@ -35,6 +35,4 @@ public struct AgentModels: Decodable, Sendable {
public let defaultModelOptions: Bool?
/// The agent's modes, its Auto mode first and listed as `auto` (nil from older hosts).
public let modes: [AgentMode]?
- /// The mode its sessions start in.
- public let currentModeId: String?
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Bot.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Bot.swift
index e46d0279..24f6c96c 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/Bot.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Bot.swift
@@ -116,7 +116,7 @@ extension Bot {
command = try c.decodeIfPresent(String.self, forKey: .command)
cwd = try c.decodeIfPresent(String.self, forKey: .cwd) ?? ""
managedWorkspace = try c.decodeIfPresent(Bool.self, forKey: .managedWorkspace) ?? false
- permission = try c.decodeIfPresent(String.self, forKey: .permission) ?? "auto"
+ permission = try c.decodeIfPresent(String.self, forKey: .permission) ?? "ask"
mode = try c.decodeIfPresent(String.self, forKey: .mode)
model = try c.decodeIfPresent(String.self, forKey: .model)
modelOptions = try c.decodeIfPresent([String: String].self, forKey: .modelOptions) ?? [:]
diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/ApprovalPicker.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/ApprovalPicker.swift
index 18e184f4..bf4656a5 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Bots/ApprovalPicker.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/ApprovalPicker.swift
@@ -10,14 +10,10 @@ struct ApprovalPicker: View {
@Environment(BotStore.self) private var store
@State private var catalog: AgentModels?
- private var choices: [ApprovalChoice] { ApprovalChoice.all(catalog) }
- private var selected: ApprovalChoice? {
- ApprovalChoice.selected(permission: draft.permission, mode: draft.mode, in: choices, catalog: catalog)
- }
-
var body: some View {
- ValueRow("Permissions", detail: selected.map { [$0.note, L10n.tr($0.detail)].compactMap { $0 }.joined(separator: " ") }) {
- ChoicePicker(selection: Binding(get: { selected?.id ?? "" }, set: { draft.setApproval($0) }),
+ let (choices, selected) = ApprovalChoice.choices(permission: draft.permission, mode: draft.mode, catalog: catalog)
+ ValueRow("Permissions", detail: [selected.note, L10n.tr(selected.detail)].compactMap { $0 }.joined(separator: " ")) {
+ ChoicePicker(selection: Binding(get: { selected.id }, set: { draft.setApproval($0) }),
options: choices.map { ($0.id, $0.label) })
}
.task(id: "\(store.computer.id)/\(draft.backend)/\(store.connection == .online)") { await load() }
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/AgentModeTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/AgentModeTests.swift
index bb225287..ee4452f2 100644
--- a/apps/ios/Kit/Tests/CodyncKitTests/AgentModeTests.swift
+++ b/apps/ios/Kit/Tests/CodyncKitTests/AgentModeTests.swift
@@ -14,15 +14,11 @@ private func catalog(_ json: String) throws -> AgentModels {
}
@Test func approvalsListTheAgentsModesThenApproveAutomatically() throws {
- let codex = try catalog(#"{"models":[],"modes":[{"id":"auto","name":"Auto review","description":"Only ask for actions detected as potentially unsafe"},{"id":"read-only","name":"Read-only"}],"currentModeId":"auto"}"#)
- let choices = ApprovalChoice.all(codex)
- #expect(choices.map(\.label) == ["Auto review", "Read-only", "Approve automatically"])
- #expect(choices.first?.note == "Only ask for actions detected as potentially unsafe")
-
+ let codex = try catalog(#"{"models":[],"modes":[{"id":"auto","name":"Auto review","description":"Only ask for actions detected as potentially unsafe"},{"id":"read-only","name":"Read-only"}]}"#)
var draft = BotDraft(name: "Bot", backend: "codex")
- #expect(ApprovalChoice.selected(permission: draft.permission, mode: draft.mode, in: choices, catalog: codex)?.label == "Auto review")
- // An unset mode is the one the agent starts in.
- #expect(ApprovalChoice.selected(permission: "ask", mode: nil, in: choices, catalog: codex)?.label == "Auto review")
+ let (choices, selected) = ApprovalChoice.choices(permission: draft.permission, mode: draft.mode, catalog: codex)
+ #expect(choices.map(\.label) == ["Auto review", "Read-only", "Approve automatically"])
+ #expect((selected.label, selected.note) == ("Auto review", "Only ask for actions detected as potentially unsafe"))
draft.setApproval(choices[1].id)
#expect((draft.permission, draft.mode) == ("ask", "read-only"))
draft.setApproval(ApprovalChoice.approve)
@@ -31,15 +27,27 @@ private func catalog(_ json: String) throws -> AgentModels {
draft.id = "b"
let body = try #require(JSONSerialization.jsonObject(with: JSONEncoder().encode(BotUpdate(draft: draft))) as? [String: Any])
#expect(body["mode"] is NSNull)
- #expect(ApprovalChoice.selected(permission: draft.permission, mode: draft.mode, in: choices, catalog: codex)?.label == "Approve automatically")
+ #expect(ApprovalChoice.choices(permission: draft.permission, mode: draft.mode, catalog: codex).selected.label == "Approve automatically")
+}
+
+@Test func aBotNeverShowsAsMoreCarefulThanItIs() throws {
+ let codex = try catalog(#"{"models":[],"modes":[{"id":"auto","name":"Auto review"},{"id":"read-only","name":"Read-only"}]}"#)
+ // Without a mode it works in the agent's default, and asks.
+ let unset = ApprovalChoice.choices(permission: "ask", mode: nil, catalog: codex)
+ #expect(unset.all.map(\.label) == ["Auto review", "Read-only", "Ask me", "Approve automatically"])
+ #expect(unset.selected.label == "Ask me")
+ // A mode the list lacks (or that hasn't loaded) shows as itself.
+ let bypass = ApprovalChoice.choices(permission: "ask", mode: "bypassPermissions", catalog: nil)
+ #expect(bypass.all.map(\.label) == ["Auto", "Ask me", "bypassPermissions", "Approve automatically"])
+ #expect(bypass.selected.label == "bypassPermissions")
}
@Test func anAgentWithoutAutoAsksAndOneStillLoadingOffersAuto() throws {
let plain = try catalog(#"{"models":[],"modes":[]}"#)
- let choices = ApprovalChoice.all(plain)
- #expect(choices.map(\.label) == ["Ask me", "Approve automatically"])
- #expect(ApprovalChoice.selected(permission: "ask", mode: "auto", in: choices, catalog: plain)?.label == "Ask me")
- #expect(ApprovalChoice.all(nil).map(\.label) == ["Auto", "Ask me", "Approve automatically"])
+ let asks = ApprovalChoice.choices(permission: "ask", mode: "auto", catalog: plain)
+ #expect(asks.all.map(\.label) == ["Ask me", "Approve automatically"])
+ #expect(asks.selected.label == "Ask me")
+ #expect(ApprovalChoice.choices(permission: "ask", mode: "auto", catalog: nil).all.map(\.label) == ["Auto", "Ask me", "Approve automatically"])
// Another agent's ids mean nothing: a picked mode becomes its Auto mode.
var draft = BotDraft(name: "Bot")
diff --git a/docs/architecture/file-structure.md b/docs/architecture/file-structure.md
index f398ac39..f47a4bde 100644
--- a/docs/architecture/file-structure.md
+++ b/docs/architecture/file-structure.md
@@ -19,7 +19,7 @@ Codync/
│ │ ├── chat/ # Groups, bot-to-bot requests, prompt snapshots, memory
│ │ ├── remote/ # Identity, wire crypto, E2E channel, cloud, relay socket, push
│ │ ├── market/ # Marketplace (registry.rs, install.rs, skills.rs), Composio, MCP OAuth
-│ │ └── tui/ # Terminal client (app/: state and input; view/: drawing; manage/ + sheets.rs: settings; connections.rs: secure connection requests)
+│ │ └── tui/ # Terminal client (app/: state and input, the bot form in forms.rs + approvals.rs, the group form in group_form.rs; view/: drawing; manage/ + sheets.rs: settings; connections.rs: secure connection requests)
│ └── tests/ # Host integration tests and scripted ACP agents
├── apps/
│ ├── project.yml # XcodeGen source of truth for every Apple target
@@ -103,6 +103,7 @@ Codync/
| Host cloud state and relay connection | `host/src/remote/cloud.rs`, `cloud_url.rs`, `relay.rs` |
| Agent discovery, sign-in, setup terminal, Node.js for npm agents | `host/src/agent/backends.rs` (+ `backends/catalog.rs` the known harnesses, `backends/sign_in.rs`, `backends/search_path.rs`, `backends/workbuddy.rs` the CLI inside the WorkBuddy app), `registry.rs`, `auth.rs` (+ `auth/agent.rs` starting an agent and its own sign-in, `auth/models.rs`), `term.rs`, `node.rs` |
| Fast mode (session config option) | `host/src/agent/config.rs`, `agent/bot/fast_mode.rs` |
+| Agent modes (Permissions) | `host/src/agent/modes.rs` (the modes, Auto, `switch`), `agent/bot/modes.rs` (each session's mode), `agent/auth/models.rs` (`agentModels`, `InFlight`); terminal `host/src/tui/app/approvals.rs`; iPhone `CodyncKit/Models/AgentMode.swift`, `CodyncUI/Bots/ApprovalPicker.swift`; Android `core/Approvals.kt`, `ApprovalRow.kt`; desktop `src/shared/approvals.ts`, `views/bots/ApprovalRow.tsx` |
| Marketplace, Composio, connector OAuth | `host/src/market/` |
| Skills a bot writes (`save_skill`) | `host/src/chat/skills.rs`, stored by `host/src/market/skills.rs` |
| Artifacts (`publish_artifact`) and a chat's Library | `host/src/chat/artifacts.rs`, `library.rs`; desktop `apps/desktop/src/renderer/views/library/` (+ `src/main/artifacts.ts`); iPhone `apps/ios/Kit/Sources/CodyncUI/Artifacts/` (+ `Store/ArtifactCache.swift`, `BotStore+Artifacts.swift`); Android `ArtifactCardView.kt`, `ArtifactViewer.kt`, `ArtifactWebView.kt`, `LibraryView.kt`, `AppStoreArtifacts.kt` (+ `core/Artifact.kt`, `core/Library.kt`); terminal `host/src/tui/net/artifacts.rs`, `manage/library.rs` |
diff --git a/docs/features/agent-fallback.md b/docs/features/agent-fallback.md
index d5867a51..58bbdbfd 100644
--- a/docs/features/agent-fallback.md
+++ b/docs/features/agent-fallback.md
@@ -45,7 +45,9 @@ What their issues taught, and the answer here:
- Each agent appears once, the bot's own included. Making a fallback the bot's own agent drops it from the list
(`fallback::tidy`).
- Everything else is the bot's for every step: folder, approvals, connectors, skills, computer use, memory, fast mode
- where the step's agent has it (`fallback::effective`).
+ where the step's agent has it (`fallback::effective`). Its mode too ([agent modes](marketplace.md#agent-modes)):
+ `auto` is each step's own Auto mode, and a step whose agent lacks any other mode fails the turn rather than work in
+ its default.
## When the bot moves on (`fallback::reason`)
diff --git a/docs/features/bot-collaboration.md b/docs/features/bot-collaboration.md
index dea65586..e7a60581 100644
--- a/docs/features/bot-collaboration.md
+++ b/docs/features/bot-collaboration.md
@@ -83,8 +83,8 @@ Bot request chains can make at most eight handoffs. A request turn messages no o
A bot whose settings have **Manage the team** on (off by default; only the user turns it on, on any client; a client hides the switch for a host that sends no `manageTeam`) also gets the built-in `manage` MCP server, so a lead bot can hire and set up the specialists it needs:
-- `list_team`: every agent bot, the manager itself (`you: true`) and hidden ones included, with its setup (instructions, agent, model and its settings, fallbacks, avatar, folder, approvals, whether it manages the team, who created it) and routines.
-- `create_bot {name, instructions?, agent?, model?, avatarColor?, avatarShape?, folder?, routines?}`: a new bot with the agent a client's new bot gets. It manages the team too, and takes the manager's approval setting, connectors and skills, so it can't act more freely or reach more than the manager (a bot under Ask can't create bots that don't ask; connectors the user turned off for the manager stay off); it never gets computer use. Without an avatar it gets a random look, as a client's new bot does. `routines` are `save_routine` bodies. Bots stop making bots at 20 that bots made (deleted ones don't count), so managers that make managers can't multiply without end; past that the manager asks the user.
+- `list_team`: every agent bot, the manager itself (`you: true`) and hidden ones included, with its setup (instructions, agent, model and its settings, fallbacks, avatar, folder, approvals, agent `mode`, whether it manages the team, who created it) and routines.
+- `create_bot {name, instructions?, agent?, model?, avatarColor?, avatarShape?, folder?, routines?}`: a new bot with the agent a client's new bot gets. It manages the team too, and takes the manager's approval setting and agent mode, connectors and skills, so it can't act more freely or reach more than the manager (a bot under Ask can't create bots that don't ask; connectors the user turned off for the manager stay off); it never gets computer use. A manager in one of its agent's own modes, such as Plan, creates bots only on that agent: another may not have the mode. Without an avatar it gets a random look, as a client's new bot does. `routines` are `save_routine` bodies. Bots stop making bots at 20 that bots made (deleted ones don't count), so managers that make managers can't multiply without end; past that the manager asks the user.
- `update_bot {botId, name?, instructions?, model?, fallbacks?, avatarColor?, avatarShape?, hidden?, routines?}`: any agent bot, the manager itself included; a routine with an `id` replaces that routine (one of that bot's). `fallbacks` (up to 3 `{agent, model?}`, [agent fallbacks](agent-fallback.md)) replaces the bot's list, also for a bot whose user turned "Let the bot change its fallbacks" off: that switch is about the bot's own `set_fallbacks`. A changed model drops the bot's model settings (effort…); setting those, turning Manage the team on or off, deleting bots and every other setting stay with the user. No model id sets how the agent approves tools (`opus[mode=acceptEdits]`): the host never sends a model option of the agent's `mode` category. A new agent or model that arrives during a turn (the manager changing its own) restarts the agent once that turn ends, not in the middle of it; this holds for a change from the settings too.
A manager doesn't run other bots' routines. To test a teammate's, it asks that bot with `message_bot` to run it with its own `run_routine` (by id), so the run is the owner's: its routine session, timeout, retries, run history and result in the owner's chat. The `manage` instructions say so, the `routines` instructions let a bot do it when another bot asks for one of its own routines, and `run_routine` with an id that isn't the caller's fails with that hint ([routines](routines.md#conversational-setup-and-tools)). A hidden bot can't be messaged, so for its routine the manager asks the user to run it from that bot.
diff --git a/docs/features/marketplace.md b/docs/features/marketplace.md
index 8224d270..f66d01da 100644
--- a/docs/features/marketplace.md
+++ b/docs/features/marketplace.md
@@ -104,7 +104,7 @@ See [file structure](../architecture/file-structure.md), [bot collaboration](bot
## Model selection
-The shared bot editor requests `agentModels {backend}` from the selected computer. The host starts an isolated ACP session under its probe directory with saved agent credentials, no MCP servers and no prompt, then closes the process. The response is `{models: [{id, name, description, options, optionsError?}], currentModelId, fastMode, defaultModelOptions, modes, currentModeId}` (modes: see Agent modes). The host keeps each agent's answer for a minute and hands one in progress to the asks that come meanwhile (`auth::Recent`): an editor asks from the model picker and Permissions at once, and each ask would otherwise start the agent.
+The shared bot editor requests `agentModels {backend}` from the selected computer. The host starts an isolated ACP session under its probe directory with saved agent credentials, no MCP servers and no prompt, then closes the process. The response is `{models: [{id, name, description, options, optionsError?}], currentModelId, fastMode, defaultModelOptions, modes}` (modes: see Agent modes). The host hands a list in progress to the asks for the same agent that come meanwhile (`auth::InFlight`): an editor asks from the model picker and Permissions at once, and each ask would otherwise start the agent. An ask after the list came (Refresh) fetches it again.
Discovery prefers ACP `configOptions` with category `model` (including grouped options), with conventional `model`/`models` IDs as a compatibility fallback. Older agents may expose `models.availableModels`. Model names and IDs come from the agent; Codync does not bundle a provider catalog. See the [ACP config option contract](https://agentclientprotocol.com/protocol/v1/session-config-options).
@@ -140,9 +140,9 @@ Clients show Fast mode for an agent bot unless its runtime says `unsupported` (a
Agents list how they ask before acting as session modes: a `configOptions` entry with category `mode`, or the older `modes` field (`agent/modes.rs`). Claude's adapter offers Manual (`default`), Accept edits, Plan, Auto and, where allowed, Bypass permissions; Codex's offers Read-only, Workspace access, Auto review (`agent`) and Full access. ACP itself has no classifier: Claude's Auto is Claude Code's auto mode, Codex's Auto review its guardian reviewer.
-A bot's `mode` names the one it works in: the agent's own id, or `auto` for the agent's Auto mode whatever its id (`auto`, or the one named "Auto review"), so the choice carries over to another agent or a fallback. Unset keeps the agent's default. `agentModels` lists the modes as `{modes: [{id, name, description}], currentModeId}`, the Auto mode first and under `auto`. Clients show them as the Permissions choices, then Approve automatically; an agent without modes shows Ask me instead, and one whose list hasn't loaded shows Auto, Ask me and Approve automatically (`ApprovalChoice` on iOS and Android, `shared/approvals.ts` on the desktop, `tui/app/approvals.rs`). `permission` stays what Codync does with a request that still reaches it: `ask` (a card) or `auto` (approve).
+A bot's `mode` names the one it works in: the agent's own id, or `auto` for the agent's Auto mode whatever its id (Claude's `auto`, or the one named "Auto review"; another agent's `auto`, like Goose's that approves every tool call, isn't it and isn't offered), so the choice carries over to another agent or a fallback that has one. Unset keeps the mode the session opened in (the agent's default). `agentModels` lists the modes as `modes: [{id, name, description}]`, the Auto mode first and under `auto`. Clients show them as the Permissions choices, then Approve automatically; an agent without modes shows Ask me instead, and one whose list hasn't loaded shows Auto, Ask me and Approve automatically (`ApprovalChoice` on iOS and Android, `shared/approvals.ts` on the desktop, `tui/app/approvals.rs`). A bot without a mode, or in Auto on an agent without one, shows as Ask me, and one in a mode the list lacks as that mode's id, never as more careful than it is. `permission` stays what Codync does with a request that still reaches it: `ask` (a card) or `auto` (approve).
-New bots get `permission: ask` and `mode: auto` (`new_bot::with_defaults`, when the client picks neither), the lead and imported bots included; a bot a manager creates gets the manager's. Bots made before keep theirs. The actor sets the mode once per session, before its first turn and again after the user picks another (`agent/bot/modes.rs`), with `session/set_config_option` or `session/set_mode`. The agent may leave it during the session (Claude leaves Plan once the plan is approved, and turns Auto into Accept edits on a model without it, with a notice of its own), and that stands until the next session. A switch the agent refuses fails the turn, so a bot never works in a mode the user didn't pick. An agent that doesn't offer the mode keeps its default, and Codync asks about whatever it asks.
+New bots get `permission: ask` and `mode: auto` (`new_bot::with_defaults`, when the client picks neither), the lead and imported bots included; a bot a manager creates gets the manager's, on the manager's agent only (`create_bot` on another agent is refused while the manager works in one of its agent's own modes). Bots made before keep theirs. Changing a bot's agent turns a picked mode into `auto`, in the clients and on the host (`hub/patch.rs`) alike. The actor sets the mode once per session, before its first turn and again after the user picks another (`agent/bot/modes.rs`, the decision in `modes::switch`), with `session/set_config_option` or `session/set_mode`; cleared, the session goes back to the mode it opened in. The agent may leave it during the session (Claude leaves Plan once the plan is approved, and turns Auto into Accept edits on a model without it, with a notice of its own), and that stands until the next session. A mode the agent doesn't list (a fallback's other agent, say) or refuses to switch to fails the turn, so a bot never works in a mode the user didn't pick. Only `auto` on an agent without an Auto mode keeps the agent's own, and Codync asks about whatever it asks.
## Secure connection setup
diff --git a/host/src/agent/auth.rs b/host/src/agent/auth.rs
index 583d7e78..d344a5a2 100644
--- a/host/src/agent/auth.rs
+++ b/host/src/agent/auth.rs
@@ -33,7 +33,7 @@ mod agent;
mod models;
pub use agent::authenticate;
use agent::start;
-pub use models::{Recent, models, recent_models};
+pub use models::{InFlight, models, shared_models};
pub(crate) use models::{model_config, model_ids};
#[derive(Clone, Debug, Serialize)]
diff --git a/host/src/agent/auth/models.rs b/host/src/agent/auth/models.rs
index a93dd5b2..c0d13146 100644
--- a/host/src/agent/auth/models.rs
+++ b/host/src/agent/auth/models.rs
@@ -8,41 +8,35 @@ use crate::store::Store;
use anyhow::{Context, Result, bail};
use serde_json::{Value, json};
use std::collections::HashMap;
-use std::sync::{Arc, Mutex as StdMutex};
-use std::time::{Duration, Instant};
-use tokio::sync::Mutex;
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+use tokio::sync::OnceCell;
-/// Model lists from the last minute, by agent: a settings screen asks for one from several places at once (the model
-/// picker, Approvals), and each would otherwise start the agent.
+/// Model lists being fetched, by agent: a settings screen asks for one from several places at once (the model
+/// picker, Approvals), and each would otherwise start the agent. An ask after one came fetches afresh.
#[derive(Default)]
-pub struct Recent(StdMutex<HashMap<String, Slot>>);
+pub struct InFlight(Mutex<HashMap<String, Slot>>);
-/// One agent's list and when it came; locked while it's asked for.
-type Slot = Arc<Mutex<Option<(Instant, Value)>>>;
+/// One fetch's answer, for every ask that came while it ran (a failure as its text).
+type Slot = Arc<OnceCell<Result<Value, String>>>;
-impl Recent {
- /// `fetch`'s list for `agent`, or the one fetched in the last minute; one in progress answers those that come
- /// meanwhile. A failure is kept by no one.
+impl InFlight {
async fn get(&self, agent: &str, fetch: impl Future<Output = Result<Value>>) -> Result<Value> {
let slot = self.0.locked().entry(agent.to_owned()).or_default().clone();
- let mut listed = slot.lock().await;
- if let Some((at, catalog)) = listed.as_ref()
- && at.elapsed() < Duration::from_mins(1)
- {
- return Ok(catalog.clone());
- }
- let result = fetch.await;
- match &result {
- Ok(catalog) => *listed = Some((Instant::now(), catalog.clone())),
- Err(_) => drop(self.0.locked().remove(agent)),
- }
- result
+ let answer = slot
+ .get_or_init(|| async {
+ let answer = fetch.await.map_err(|e| format!("{e:#}"));
+ self.0.locked().remove(agent);
+ answer
+ })
+ .await;
+ answer.clone().map_err(anyhow::Error::msg)
}
}
-/// [`models`], shared with the asks of the last minute.
-pub async fn recent_models(hub: &Hub, backend: &str) -> Result<Value> {
- hub.catalogs.get(backend, models(&hub.store, backend)).await
+/// [`models`], shared with the asks for the same agent meanwhile.
+pub async fn shared_models(hub: &Hub, backend: &str) -> Result<Value> {
+ hub.model_lists.get(backend, models(&hub.store, backend)).await
}
/// Discover the agent's advertised models in an isolated, prompt-free session.
@@ -71,6 +65,8 @@ pub async fn models(store: &Store, backend: &str) -> Result<Value> {
Value::Null
};
let mut catalog = model_catalog(&session, &options);
+ catalog["modes"] =
+ crate::agent::modes::Modes::from_session(&session, backend).map_or(json!([]), |m| m.catalog());
if backend != "cursor" {
discover_options(&acp, &session, &mut catalog).await?;
}
@@ -155,8 +151,7 @@ pub(crate) fn model_ids(session: &Value) -> Vec<String> {
catalog["models"].as_array().into_iter().flatten().filter_map(|m| text(&m["id"])).collect()
}
-/// `{models: [{id, name, description, options}], currentModelId, fastMode, modes: [{id, name, description}],
-/// currentModeId}` (modes: see `agent::modes`); `options` is
+/// `{models: [{id, name, description, options}], currentModelId, fastMode}`; `options` is
/// Cursor's `cursor/list_available_models` answer (`Null` for other agents).
fn model_catalog(session: &Value, options: &Value) -> Value {
fn collect(options: &Value, out: &mut Vec<Value>) {
@@ -191,12 +186,9 @@ fn model_catalog(session: &Value, options: &Value) -> Value {
let own = model_options(options, model["id"].as_str().unwrap_or_default());
model["options"] = json!(if options.is_null() { initial_options.clone() } else { own });
}
- let agent_modes = crate::agent::modes::Modes::from_session(session)
- .map_or_else(|| json!({"modes": [], "currentModeId": null}), |m| m.catalog());
json!({"models": models, "currentModelId": current,
"defaultModelOptions": true,
- "fastMode": crate::agent::config::fast_mode_config(session).is_some(),
- "modes": agent_modes["modes"], "currentModeId": agent_modes["currentModeId"]})
+ "fastMode": crate::agent::config::fast_mode_config(session).is_some()})
}
/// One model's options as `[{id, name, values: [{id, name}], default}]`, from Cursor's
@@ -237,8 +229,8 @@ mod tests {
use super::*;
#[tokio::test]
- async fn asks_at_once_start_the_agent_once_and_a_failure_is_asked_again() {
- let recent = Recent::default();
+ async fn asks_at_once_start_the_agent_once_and_later_ones_again() {
+ let lists = InFlight::default();
let started = std::sync::atomic::AtomicUsize::new(0);
let fetch = |ok: bool| {
let started = &started;
@@ -248,11 +240,11 @@ mod tests {
if ok { Ok(json!({"models": []})) } else { Err(anyhow::anyhow!("signed out")) }
}
};
- let (a, b) = tokio::join!(recent.get("claude", fetch(true)), recent.get("claude", fetch(true)));
+ let (a, b) = tokio::join!(lists.get("claude", fetch(true)), lists.get("claude", fetch(true)));
assert_eq!((a.unwrap(), b.unwrap()), (json!({"models": []}), json!({"models": []})));
assert_eq!(started.load(std::sync::atomic::Ordering::SeqCst), 1);
- assert!(recent.get("codex", fetch(false)).await.is_err());
- assert!(recent.get("codex", fetch(true)).await.is_ok());
+ assert_eq!(lists.get("claude", fetch(false)).await.unwrap_err().to_string(), "signed out", "a refresh fetches");
+ assert!(lists.get("claude", fetch(true)).await.is_ok());
assert_eq!(started.load(std::sync::atomic::Ordering::SeqCst), 3);
}
@@ -325,8 +317,7 @@ mod tests {
assert_eq!(result["models"][0]["description"], "Available here");
assert_eq!(
model_catalog(&json!({}), &Value::Null),
- json!({"models": [], "currentModelId": null, "fastMode": false, "defaultModelOptions": true,
- "modes": [], "currentModeId": null})
+ json!({"models": [], "currentModelId": null, "fastMode": false, "defaultModelOptions": true})
);
}
diff --git a/host/src/agent/bot/fast_mode.rs b/host/src/agent/bot/fast_mode.rs
index 667ab040..e0a3ac9b 100644
--- a/host/src/agent/bot/fast_mode.rs
+++ b/host/src/agent/bot/fast_mode.rs
@@ -12,7 +12,7 @@ pub(super) enum Listing {
Session,
/// The answer to our own Fast mode switch.
Switch,
- /// A `config_option_update`.
+ /// A `config_option_update`, or the answer to a mode switch.
Update,
}
diff --git a/host/src/agent/bot/launch.rs b/host/src/agent/bot/launch.rs
index 9d712a9b..f6cc99c6 100644
--- a/host/src/agent/bot/launch.rs
+++ b/host/src/agent/bot/launch.rs
@@ -7,7 +7,7 @@ use crate::agent::registry::{Candidate, Cmd};
use crate::store::BotConfig;
use anyhow::Result;
use serde_json::{Value, json};
-use std::collections::{BTreeMap, HashMap};
+use std::collections::{BTreeMap, HashMap, HashSet};
use std::time::{Duration, Instant};
/// ACP's `systemPrompt`: the bot's instructions added to the agent's own.
@@ -74,6 +74,12 @@ pub(crate) async fn select_model(acp: &Acp, res: &Value, sid: &str, cfg: &BotCon
current = answer;
}
}
+ // The older `modes` field comes only with the session (`agent::modes`).
+ if current.get("modes").is_none()
+ && let Some(modes) = res.get("modes")
+ {
+ current["modes"] = modes.clone();
+ }
Ok(current)
}
@@ -162,7 +168,7 @@ pub(crate) async fn start_agent(command: &str, cwd: &str, env: &[(String, String
opening: false,
fast_options: HashMap::new(),
modes: HashMap::new(),
- mode_set: std::collections::HashSet::new(),
+ mode_set: HashSet::new(),
reports_compaction: false,
usage: HashMap::new(),
renamed: HashMap::new(),
diff --git a/host/src/agent/bot/modes.rs b/host/src/agent/bot/modes.rs
index abba6d51..29de19fa 100644
--- a/host/src/agent/bot/modes.rs
+++ b/host/src/agent/bot/modes.rs
@@ -1,49 +1,66 @@
//! Keeps each live session in the bot's mode (`BotConfig::mode`, see `agent::modes`): set once per session, and
-//! again after the user picks another. The agent may leave it during the session (Plan, once the plan is approved;
-//! Auto, on a model without it), and that stands until the next session. An agent without that mode keeps its own,
-//! and Codync asks about whatever it asks.
+//! again after the user picks another (none: the mode the session opened in). The agent may leave it during the
+//! session (Plan, once the plan is approved; Auto, on a model without it), and that stands until the next session.
+//! Asked for Auto, an agent without it keeps its own mode and Codync asks about whatever it asks; a mode the agent
+//! lacks or refuses fails the turn instead.
use super::Actor;
-use crate::agent::modes::Modes;
-use anyhow::{Context, Result};
+use super::fast_mode::Listing;
+use crate::agent::modes::{Modes, Switch, switch};
+use anyhow::{Context, Result, bail};
use serde_json::{Value, json};
impl Actor {
- /// Records the session's modes from an agent answer or a `config_option_update`.
+ /// Records the session's modes from an agent answer or a `config_option_update`; the one it opened in stays.
pub(super) fn note_modes(&mut self, sid: &str, options: &Value) {
- if let (Some(conn), Some(modes)) = (self.conn.as_mut(), Modes::from_session(options)) {
+ let Some(conn) = self.conn.as_mut() else { return };
+ if let Some(mut modes) = Modes::from_session(options, &self.cfg.backend) {
+ if let Some(known) = conn.modes.get(sid) {
+ modes.opening.clone_from(&known.opening);
+ }
conn.modes.insert(sid.to_owned(), modes);
}
}
- /// Switches a live session to the bot's mode before its turn, once per session. A switch the agent refuses
- /// fails the turn: the bot never works in a mode the user didn't pick.
+ /// The session is in mode `id` now: a `current_mode_update`, or a switch the agent answered without its modes.
+ pub(super) fn note_current_mode(&mut self, sid: &str, id: Option<&str>) {
+ if let Some(modes) = self.conn.as_mut().and_then(|c| c.modes.get_mut(sid)) {
+ modes.current = id.map(str::to_owned);
+ }
+ }
+
+ /// Switches a live session to the bot's mode before its turn, once per session. A mode the agent lacks or
+ /// refuses fails the turn: the bot never works in a mode the user didn't pick.
pub(super) async fn sync_mode(&mut self, sid: &str) -> Result<()> {
- let Some(wanted) = self.cfg.mode.clone() else { return Ok(()) };
let Some(conn) = self.conn.as_mut() else { return Ok(()) };
if conn.mode_set.contains(sid) {
return Ok(());
}
- let target = conn.modes.get(sid).map(|modes| {
- let id = modes.resolve(&wanted).map(str::to_owned);
- let current = id.is_some() && modes.current == id;
- let name = modes.list.iter().find(|m| m["id"].as_str() == id.as_deref()).and_then(|m| m["name"].as_str());
- (id, current, modes.config_id.clone(), name.map(str::to_owned))
- });
- let (Some(id), false, config, name) = target.unwrap_or_default() else {
- // Already in it, or an agent without that mode (or without Auto): it keeps its own and asks as it does.
- conn.mode_set.insert(sid.to_owned());
- return Ok(());
+ let modes = conn.modes.get(sid);
+ let (mode, config) = match switch(modes, self.cfg.mode.as_deref()) {
+ Switch::Stay => {
+ conn.mode_set.insert(sid.to_owned());
+ return Ok(());
+ }
+ Switch::To(mode) => (mode.clone(), modes.and_then(|m| m.config_id.clone())),
+ Switch::Missing => bail!(
+ "{} doesn't have {}, the mode this bot works in, so this turn didn't start. Pick another under \
+ Permissions (Auto carries over to every agent that has one).",
+ crate::agent::fallback::name(&self.cfg.backend),
+ self.cfg.mode.as_deref().unwrap_or_default()
+ ),
};
let (method, params) = match config {
- Some(config) => ("session/set_config_option", json!({"sessionId": sid, "configId": config, "value": id})),
- None => ("session/set_mode", json!({"sessionId": sid, "modeId": id})),
+ Some(config) => {
+ ("session/set_config_option", json!({"sessionId": sid, "configId": config, "value": mode.id}))
+ }
+ None => ("session/set_mode", json!({"sessionId": sid, "modeId": mode.id})),
};
let answer = self.session_request(method, params).await.with_context(|| {
- let mode = name.unwrap_or_else(|| id.clone());
- format!("Couldn't switch the agent to {mode}, the mode this bot works in, so this turn didn't start")
+ format!("Couldn't switch the agent to {}, the mode this bot works in, so this turn didn't start", mode.name)
})?;
- self.note_options(sid, &answer, super::fast_mode::Listing::Switch);
+ self.note_current_mode(sid, Some(&mode.id));
+ self.note_options(sid, &answer, Listing::Update);
if let Some(conn) = self.conn.as_mut() {
conn.mode_set.insert(sid.to_owned());
}
diff --git a/host/src/agent/bot/updates.rs b/host/src/agent/bot/updates.rs
index 2074a372..425c6143 100644
--- a/host/src/agent/bot/updates.rs
+++ b/host/src/agent/bot/updates.rs
@@ -38,6 +38,11 @@ impl Actor {
&& let Some(sid) = params["sessionId"].as_str()
{
self.note_options(sid, &params["update"], Listing::Update);
+ } else if method == "session/update"
+ && params["update"]["sessionUpdate"] == "current_mode_update"
+ && let Some(sid) = params["sessionId"].as_str()
+ {
+ self.note_current_mode(sid, params["update"]["currentModeId"].as_str());
} else if method == "session/update"
&& params["sessionId"].as_str() == self.turn_session.as_deref()
&& self.turn.is_some()
diff --git a/host/src/agent/modes.rs b/host/src/agent/modes.rs
index 3f78c6ad..e70be10f 100644
--- a/host/src/agent/modes.rs
+++ b/host/src/agent/modes.rs
@@ -2,88 +2,139 @@
//! Read-only / Auto review / Full access…), as its `mode` config option or the older `modes` field lists them.
//! A bot names the one it wants (`BotConfig::mode`); what still reaches Codync follows the bot's Approvals.
+use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
-/// The mode where the agent itself decides what is safe and asks only about the rest. Codync's name for it,
-/// and Claude's id: an agent that calls it something else (Codex's `agent`, "Auto review") is listed under it.
+/// The mode where the agent itself decides what is safe and asks only about the rest. Codync's name for it, and
+/// Claude's id: an agent that calls it something else (Codex's `agent`, "Auto review") is listed under it.
pub const AUTO: &str = "auto";
+/// One mode, with the agent's own id and words.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Mode {
+ pub id: String,
+ pub name: String,
+ pub description: Option<String>,
+}
+
/// A session's modes as the agent last listed them.
-#[derive(Clone, Debug, Default, PartialEq, Eq)]
+#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Modes {
/// The config option that switches them; none for an agent that lists only the older `modes` field.
pub config_id: Option<String>,
pub current: Option<String>,
- /// `{id, name, description}`, the agent's ids, in its order.
- pub list: Vec<Value>,
+ /// The mode the session opened in, which a bot without a mode of its own works in.
+ pub opening: Option<String>,
+ /// In the agent's order.
+ pub list: Vec<Mode>,
+ /// The id of its Auto mode, if it has one.
+ auto: Option<String>,
+}
+
+/// What a session does for the mode a bot wants (see [`switch`]).
+#[derive(Debug, PartialEq, Eq)]
+pub enum Switch<'a> {
+ /// It's in that mode already, or the bot wants [`AUTO`] from an agent without one, which keeps its own.
+ Stay,
+ To(&'a Mode),
+ /// The agent doesn't have that mode: the turn doesn't start, rather than run in one the user didn't pick.
+ Missing,
}
impl Modes {
- /// From a `session/new` / `session/load` answer or a `config_option_update`; none when the agent lists no modes.
- pub fn from_session(session: &Value) -> Option<Self> {
- if let Some(option) =
+ /// From a `session/new` / `session/load` answer or a `config_option_update` of agent `backend`; none when the
+ /// agent lists no modes.
+ pub fn from_session(session: &Value, backend: &str) -> Option<Self> {
+ let (config_id, current, list) = if let Some(option) =
session["configOptions"].as_array().into_iter().flatten().find(|o| o["category"] == "mode")
{
let mut list = Vec::new();
flatten(&option["options"], &mut list);
- return (!list.is_empty()).then(|| Self {
- config_id: text(&option["id"]),
- current: text(&option["currentValue"]),
- list,
- });
- }
- let modes = &session["modes"];
- let list: Vec<Value> =
- modes["availableModes"].as_array().into_iter().flatten().filter_map(|m| entry(&m["id"], m)).collect();
- (!list.is_empty()).then(|| Self { config_id: None, current: text(&modes["currentModeId"]), list })
- }
-
- /// The agent's id for the mode a bot wants: its own id, or for [`AUTO`] the agent's Auto mode under any name.
- pub fn resolve(&self, wanted: &str) -> Option<&str> {
- let ids = || self.list.iter().filter_map(|m| m["id"].as_str());
- ids().find(|id| *id == wanted).or_else(|| (wanted == AUTO).then(|| self.auto()).flatten())
+ (text(&option["id"]), text(&option["currentValue"]), list)
+ } else {
+ let modes = &session["modes"];
+ let list = modes["availableModes"].as_array().into_iter().flatten().filter_map(|m| entry(&m["id"], m));
+ (None, text(&modes["currentModeId"]), list.collect())
+ };
+ let auto = auto_mode(backend, &list).map(|m| m.id.clone());
+ (!list.is_empty()).then(|| Self { config_id, opening: current.clone(), current, list, auto })
}
- /// The agent's Auto mode: Claude's `auto`, or one named "Auto review" (Codex's `agent`).
- fn auto(&self) -> Option<&str> {
- let named = |m: &&Value| m["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case("auto review"));
- self.list.iter().find(|m| m["id"] == AUTO).or_else(|| self.list.iter().find(named))?["id"].as_str()
+ fn by_id(&self, id: &str) -> Option<&Mode> {
+ self.list.iter().find(|m| m.id == id)
}
- /// What clients offer: `{modes, currentModeId}`, the Auto mode first and listed as [`AUTO`], so a bot's choice
+ /// What clients offer: `[{id, name, description}]`, the Auto mode first and listed as [`AUTO`], so a bot's choice
/// carries over to another agent that has one.
pub fn catalog(&self) -> Value {
- let auto = self.auto();
- let current = self.current.as_deref();
- let current = if current.is_some() && current == auto { Some(AUTO) } else { current };
- let mut modes: Vec<Value> = self.list.clone();
- modes.sort_by_key(|m| m["id"].as_str() != auto);
+ let auto = self.auto.as_deref();
+ let mut modes: Vec<Mode> = self.list.clone();
+ // Another agent's mode under Codync's id for Auto (Goose's approves every tool call) can't be told apart from
+ // it, so it isn't offered.
+ modes.retain(|m| m.id != AUTO || auto == Some(AUTO));
+ modes.sort_by_key(|m| Some(m.id.as_str()) != auto);
for mode in &mut modes {
- if mode["id"].as_str() == auto {
- mode["id"] = AUTO.into();
+ if Some(mode.id.as_str()) == auto {
+ AUTO.clone_into(&mut mode.id);
}
}
- json!({"modes": modes, "currentModeId": current})
+ json!(modes)
}
}
-fn flatten(options: &Value, out: &mut Vec<Value>) {
+/// What a session in `modes` (none: the agent lists none) does for a bot that wants `wanted`: the agent's own id, or
+/// [`AUTO`] for its Auto mode under any id; `None` for the mode the session opened in.
+pub fn switch<'a>(modes: Option<&'a Modes>, wanted: Option<&str>) -> Switch<'a> {
+ let Some(modes) = modes else {
+ return if wanted.is_some_and(|id| id != AUTO) { Switch::Missing } else { Switch::Stay };
+ };
+ let mode = match wanted {
+ None => modes.opening.as_deref().and_then(|id| modes.by_id(id)),
+ Some(AUTO) => modes.auto.as_deref().and_then(|id| modes.by_id(id)),
+ Some(id) => match modes.by_id(id) {
+ Some(mode) => Some(mode),
+ None => return Switch::Missing,
+ },
+ };
+ match mode {
+ Some(mode) if modes.current.as_deref() != Some(&mode.id) => Switch::To(mode),
+ _ => Switch::Stay,
+ }
+}
+
+/// The agent's Auto mode: Claude's `auto`, or one named "Auto review" (Codex's `agent`). Only these: another agent's
+/// `auto` may approve everything without asking (Goose's).
+fn auto_mode<'a>(backend: &str, list: &'a [Mode]) -> Option<&'a Mode> {
+ list.iter()
+ .find(|m| backend == "claude" && m.id == AUTO)
+ .or_else(|| list.iter().find(|m| m.name.eq_ignore_ascii_case("auto review")))
+}
+
+fn flatten(options: &Value, out: &mut Vec<Mode>) {
for option in options.as_array().into_iter().flatten() {
if option["options"].is_array() {
flatten(&option["options"], out);
} else if let Some(mode) = entry(&option["value"], option)
- && !out.iter().any(|m| m["id"] == mode["id"])
+ && !out.iter().any(|m| m.id == mode.id)
{
out.push(mode);
}
}
}
-fn entry(id: &Value, mode: &Value) -> Option<Value> {
+fn entry(id: &Value, mode: &Value) -> Option<Mode> {
let id = text(id)?;
- Some(
- json!({"name": text(&mode["name"]).unwrap_or_else(|| id.clone()), "description": text(&mode["description"]), "id": id}),
- )
+ let description = text(&mode["description"]).map(sentence);
+ Some(Mode { name: text(&mode["name"]).unwrap_or_else(|| id.clone()), description, id })
+}
+
+/// Clients put Codync's own sentence after the agent's description, so it ends like one ("Claude handles
+/// permission decisions" has no period).
+fn sentence(mut s: String) -> String {
+ if !s.ends_with(['.', '!', '?', '。', '!', '?']) {
+ s.push('.');
+ }
+ s
}
fn text(v: &Value) -> Option<String> {
@@ -111,33 +162,76 @@ mod tests {
{"value": "agent-full-access", "name": "Full access"}]}]})
}
+ fn goose() -> Value {
+ json!({"modes": {"currentModeId": "smart_approve", "availableModes": [
+ {"id": "auto", "name": "auto", "description": "Automatically approve tool calls"},
+ {"id": "approve", "name": "approve"}, {"id": "smart_approve", "name": "smart_approve"},
+ {"id": "chat", "name": "chat"}]}})
+ }
+
+ fn to(modes: &Modes, wanted: Option<&str>) -> Option<String> {
+ match switch(Some(modes), wanted) {
+ Switch::To(mode) => Some(mode.id.clone()),
+ Switch::Stay => None,
+ Switch::Missing => Some("missing".into()),
+ }
+ }
+
#[test]
fn auto_is_the_agents_own_auto_mode_under_any_id() {
- let claude = Modes::from_session(&claude()).unwrap();
+ let claude = Modes::from_session(&claude(), "claude").unwrap();
assert_eq!(claude.config_id.as_deref(), Some("mode"));
- assert_eq!(claude.resolve(AUTO), Some("auto"));
- assert_eq!(claude.resolve("plan"), Some("plan"));
- assert_eq!(claude.resolve("agent"), None, "another agent's id");
- let codex = Modes::from_session(&codex()).unwrap();
- assert_eq!(codex.resolve(AUTO), Some("agent"));
- assert_eq!(codex.resolve("read-only"), Some("read-only"));
+ assert_eq!(to(&claude, Some(AUTO)).as_deref(), Some("auto"));
+ assert_eq!(to(&claude, Some("plan")).as_deref(), Some("plan"));
+ assert_eq!(to(&claude, Some("default")), None, "already in it");
+ let codex = Modes::from_session(&codex(), "codex").unwrap();
+ assert_eq!(to(&codex, Some(AUTO)), None, "its Auto review is where it starts");
+ assert_eq!(to(&codex, Some("read-only")).as_deref(), Some("read-only"));
let manual = json!({"modes": {"currentModeId": "ask", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "code", "name": "Code"}]}});
- let legacy = Modes::from_session(&manual).unwrap();
+ let legacy = Modes::from_session(&manual, "kimi").unwrap();
assert_eq!((legacy.config_id.as_deref(), legacy.current.as_deref()), (None, Some("ask")));
- assert_eq!(legacy.resolve(AUTO), None, "no Auto mode: the bot asks the user");
- assert!(Modes::from_session(&json!({"configOptions": [{"id": "model", "category": "model"}]})).is_none());
+ assert_eq!(to(&legacy, Some(AUTO)), None, "no Auto mode: it keeps its own, and the bot asks the user");
+ assert!(Modes::from_session(&json!({"configOptions": [{"id": "model", "category": "model"}]}), "x").is_none());
+ }
+
+ #[test]
+ fn a_mode_the_agent_lacks_never_runs_in_another() {
+ let codex = Modes::from_session(&codex(), "codex").unwrap();
+ assert_eq!(to(&codex, Some("plan")).as_deref(), Some("missing"), "another agent's id");
+ assert_eq!(switch(None, Some("plan")), Switch::Missing, "an agent without modes");
+ assert_eq!(switch(None, Some(AUTO)), Switch::Stay);
+ assert_eq!(switch(None, None), Switch::Stay);
+ // Goose's `auto` approves every tool call: it isn't the Auto mode, nor offered under its id.
+ let goose = Modes::from_session(&goose(), "goose").unwrap();
+ assert_eq!(to(&goose, Some(AUTO)), None);
+ let ids: Vec<Value> = goose.catalog().as_array().unwrap().iter().map(|m| m["id"].clone()).collect();
+ assert_eq!(ids, [json!("approve"), json!("smart_approve"), json!("chat")]);
+ // Nor is Claude's, run as a custom command: Codync can't tell which agent it is.
+ let custom = Modes::from_session(&claude(), "custom").unwrap();
+ assert_eq!(to(&custom, Some(AUTO)), None);
+ }
+
+ #[test]
+ fn a_bot_without_a_mode_goes_back_to_the_one_its_session_opened_in() {
+ let mut claude = Modes::from_session(&claude(), "claude").unwrap();
+ assert_eq!(to(&claude, None), None);
+ claude.current = Some("auto".into());
+ assert_eq!(to(&claude, None).as_deref(), Some("default"));
}
#[test]
fn clients_get_the_auto_mode_first_and_under_codyncs_name() {
- let codex = Modes::from_session(&codex()).unwrap().catalog();
- let ids: Vec<&str> = codex["modes"].as_array().unwrap().iter().filter_map(|m| m["id"].as_str()).collect();
+ let codex = Modes::from_session(&codex(), "codex").unwrap().catalog();
+ let ids: Vec<&str> = codex.as_array().unwrap().iter().filter_map(|m| m["id"].as_str()).collect();
assert_eq!(ids, ["auto", "read-only", "agent-full-access"]);
- assert_eq!(codex["modes"][0]["name"], "Auto review");
- assert_eq!(codex["currentModeId"], "auto");
- let claude = Modes::from_session(&claude()).unwrap().catalog();
- assert_eq!(claude["modes"][0]["id"], "auto");
- assert_eq!(claude["modes"][1]["name"], "Manual");
- assert_eq!(claude["currentModeId"], "default");
+ assert_eq!(codex[0]["name"], "Auto review");
+ let claude = Modes::from_session(&claude(), "claude").unwrap().catalog();
+ assert_eq!(claude[0]["id"], "auto");
+ assert_eq!(
+ claude[1],
+ json!({"id": "default", "name": "Manual", "description": "Always ask before making changes."})
+ );
+ // A description that already ends a sentence keeps its own mark.
+ assert_eq!(sentence("Plan first!".into()), "Plan first!");
}
}
diff --git a/host/src/api/host.rs b/host/src/api/host.rs
index eec65a17..15cffda3 100644
--- a/host/src/api/host.rs
+++ b/host/src/api/host.rs
@@ -113,7 +113,7 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value
let backend = if step == crate::agent::term::Step::Node { "" } else { str_arg(&b, "backend")? };
json!({"term": hub.terms.start(backend, step, b["method"].as_str(), cols, rows).await?})
}
- "agentModels" => crate::agent::auth::recent_models(hub, str_arg(&b, "backend")?).await?,
+ "agentModels" => crate::agent::auth::shared_models(hub, str_arg(&b, "backend")?).await?,
"agentAuth" | "agentAuthenticate" | "setAgentEnv" => {
let backend = str_arg(&b, "backend")?;
let status = match method {
diff --git a/host/src/chat/calls/context.rs b/host/src/chat/calls/context.rs
index e7bb6366..ec1ccacc 100644
--- a/host/src/chat/calls/context.rs
+++ b/host/src/chat/calls/context.rs
@@ -4,7 +4,7 @@
use super::speech::{call_so_far, spoken};
use super::tools::{runtime, waiting};
use crate::hub::{BotStatus, Hub};
-use crate::store::{BotConfig, Entry, EntryKind, Lane};
+use crate::store::{BotConfig, Entry, EntryKind, Lane, Permission};
use crate::voice::Provider;
use codync_mem::files::{self as mf, MAIN};
use std::path::Path;
@@ -209,10 +209,17 @@ fn bot(hub: &Hub, cfg: &BotConfig) -> String {
lines.push(format!("Runs on: {}{model}", crate::agent::fallback::name(&cfg.backend)));
let project = Path::new(&cfg.cwd).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
lines.push(format!("Folder: {} (project {project})", cfg.cwd));
- lines.push(format!(
- "Permission mode: {}",
- serde_json::to_value(cfg.permission).ok().and_then(|v| v.as_str().map(str::to_owned)).unwrap_or_default()
- ));
+ // What the bot does before it acts: the agent's mode, then what Codync does with what still asks.
+ let mode = match cfg.mode.as_deref() {
+ None => "the agent's default mode".to_owned(),
+ Some(crate::agent::modes::AUTO) => "the agent's Auto mode (it decides what's safe)".to_owned(),
+ Some(mode) => format!("the agent's {mode} mode"),
+ };
+ let rest = match cfg.permission {
+ Permission::Ask => "what it still asks about comes to the user as an approval card",
+ Permission::Auto => "Codync approves what it still asks about automatically",
+ };
+ lines.push(format!("Approvals: {mode}; {rest}"));
if !cfg.connectors.is_empty() {
lines.push(format!("Connectors: {}", cfg.connectors.join(", ")));
}
@@ -423,7 +430,7 @@ pub(super) mod tests {
// Unstaged, so its porcelain line starts with a space.
std::fs::write(repo.join("cart.ts"), "y").unwrap();
let id = uuid::Uuid::new_v4().to_string();
- let cfg = bot(&id, "Mika", &repo.to_string_lossy());
+ let cfg = BotConfig { mode: Some("auto".into()), ..bot(&id, "Mika", &repo.to_string_lossy()) };
hub.store.save_bot(&cfg).unwrap();
hub.store.save_bot(&bot(&uuid::Uuid::new_v4().to_string(), "Owen", "/tmp")).unwrap();
remember(&hub, Some(&id), "- The shop deploys from main\n");
@@ -455,7 +462,9 @@ pub(super) mod tests {
] {
assert!(gemini.contains(heading), "{heading} is there");
}
- for fact in ["Lives in Taipei", "The shop deploys from main", "zh-TW", "github", "Owen"] {
+ let approvals = "Approvals: the agent's Auto mode (it decides what's safe); what it still asks about comes to \
+ the user as an approval card";
+ for fact in ["Lives in Taipei", "The shop deploys from main", "zh-TW", "github", "Owen", approvals] {
assert!(gemini.contains(fact), "{fact} reaches the voice");
}
if repo_ok {
diff --git a/host/src/chat/manage.rs b/host/src/chat/manage.rs
index 9977b041..2a0a4e25 100644
--- a/host/src/chat/manage.rs
+++ b/host/src/chat/manage.rs
@@ -152,6 +152,16 @@ async fn create(hub: &Arc<Hub>, source: &BotConfig, args: &Value) -> Result<Valu
body["skills"] = json!(source.skills);
body["createdBy"] = source.id.clone().into();
let cfg = crate::agent::new_bot::with_defaults(hub, body).await?;
+ // A mode is its agent's: on another agent, the new bot would work in that one's default, which may ask less.
+ if cfg.backend != source.backend
+ && let Some(mode) = source.mode.as_deref().filter(|m| *m != crate::agent::modes::AUTO)
+ {
+ bail!(
+ "you work in your agent's {mode} mode, which {} may not have: create this bot on {}, or ask the user to",
+ crate::agent::fallback::name(&cfg.backend),
+ source.backend
+ );
+ }
crate::hub::validate(&cfg)?;
fields.insert("backend".into(), cfg.backend.clone().into());
let name = cfg.name.clone();
diff --git a/host/src/chat/manage/tests.rs b/host/src/chat/manage/tests.rs
index 1b533214..601aec60 100644
--- a/host/src/chat/manage/tests.rs
+++ b/host/src/chat/manage/tests.rs
@@ -50,6 +50,10 @@ async fn a_manager_creates_and_changes_bots_that_record_who_made_them() {
// It manages the team like the bot that made it, and asks no less.
assert_eq!((cfg.created_by.as_deref(), cfg.permission, cfg.manage_team), (Some("lead"), Permission::Auto, true));
assert_eq!(cfg.mode.as_deref(), Some("plan"), "in the same mode");
+ // Another agent may not have that mode: no bot is made on it.
+ let other = json!({"name": "Reviewer", "agent": "codex"});
+ let refused = call(&hub, "lead", "create_bot", &other).await.unwrap_err().to_string();
+ assert!(refused.contains("plan mode, which Codex may not have"), "{refused}");
// And reaches only the connectors and skills it does, not every installed one.
assert_eq!((cfg.connectors, cfg.skills), (vec!["github".to_owned()], vec![]));
assert_eq!(made["routines"][0]["triggerDescriptions"][0], "Every 30 minutes");
@@ -99,7 +103,7 @@ async fn a_manager_creates_and_changes_bots_that_record_who_made_them() {
assert!(refused("lead", "update_bot", own).await.contains("turned off setting your own fallbacks"));
// Under Ask, a change too long for its card to show in full never reaches the card.
hub.update_bot(&json!({"id": "lead", "permission": "ask"})).unwrap();
- let long = json!({"name": "x", "instructions": "a".repeat(MAX_INSTRUCTIONS_CHARS)});
+ let long = json!({"name": "x", "agent": "claude", "instructions": "a".repeat(MAX_INSTRUCTIONS_CHARS)});
assert!(refused("lead", "create_bot", long).await.contains("too long for its approval card"));
assert_eq!(hub.store.bots().unwrap().len(), 3, "a refused change creates nothing");
assert_eq!(hub.routines.list("dev")["routines"], json!([]));
diff --git a/host/src/hub.rs b/host/src/hub.rs
index 8878a5b8..90c0e6ac 100644
--- a/host/src/hub.rs
+++ b/host/src/hub.rs
@@ -112,7 +112,8 @@ pub struct Hub {
pub screen: Arc<Screen>,
/// Setup terminals (installs, sign-ins).
pub terms: Arc<crate::agent::term::Terms>,
- pub catalogs: crate::agent::auth::Recent,
+ /// Model lists being fetched (`agentModels`).
+ pub model_lists: crate::agent::auth::InFlight,
}
impl Hub {
@@ -151,7 +152,7 @@ impl Hub {
cloud: crate::remote::cloud::Cloud::default(),
screen,
terms: Arc::default(),
- catalogs: crate::agent::auth::Recent::default(),
+ model_lists: crate::agent::auth::InFlight::default(),
})
}
diff --git a/host/src/hub/patch.rs b/host/src/hub/patch.rs
index 07b27362..bbd3cd95 100644
--- a/host/src/hub/patch.rs
+++ b/host/src/hub/patch.rs
@@ -25,6 +25,13 @@ pub(super) fn patched(stored: &BotConfig, patch: &Value) -> Result<BotConfig> {
if (cfg.model != stored.model || cfg.backend != stored.backend) && patch.get("modelOptions").is_none() {
cfg.model_options.clear();
}
+ // So do modes, to one agent: on another, a picked mode becomes its Auto mode, as the apps do it.
+ if cfg.backend != stored.backend
+ && patch.get("mode").is_none()
+ && cfg.mode.as_deref().is_some_and(|m| m != crate::agent::modes::AUTO)
+ {
+ cfg.mode = Some(crate::agent::modes::AUTO.into());
+ }
if cfg.kind != stored.kind {
bail!("a bot can't become a group, or a group a bot");
}
@@ -48,4 +55,15 @@ mod tests {
assert_eq!(section(json!({"id": "a", "section": null})), None, "null: out of its section");
assert_eq!(section(json!({"id": "a", "section": "Work"})).as_deref(), Some("Work"));
}
+
+ #[test]
+ fn another_agent_works_in_its_auto_mode_unless_the_patch_picks_one() {
+ let stored: BotConfig =
+ serde_json::from_value(json!({"id": "a", "name": "a", "backend": "claude", "cwd": "/tmp", "mode": "plan"}))
+ .expect("a bot config");
+ let mode = |patch| patched(&stored, &patch).expect("a valid patch").mode;
+ assert_eq!(mode(json!({"backend": "codex"})).as_deref(), Some("auto"), "plan is Claude's");
+ assert_eq!(mode(json!({"backend": "codex", "mode": "read-only"})).as_deref(), Some("read-only"));
+ assert_eq!(mode(json!({"name": "b"})).as_deref(), Some("plan"));
+ }
}
diff --git a/host/src/store/model.rs b/host/src/store/model.rs
index 1077fcaf..e71722f4 100644
--- a/host/src/store/model.rs
+++ b/host/src/store/model.rs
@@ -80,8 +80,8 @@ pub struct BotConfig {
pub cwd: String,
#[serde(default)]
pub permission: Permission,
- /// The agent mode to work in (see `agent::modes`): its own id, or `auto` for its Auto mode under any id. None
- /// keeps the agent's default, as do agents without that mode.
+ /// The agent mode to work in (see `agent::modes`): its own id, or `auto` for its Auto mode under any id (an agent
+ /// without one keeps its own). None: the mode its sessions open in, the agent's default.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mode: Option<String>,
#[serde(default)]
diff --git a/host/src/tui/app/approvals.rs b/host/src/tui/app/approvals.rs
index 035b3ae4..3ad898cb 100644
--- a/host/src/tui/app/approvals.rs
+++ b/host/src/tui/app/approvals.rs
@@ -1,33 +1,12 @@
//! The bot form's Approvals: the agent's modes, its Auto mode first (`agent::modes`), then Codync approving
-//! everything. An agent without modes offers Ask me instead; one whose list hasn't come yet, Auto and Ask me.
+//! everything. An agent without modes offers Ask me instead; one whose list hasn't come yet, Auto and Ask me. A bot
+//! without a mode (or in Auto on an agent without one) shows as Ask me, and one in a mode the list lacks as that
+//! mode's id: never as more careful than it is.
use super::{App, Form, cycle};
-use crate::agent::modes::AUTO;
-use serde_json::Value;
-
-/// The modes an agent's model list came with (`agentModels`).
-#[derive(Clone, Debug, Default)]
-pub struct AgentModes {
- /// `(id, name)`, Auto first and listed as `auto`.
- pub list: Vec<(String, String)>,
- /// The mode its sessions start in.
- pub current: Option<String>,
-}
+use crate::agent::modes::{AUTO, Mode};
-impl AgentModes {
- pub fn parse(v: &Value) -> Self {
- let list = v["modes"]
- .as_array()
- .into_iter()
- .flatten()
- .filter_map(|m| {
- let id = m["id"].as_str()?;
- Some((id.to_owned(), m["name"].as_str().unwrap_or(id).to_owned()))
- })
- .collect();
- Self { list, current: v["currentModeId"].as_str().map(str::to_owned) }
- }
-}
+const ASKS: &str = "Anything the agent still asks about comes to you as an approval card.";
/// One Approvals choice: the mode to work in and whether Codync approves what still asks.
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -35,52 +14,82 @@ pub struct Approval {
pub mode: Option<String>,
pub auto: bool,
pub label: String,
+ /// The agent's own words for its mode, untranslated.
+ pub note: Option<String>,
+ /// What Codync does, to translate.
+ pub detail: &'static str,
}
impl Approval {
- fn new(mode: Option<&str>, auto: bool, label: &str) -> Self {
- Self { mode: mode.map(str::to_owned), auto, label: label.to_owned() }
+ fn new(mode: Option<&str>, auto: bool, label: &str, detail: &'static str) -> Self {
+ Self { mode: mode.map(str::to_owned), auto, label: label.to_owned(), note: None, detail }
+ }
+
+ fn ask() -> Self {
+ Self::new(None, false, "Ask me", "You'll get an approval card and a notification whenever the agent asks.")
}
}
+/// The modes an agent's model list came with (`agentModels`), Auto first and listed as `auto`.
+pub fn parse_modes(v: &serde_json::Value) -> Vec<Mode> {
+ serde_json::from_value(v["modes"].clone()).unwrap_or_default()
+}
+
impl App {
- /// What the form offers for `backend`.
- pub fn approvals(&self, backend: &str) -> Vec<Approval> {
- let ask = Approval::new(None, false, "Ask me");
- let approve = Approval::new(None, true, "Approve automatically");
- match self.modes.get(backend) {
- None => vec![Approval::new(Some(AUTO), false, "Auto"), ask, approve],
- Some(m) if m.list.is_empty() => vec![ask, approve],
- Some(m) => m
- .list
+ /// What the form offers for its agent, and which one its setting shows as.
+ pub fn approvals(&self, f: &Form) -> (Vec<Approval>, usize) {
+ let mut choices = match self.modes.get(&f.backend) {
+ None => vec![
+ Approval::new(Some(AUTO), false, "Auto", "The agent decides what's safe and asks you about the rest."),
+ Approval::ask(),
+ ],
+ Some(modes) if modes.is_empty() => vec![Approval::ask()],
+ Some(modes) => modes
.iter()
- .map(|(id, name)| Approval::new(Some(id), false, name))
- .chain(std::iter::once(approve))
+ .map(|m| Approval { note: m.description.clone(), ..Approval::new(Some(&m.id), false, &m.name, ASKS) })
.collect(),
- }
+ };
+ choices.push(Approval::new(
+ None,
+ true,
+ "Approve automatically",
+ "Tool requests are approved automatically. Your agent's own settings (like Claude Code's permission rules) still apply.",
+ ));
+ let position = |choices: &[Approval], mode: Option<&str>| {
+ choices.iter().position(|c| !c.auto && c.mode.as_deref() == mode)
+ };
+ // Unlisted: Auto on an agent without it is its default, like no mode (Ask me); any other mode is itself.
+ let unlisted = match f.mode.as_deref() {
+ Some(id) if id != AUTO => Approval::new(Some(id), false, id, ASKS),
+ _ => Approval::ask(),
+ };
+ let found = position(&choices, f.mode.as_deref()).or_else(|| position(&choices, unlisted.mode.as_deref()));
+ let selected = match found {
+ _ if f.auto => choices.len() - 1,
+ Some(i) => i,
+ None => {
+ choices.insert(choices.len() - 1, unlisted);
+ choices.len() - 2
+ }
+ };
+ (choices, selected)
}
- /// The choice the form's setting shows as: an unset mode is the one the agent starts in.
+ /// The choice the form's setting shows as.
pub fn approval(&self, f: &Form) -> Approval {
- let choices = self.approvals(&f.backend);
- let current = self.modes.get(&f.backend).and_then(|m| m.current.as_deref());
- let mode = f.mode.as_deref().or(current);
- let pick = |c: &&Approval| {
- if f.auto {
- c.auto
- } else {
- !c.auto && (c.mode.as_deref() == mode || (c.mode.is_none() && f.mode.is_none()))
- }
- };
- let first = choices.iter().find(|c| !c.auto).cloned();
- choices.iter().find(pick).cloned().or(first).unwrap_or_else(|| Approval::new(None, f.auto, "Ask me"))
+ let (mut choices, selected) = self.approvals(f);
+ choices.swap_remove(selected)
+ }
+
+ /// What a bot's mode is called on its agent, as far as the list that came says.
+ pub fn mode_name<'a>(&'a self, backend: &str, id: &'a str) -> &'a str {
+ let listed = self.modes.get(backend).and_then(|modes| modes.iter().find(|m| m.id == id));
+ listed.map_or(id, |m| m.name.as_str())
}
pub(super) fn cycle_approval(&self, f: &mut Form, d: isize) {
- let choices = self.approvals(&f.backend);
- let now = self.approval(f);
- let i = choices.iter().position(|c| *c == now).unwrap_or(0);
- let next = &choices[cycle(i, d, choices.len())];
+ let (choices, selected) = self.approvals(f);
+ let next = &choices[cycle(selected, d, choices.len())];
(f.mode, f.auto) = (next.mode.clone(), next.auto);
}
}
@@ -89,7 +98,7 @@ impl App {
mod tests {
use super::super::{Overlay, test_app};
use super::*;
- use serde_json::json;
+ use serde_json::{Value, json};
fn form(app: &mut App, bot: &Value) -> Form {
app.bots.insert("b".into(), super::super::Bot::parse(bot).expect("a bot"));
@@ -99,26 +108,40 @@ mod tests {
*f
}
+ fn labels(app: &App, f: &Form) -> Vec<String> {
+ app.approvals(f).0.into_iter().map(|c| c.label).collect()
+ }
+
#[tokio::test]
async fn approvals_list_the_agents_modes_then_approve_automatically() {
let mut app = test_app();
- let codex = json!({"modes": [{"id": "auto", "name": "Auto review"}, {"id": "read-only", "name": "Read-only"}],
- "currentModeId": "auto"});
- app.modes.insert("codex".into(), AgentModes::parse(&codex));
+ let codex = json!({"modes": [{"id": "auto", "name": "Auto review", "description": "Only ask for unsafe actions"},
+ {"id": "read-only", "name": "Read-only"}]});
+ app.modes.insert("codex".into(), parse_modes(&codex));
let mut f = form(&mut app, &json!({"id": "b", "backend": "codex", "permission": "ask", "mode": "auto"}));
- assert_eq!(app.approval(&f).label, "Auto review");
- let labels: Vec<String> = app.approvals("codex").into_iter().map(|c| c.label).collect();
- assert_eq!(labels, ["Auto review", "Read-only", "Approve automatically"]);
+ let auto = app.approval(&f);
+ assert_eq!((auto.label.as_str(), auto.note.as_deref()), ("Auto review", Some("Only ask for unsafe actions")));
+ assert_eq!(labels(&app, &f), ["Auto review", "Read-only", "Approve automatically"]);
+ assert_eq!(app.mode_name("codex", "read-only"), "Read-only");
app.cycle_approval(&mut f, 1);
assert_eq!((f.mode.as_deref(), f.auto), (Some("read-only"), false));
app.cycle_approval(&mut f, 1);
assert_eq!((f.mode.as_deref(), f.auto), (None, true));
assert_eq!(f.changes(), json!({"permission": "auto", "mode": null}));
+ // A bot without a mode is the agent's default, and one in a mode the list lacks shows it.
+ f.auto = false;
+ assert_eq!(app.approval(&f).label, "Ask me");
+ f.mode = Some("bypassPermissions".into());
+ assert_eq!(labels(&app, &f), ["Auto review", "Read-only", "bypassPermissions", "Approve automatically"]);
+ assert_eq!(app.approval(&f).label, "bypassPermissions");
+
// An agent without modes asks about everything; one whose list hasn't come yet offers Auto too.
- app.modes.insert("gemini".into(), AgentModes::default());
+ app.modes.insert("gemini".into(), vec![]);
let f = form(&mut app, &json!({"id": "b", "backend": "gemini", "permission": "ask", "mode": "auto"}));
+ assert_eq!(labels(&app, &f), ["Ask me", "Approve automatically"]);
assert_eq!(app.approval(&f).label, "Ask me");
- assert_eq!(app.approvals("other").len(), 3);
+ let f = form(&mut app, &json!({"id": "b", "backend": "other", "permission": "ask", "mode": "plan"}));
+ assert_eq!(labels(&app, &f), ["Auto", "Ask me", "plan", "Approve automatically"]);
}
}
diff --git a/host/src/tui/app/mod.rs b/host/src/tui/app/mod.rs
index 891076a6..a3398849 100644
--- a/host/src/tui/app/mod.rs
+++ b/host/src/tui/app/mod.rs
@@ -20,7 +20,7 @@ mod slash;
mod steps;
mod ui;
-pub use approvals::AgentModes;
+pub use approvals::parse_modes;
pub use bot::{AgentModel, Bot, ModelOption, OwnMemory};
pub use editor::Editor;
pub use exchange::{ConversationRow, Exchange, Item, Outcome, conversation, group, rows};
@@ -129,7 +129,7 @@ pub struct App {
/// Agents whose model list came with Fast mode.
pub fast_mode: HashSet<String>,
/// The modes each agent's model list came with.
- pub modes: HashMap<String, AgentModes>,
+ pub modes: HashMap<String, Vec<crate::agent::modes::Mode>>,
/// A setup terminal holding the screen.
pub shell: Option<Shell>,
/// Chats marked read since their bot's unread count last changed.
diff --git a/host/src/tui/manage/replies.rs b/host/src/tui/manage/replies.rs
index 83dc1c11..eabf0636 100644
--- a/host/src/tui/manage/replies.rs
+++ b/host/src/tui/manage/replies.rs
@@ -219,7 +219,7 @@ impl App {
if v["fastMode"] == true {
self.fast_mode.insert(backend.clone());
}
- self.modes.insert(backend.clone(), crate::tui::app::AgentModes::parse(&v));
+ self.modes.insert(backend.clone(), crate::tui::app::parse_modes(&v));
self.models.insert(backend, Some(list));
}
Reply::Downloaded => {
diff --git a/host/src/tui/view/chat.rs b/host/src/tui/view/chat.rs
index a6467f90..b256880f 100644
--- a/host/src/tui/view/chat.rs
+++ b/host/src/tui/view/chat.rs
@@ -47,7 +47,11 @@ pub(super) fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {
let names: Vec<String> = b.members.iter().map(|m| app.author_name(Some(m))).collect();
put(buf, x, r.y, room, &truncate(&format!("group · {}", names.join(", ")), usize::from(room)), t.secondary);
} else if !narrow {
- let mode = if b.auto { "approve all" } else { b.mode.as_deref().unwrap_or("ask") };
+ let mode = match b.mode.as_deref() {
+ _ if b.auto => "approve all",
+ None => "ask",
+ Some(id) => app.mode_name(&b.backend, id),
+ };
let fast = match (b.fast_mode, b.fast_refusal().is_some()) {
(true, true) => " · ⚡ refused",
(true, false) => " · ⚡ fast",
diff --git a/host/src/tui/view/forms.rs b/host/src/tui/view/forms.rs
index ab48136a..ffd4f39c 100644
--- a/host/src/tui/view/forms.rs
+++ b/host/src/tui/view/forms.rs
@@ -210,7 +210,8 @@ pub(super) fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {
);
}
Field::Approvals => {
- put(buf, vx, y, vw, &format!("‹ {} ›", tr(&app.approval(f).label)), t.text.patch(base));
+ let label = app.approval(f).label;
+ put(buf, vx, y, vw, &format!("‹ {} ›", tr(&label)), t.text.patch(base));
}
Field::Computer => {
let s = if f.computer { "◉ On ○ Off" } else { "○ On ◉ Off" };
@@ -305,6 +306,10 @@ pub(super) fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {
} else if f.current() == Field::SelfFallbacks {
let line = tr("Let the bot change its fallbacks: it can set this list itself, for example when you ask it to.");
put(buf, inner.x, by - 1, inner.width, &line, t.dim.patch(t.panel));
+ } else if f.current() == Field::Approvals {
+ let choice = app.approval(f);
+ let line = [choice.note.unwrap_or_default(), tr(choice.detail).into_owned()].join(" ");
+ put(buf, inner.x, by - 1, inner.width, line.trim(), t.dim.patch(t.panel));
} else if f.current() == Field::Team {
let line =
"Let this bot create bots and change any bot's setup, its own included. The bots it creates can too.";
diff --git a/host/tests/fallback_e2e.rs b/host/tests/fallback_e2e.rs
index 37c1e90e..45b7fed5 100644
--- a/host/tests/fallback_e2e.rs
+++ b/host/tests/fallback_e2e.rs
@@ -101,6 +101,25 @@ async fn the_next_agent_carries_the_turn_on_and_the_bot_goes_back() {
assert!(text.contains("Codex reached its usage limit (resets in 1 h)"), "{text}");
}
+#[tokio::test]
+async fn a_fallback_without_the_bots_mode_doesnt_take_the_turn() {
+ let host = Host::start().await;
+ let script = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mode_agent.py");
+ let bot = json!({"name": "Moded", "backend": "custom", "command": common::python_agent(&script),
+ "connectors": [], "notify": false, "permission": "ask", "mode": "read-only"});
+ let bot = host.call("createBot", bot).await["bot"]["id"].as_str().unwrap().to_owned();
+ host.call("updateBot", json!({"id": bot, "fallbacks": [{"backend": "codex", "command": agent("standin")}]})).await;
+ let folder = host.home.join("bots").join(&bot).join("workspace");
+ std::fs::write(folder.join("limit"), "").unwrap();
+
+ host.call("send", json!({"botId": bot, "text": "Fix the login tests"})).await;
+ let failed = wait_for(&host, &bot, "failure", |e| e["data"]["style"] == "error").await;
+ let text = failed["data"]["text"].as_str().unwrap();
+ assert!(text.contains("Codex doesn't have read-only, the mode this bot works in"), "{text}");
+ let standin = host.log(&bot, "standin.jsonl");
+ assert!(!standin.iter().any(|r| r["method"] == "session/prompt"), "the fallback never works in its own mode");
+}
+
#[tokio::test]
async fn an_agent_back_in_a_new_session_hears_the_conversation_unless_the_user_started_over() {
let host = Host::start().await;
diff --git a/host/tests/fixtures/fast_mode_agent.py b/host/tests/fixtures/fast_mode_agent.py
index 80320949..7fbc973c 100644
--- a/host/tests/fixtures/fast_mode_agent.py
+++ b/host/tests/fixtures/fast_mode_agent.py
@@ -3,13 +3,14 @@ every new process. It resumes sessions, logs session calls to calls.jsonl in its
folder, and answers each prompt with its speed and the prompt text. With a `refuse`
file in its folder it turns Fast mode back off during a prompt, the way Claude does
for an account without extra usage. With a `plain` file its sessions list no config
-options at all."""
+options at all; with a `moded` file they also list modes like Codex's, starting on Read-only."""
import json
import os
import sys
fast = "off"
+mode = "read-only"
def send(value):
@@ -22,11 +23,15 @@ def log(value):
def options(description="Faster responses on supported models"):
- return {"configOptions": [{
+ listed = [{
"id": "fast", "name": "Fast mode", "description": description, "category": "model_config",
"type": "select", "currentValue": fast,
"options": [{"value": "on", "name": "On"}, {"value": "off", "name": "Off"}],
- }]}
+ }]
+ if os.path.exists("moded"):
+ listed.append({"id": "mode", "name": "Mode", "category": "mode", "type": "select", "currentValue": mode,
+ "options": [{"value": "read-only", "name": "Read-only"}, {"value": "agent", "name": "Auto review"}]})
+ return {"configOptions": listed}
for line in sys.stdin:
@@ -43,7 +48,10 @@ for line in sys.stdin:
send({"id": rid, "result": {"sessionId": "s1", **listed}})
elif method == "session/set_config_option":
log({"method": method, "configId": params["configId"], "value": params["value"]})
- fast = params["value"]
+ if params["configId"] == "mode":
+ mode = params["value"]
+ else:
+ fast = params["value"]
send({"id": rid, "result": options()})
elif method == "session/prompt":
if fast == "on" and os.path.exists("refuse"):
diff --git a/host/tests/fixtures/mode_agent.py b/host/tests/fixtures/mode_agent.py
index e92f627c..e1a0e3c0 100644
--- a/host/tests/fixtures/mode_agent.py
+++ b/host/tests/fixtures/mode_agent.py
@@ -2,7 +2,7 @@
`mode` config option that starts on Read-only. It logs session calls to calls.jsonl in its folder and answers each
prompt with its mode and the prompt text. With a `planless` file in its folder, a prompt moves the session to
Full access by itself (the way Claude leaves Plan once the plan is approved); with a `stuck` file it refuses
-every mode switch."""
+every mode switch; with a `limit` file every prompt fails the way Claude's adapter reports a usage limit."""
import json
import os
@@ -48,6 +48,9 @@ for line in sys.stdin:
log({"method": method, "configId": params["configId"], "value": params["value"]})
mode = params["value"]
send({"id": rid, "result": options()})
+ elif method == "session/prompt" and os.path.exists("limit"):
+ limit = {"code": -32603, "message": "Internal error: You've hit your limit", "data": {"errorKind": "rate_limit"}}
+ send({"id": rid, "error": limit})
elif method == "session/prompt":
text = " ".join(b.get("text", "") for b in params.get("prompt", []))
update = {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": f"mode {mode} · {text}"}}
diff --git a/host/tests/turns_e2e.rs b/host/tests/turns_e2e.rs
index 9d123813..a5f4dbfe 100644
--- a/host/tests/turns_e2e.rs
+++ b/host/tests/turns_e2e.rs
@@ -330,8 +330,31 @@ async fn a_new_bot_works_in_its_agents_auto_mode_until_the_user_picks_another()
host.call("updateBot", json!({"id": bot, "mode": "read-only"})).await;
host.call("send", json!({"botId": bot, "text": "three"})).await;
host.wait_for(&bot, Duration::from_mins(1), speed_reply("mode read-only ", "three")).await;
+ // Left again (planless); without a mode of its own, the bot goes back to the one its session opened in.
+ host.call("updateBot", json!({"id": bot, "permission": "ask", "mode": null})).await;
+ host.call("send", json!({"botId": bot, "text": "four"})).await;
+ host.wait_for(&bot, Duration::from_mins(1), speed_reply("mode read-only ", "four")).await;
let log = log();
assert!(!log.contains("session/load"), "{log}");
+ assert_eq!(log.matches(r#""value": "read-only""#).count(), 2, "{log}");
+}
+
+#[tokio::test]
+async fn a_mode_switch_leaves_fast_mode_to_its_own() {
+ if python_missing() {
+ return;
+ }
+ let host = Host::start().await;
+ let bot = host.bot("Both", "tests/fixtures/fast_mode_agent.py").await;
+ let folder = host.home.join("Both");
+ std::fs::write(folder.join("moded"), "").unwrap();
+ host.call("updateBot", json!({"id": bot, "fastMode": true, "mode": "auto"})).await;
+ host.call("send", json!({"botId": bot, "text": "one"})).await;
+ host.wait_for(&bot, Duration::from_mins(1), speed_reply("fast on", "one")).await;
+ let sync = common::snapshot(&host.base, &host.token).await;
+ assert_eq!(common::bot(&sync, &bot)["fastModeSupport"], "offered", "the mode switch's answer isn't a refusal");
+ let log = std::fs::read_to_string(folder.join("calls.jsonl")).unwrap();
+ assert!(log.contains(r#""configId": "mode", "value": "agent""#) && log.contains(FAST_ON), "{log}");
}
#[tokio::test]
diff --git a/web/content/docs/agent-fallbacks.mdx b/web/content/docs/agent-fallbacks.mdx
index f609627b..337ddba2 100644
--- a/web/content/docs/agent-fallbacks.mdx
+++ b/web/content/docs/agent-fallbacks.mdx
@@ -22,7 +22,7 @@ Each agent can appear once, and the bot's own agent isn't offered. The info butt
In the terminal UI, ←/→ picks a fallback, space adds the next free agent or changes a fallback's model, `a` changes its agent, `[` and `]` move it, and `x` removes it.
-Everything else stays the bot's own whichever agent is answering: its folder, approvals, connectors, skills, computer use and memory, and Fast mode where the fallback's agent has it.
+Everything else stays the bot's own whichever agent is answering: its folder, approvals, connectors, skills, computer use and memory, and Fast mode where the fallback's agent has it. With **Auto** under Permissions, each agent works in its own Auto mode. A mode only the bot's own agent has (Claude Code's Plan, say) doesn't carry over: a fallback without it doesn't take the turn, and the chat says why.
> **Note:** A fallback that runs on an API key instead of a subscription costs money with that provider.
diff --git a/web/content/docs/bots.mdx b/web/content/docs/bots.mdx
index 117884fe..8d9ef6b7 100644
--- a/web/content/docs/bots.mdx
+++ b/web/content/docs/bots.mdx
@@ -65,13 +65,13 @@ The **Permissions** setting decides how much the agent does on its own before it
| --- | --- |
| **Auto** (Claude Code), **Auto review** (Codex) | The agent decides what's safe and does it. It blocks risky actions or asks you about them on an approval card. New bots start here. |
| The agent's other modes, such as **Manual**, **Accept edits** and **Plan** (Claude Code) or **Read-only** and **Full access** (Codex) | The agent works in that mode. Anything it asks about appears as an approval card in the chat, and your iPhone gets a "needs you" notification. The agent waits for your answer. |
-| **Ask me** | For an agent without modes: every request it makes appears as an approval card. |
+| **Ask me** | For an agent without modes, or a bot that keeps the agent's default mode: every request it makes appears as an approval card. |
| **Approve automatically** | Codync allows each request for you, choosing the agent's "allow once" option when it offers one. |
- **An agent without an Auto mode:** a new bot asks you about every request (**Ask me**).
- **A model without Claude Code's Auto mode:** Claude Code works in **Accept edits** instead and says so in the chat.
- **Another agent:** when you change the bot's agent, a mode you picked becomes the new agent's Auto mode.
-- **A mode the agent won't switch to:** the bot doesn't start the turn, and the chat says why.
+- **A mode the agent won't switch to, or doesn't have:** the bot doesn't start the turn, and the chat says why. A fallback agent without the bot's mode doesn't take over either; with **Auto**, each agent carries on in its own Auto mode.
Bots made before Codync 2.34 keep the setting they had. With any setting, your agent's own settings still apply: if Claude Code's permission rules block a tool, it stays blocked. In the terminal UI this field is called **Approvals**, and ←/→ goes through the same choices.