Skip to content

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

feat: let each bot choose when its long chats are summarized

leepokaiaaf26a9e1887
diff --git a/apps/android/WhatsNew.md b/apps/android/WhatsNew.md
index 0233930e..9c207c64 100644
--- a/apps/android/WhatsNew.md
+++ b/apps/android/WhatsNew.md
@@ -7,6 +7,13 @@ released version's section; a version without one gets the PRs' "What's New: And
else a generic "Bug fixes and improvements" line. Delete old sections.
-->
+## 2.42.0
+### zh-Hant
+- bot 設定新增「壓縮對話」:選擇 Codync 什麼時候把長對話壓縮成摘要。可以選提早(預設)、接近上限、不主動壓縮,或以 10K 為一級自己指定數量,最多到模型裝得下的上限。適用於 Claude Code 和 Codex 的 bot。
+
+### en-US
+- New Summarize long chats setting for a bot: choose when Codync summarizes a long chat. Pick Early (default), Near the limit, Only when full, or a size you set in 10K steps, up to what the model holds. For Claude Code and Codex bots.
+
## 2.41.0
### zh-Hant
- 不登入也能用了:在歡迎畫面選擇「不登入繼續」,手機掃電腦的 QR 碼就能配對,透過 Wi-Fi 或 Tailscale 連線。之後登入,配對會留在手機上;到「管理電腦」按「加入帳號」,電腦確認後就能從任何地方連線。
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/BotSettingsForm.kt b/apps/android/app/src/main/kotlin/com/codync/android/BotSettingsForm.kt
index 2b4b7f2c..09590f0c 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/BotSettingsForm.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/BotSettingsForm.kt
@@ -60,6 +60,7 @@ internal enum class FormPart { All, Often, Rarely }
CardSection("Agent") {
fallbackBanner(state, store, bot); computerRow(state, online)
agentRows(state, store, draft, change, bot, modelReload, reloadModels = { modelReload++ }) { addingFallback = true }; placeRows(state, store, draft, change, modelReload) { folders = true }
+ compactionRow(bot, draft, change)
}
CardSection("Activity") {
notifyRow(draft, change); computerUseRow(state, draft, change); manageTeamRow(state, draft, change); reachRows(state, draft, change)
@@ -80,7 +81,9 @@ internal enum class FormPart { All, Often, Rarely }
nameRow(draft, change); createdByRow(state, bot)
}
// The agent and its model are on the Details page; what's left is where it works.
- CardSection("Workspace") { computerRow(state, online); placeRows(state, store, draft, change, modelReload) { folders = true } }
+ CardSection("Workspace") {
+ computerRow(state, online); placeRows(state, store, draft, change, modelReload) { folders = true }; compactionRow(bot, draft, change)
+ }
CardSection("Activity") { notifyRow(draft, change); manageTeamRow(state, draft, change); reachRows(state, draft, change) }
Plugins(state, draft, change) { viewingSkill = it }
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/CompactionPicker.kt b/apps/android/app/src/main/kotlin/com/codync/android/CompactionPicker.kt
new file mode 100644
index 00000000..65af5f5b
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/CompactionPicker.kt
@@ -0,0 +1,49 @@
+package com.codync.android
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Row
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.Bot
+import com.codync.android.core.BotDraft
+import com.codync.android.core.Compaction
+import com.codync.android.core.CompactionTokens
+import com.codync.android.design.*
+
+/** "Summarize long chats": only where Codync summarizes the bot's chat (the host sends a choice). */
+internal fun CardRows.compactionRow(bot: Bot?, draft: BotDraft, change: (BotDraft) -> Unit) {
+ val choice = draft.compaction ?: return
+ row {
+ ValueRow("Summarize long chats", detail = "When Codync summarizes this chat so it can go on. If the chat fills up first, the agent summarizes it itself.") {
+ CompactionPicker(choice, bot?.compactionTokens) { change(draft.copy(compaction = it)) }
+ }
+ }
+}
+
+/** The pill and its menu: the three choices, then the sizes the agent's window allows (a scrolling submenu). */
+@Composable private fun CompactionPicker(choice: Compaction, tokens: CompactionTokens?, select: (Compaction) -> Unit) {
+ val current = if (choice is Compaction.Tokens) choice.label else tr(choice.label)
+ DropdownMenu({ compactionRows(choice, tokens, select) }, label = "${tr("Summarize long chats")}: $current") {
+ Row(Modifier.outline().pill(Color.Transparent), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ Text(current, Modifier.weight(1f, fill = false), style = Type.body, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)
+ Symbol("chevron.down", size = 13.dp, tint = Palette.secondary)
+ }
+ }
+}
+
+private fun compactionRows(choice: Compaction, tokens: CompactionTokens?, select: (Compaction) -> Unit): List<MenuItem> {
+ val presets = listOf(Compaction.Early, Compaction.NearLimit, Compaction.Off).map { preset ->
+ MenuItem(preset.label, selected = choice == preset) { select(preset) }
+ }
+ val picked = (choice as? Compaction.Tokens)?.tokens
+ val sizes = if (tokens == null) MenuItem("Sizes show after the bot's next reply", divider = true, enabled = false)
+ else MenuItem("Set a size", divider = true, children = tokens.sizes.map { size ->
+ MenuItem(Compaction.sizeLabel(size), selected = size == picked, verbatim = true) { select(Compaction.Tokens(size)) }
+ })
+ return presets + sizes
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/BotDraft.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/BotDraft.kt
index c0c82664..6a4a2600 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/BotDraft.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/BotDraft.kt
@@ -39,6 +39,8 @@ data class BotDraft(
val reachableByAssistants: Boolean? = null,
/** The agent mode it works in ([AgentMode]); null, sent as null, keeps the agent's default. */
val mode: String? = AgentMode.AUTO,
+ /** When Codync summarizes its chat ([Bot.compaction]); null where it doesn't, so it isn't sent. */
+ val compaction: Compaction? = null,
) {
/** A saved bot keeps a name; only a new one goes without (the host names it after its first conversations). */
val isValid: Boolean get() = name.isNotBlank()
@@ -70,7 +72,7 @@ data class BotDraft(
companion object {
/** A new bot starts with a random face, like iOS. */
val AVATAR_COLORS = listOf("black", "brown", "red", "orange", "yellow", "green", "cyan", "blue", "violet", "magenta", "gray")
- private val UNSET = setOf("fastMode", "notify", "fallbacks", "selfFallbacks", "offeredToNetwork", "reachableByAssistants")
+ private val UNSET = setOf("fastMode", "notify", "fallbacks", "selfFallbacks", "offeredToNetwork", "reachableByAssistants", "compaction")
/** Who reaches a bot belongs to its computer, not its setup. */
private val TEMPLATE_SKIPS =
setOf("id", "pinned", "hidden", "fallbacks", "selfFallbacks", "offeredToNetwork", "reachableByAssistants")
@@ -80,6 +82,6 @@ data class BotDraft(
fun from(bot: Bot): BotDraft = BotDraft(bot.id, bot.name, bot.description, bot.avatarColor, bot.avatarShape,
bot.backend, bot.command, if (bot.managedWorkspace) "" else bot.cwd, bot.permission, bot.model,
bot.modelOptions, bot.fastMode, bot.pinned, bot.hidden, bot.notify, bot.connectors, bot.skills, bot.computer, bot.manageTeam ?: false, bot.fallbacks, bot.selfFallbacks,
- bot.offeredToNetwork, bot.reachableByAssistants, bot.mode)
+ bot.offeredToNetwork, bot.reachableByAssistants, bot.mode, bot.compaction)
}
}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Compaction.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Compaction.kt
new file mode 100644
index 00000000..49ed7d8c
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Compaction.kt
@@ -0,0 +1,64 @@
+package com.codync.android.core
+
+import kotlinx.serialization.KSerializer
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.descriptors.buildClassSerialDescriptor
+import kotlinx.serialization.encoding.Decoder
+import kotlinx.serialization.encoding.Encoder
+import kotlinx.serialization.json.JsonDecoder
+import kotlinx.serialization.json.JsonEncoder
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.longOrNull
+
+/**
+ * When Codync summarizes a bot's chat so it can go on (the host's `compaction`): early by default, near the limit of
+ * the agent's window, never (the agent still does when the chat fills up), or at a size the user picked.
+ */
+@Serializable(with = CompactionSerializer::class)
+sealed interface Compaction {
+ data object Early : Compaction
+ data object NearLimit : Compaction
+ data object Off : Compaction
+ data class Tokens(val tokens: Long) : Compaction
+
+ /** As its menu row and the pill show it: a phrase to translate, or a size such as "120K" shown as it is. */
+ val label: String get() = when (this) {
+ Early -> "Early (default)"
+ NearLimit -> "Near the limit"
+ Off -> "Only when full"
+ is Tokens -> sizeLabel(tokens)
+ }
+
+ companion object {
+ fun sizeLabel(tokens: Long): String = "${tokens / 1000}K"
+ }
+}
+
+/** The sizes the bot's window allows (`compactionTokens`): [min] to [max] by [step]. */
+@Serializable
+data class CompactionTokens(val min: Long, val max: Long, val step: Long) {
+ val sizes: List<Long> get() = if (step > 0 && min <= max) (min..max step step).toList() else emptyList()
+}
+
+/** `"early"`, `"nearLimit"`, `"off"` or a number of tokens; a name from a newer host reads as early, rather than losing the bot. */
+internal object CompactionSerializer : KSerializer<Compaction> {
+ override val descriptor = buildClassSerialDescriptor("Compaction")
+ override fun serialize(encoder: Encoder, value: Compaction) {
+ val wire = when (value) {
+ Compaction.Early -> JsonPrimitive("early")
+ Compaction.NearLimit -> JsonPrimitive("nearLimit")
+ Compaction.Off -> JsonPrimitive("off")
+ is Compaction.Tokens -> JsonPrimitive(value.tokens)
+ }
+ (encoder as JsonEncoder).encodeJsonElement(wire)
+ }
+ override fun deserialize(decoder: Decoder): Compaction {
+ val wire = (decoder as JsonDecoder).decodeJsonElement() as? JsonPrimitive ?: return Compaction.Early
+ if (!wire.isString) wire.longOrNull?.let { return Compaction.Tokens(it) }
+ return when (wire.content) {
+ "nearLimit" -> Compaction.NearLimit
+ "off" -> Compaction.Off
+ else -> Compaction.Early
+ }
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt
index b58e3c79..6f41ed60 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/HostClient.kt
@@ -49,6 +49,10 @@ data class Bot(
val harnessMemory: Boolean? = null,
/** The harness keeps one memory for all its sessions that Codync can't turn off (Hermes Agent, Gemini CLI): every bot on it shares it. */
val harnessMemoryShared: Boolean? = null,
+ /** When Codync summarizes its chat; null where it doesn't (an agent it can't ask to, a group, an older host). */
+ val compaction: Compaction? = null,
+ /** The sizes its agent's window allows; null until the agent has told its window. */
+ val compactionTokens: CompactionTokens? = null,
/** Moves whenever memory changes, so an open memory screen fetches it again. */
val memoryRev: Long? = null,
val autoName: Boolean = false,
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/CompactionTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/CompactionTest.kt
new file mode 100644
index 00000000..afc815a6
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/CompactionTest.kt
@@ -0,0 +1,38 @@
+package com.codync.android.core
+
+import kotlinx.serialization.json.*
+import org.junit.Assert.*
+import org.junit.Test
+
+class CompactionTest {
+ private fun bot(fields: String): Bot = WireJson.decodeFromString("""{"id": "b", "name": "B" $fields}""")
+
+ @Test fun `a bot reads each compaction choice, and a newer host's name as early`() {
+ assertEquals(Compaction.Early, bot(""", "compaction": "early"""").compaction)
+ assertEquals(Compaction.NearLimit, bot(""", "compaction": "nearLimit"""").compaction)
+ assertEquals(Compaction.Off, bot(""", "compaction": "off"""").compaction)
+ assertEquals(Compaction.Tokens(120_000), bot(""", "compaction": 120000""").compaction)
+ assertEquals(Compaction.Early, bot(""", "compaction": "later"""").compaction)
+ assertNull("no setting where Codync doesn't summarize", bot(""", "compaction": null""").compaction)
+ assertNull(bot("").compaction)
+ }
+
+ @Test fun `the sizes run from min to max by step`() {
+ val read = bot(""", "compaction": "early", "compactionTokens": {"min": 50000, "max": 960000, "step": 10000}""")
+ val sizes = read.compactionTokens!!.sizes
+ assertEquals(92, sizes.size)
+ assertEquals(listOf(50_000L, 60_000L), sizes.take(2))
+ assertEquals(960_000L, sizes.last())
+ assertEquals("120K", Compaction.Tokens(120_000).label)
+ assertNull(bot(""", "compactionTokens": null""").compactionTokens)
+ }
+
+ @Test fun `a draft sends the choice as the host reads it, and nothing where there is none`() {
+ assertEquals(JsonPrimitive("nearLimit"), BotDraft.from(bot(""", "compaction": "nearLimit"""")).body()["compaction"])
+ assertEquals(JsonPrimitive(300_000), BotDraft.from(bot("")).copy(compaction = Compaction.Tokens(300_000)).body()["compaction"])
+ assertFalse("compaction" in BotDraft.from(bot("")).body())
+ // A stored bot reads back as written (the mirror database keeps bots as JSON).
+ val stored = bot(""", "compaction": 80000""")
+ assertEquals(stored, WireJson.decodeFromString<Bot>(WireJson.encodeToString(Bot.serializer(), stored)))
+ }
+}
diff --git a/apps/desktop/e2e/compaction.spec.ts b/apps/desktop/e2e/compaction.spec.ts
new file mode 100644
index 00000000..4f6e45a9
--- /dev/null
+++ b/apps/desktop/e2e/compaction.spec.ts
@@ -0,0 +1,96 @@
+import { test, expect, type Page } from '@playwright/test'
+import { join, resolve } from 'node:path'
+import { api, attach, typeMessage } from './sandbox.ts'
+
+// A scripted agent that answers `initialize` the way Claude's adapter does and reports the context use a message names
+// (host/tests/fixtures/instructions_agent.py). Playwright loads specs as CommonJS here, so `__dirname` is defined.
+const agent = join(resolve(__dirname, '../../..'), 'host/tests/fixtures/instructions_agent.py')
+
+type Bot = { id: string; compaction: unknown }
+
+/** The bot's Summarize long chats row, on the Settings tab of the details beside its chat. */
+async function summarizeRow(page: Page, name: string) {
+ await page.locator('.roster-row', { hasText: name }).click()
+ const details = page.locator('.details-panel')
+ if (!(await details.isVisible())) await page.getByRole('button', { name: `${name}, view details` }).click()
+ await details.getByRole('tab', { name: 'Settings' }).click()
+ return details.locator('.value-row', { hasText: 'Summarize long chats' })
+}
+
+const menuRow = (page: Page, title: string | RegExp) => page.locator('.menu-row', { hasText: title })
+
+/** The setting as the host keeps it: an update that changes nothing answers with the bot. */
+const stored = async (page: Page, id: string) => (await api<{ bot: Bot }>(page, 'updateBot', { id })).bot.compaction
+
+test('before its first reply a Claude Code bot offers only the three choices', async () => {
+ const { browser, page } = await attach()
+ const name = `Summarize e2e ${Date.now()}`
+ let botId: string | undefined
+ try {
+ botId = (await api<{ bot: Bot }>(page, 'createBot', { name, backend: 'claude', connectors: [], skills: [], notify: false })).bot.id
+ const pill = (await summarizeRow(page, name)).locator('.choice-picker')
+ await expect(pill).toHaveText('Early (default)')
+ await pill.click()
+ for (const title of ['Early (default)', 'Near the limit', 'Only when full']) await expect(menuRow(page, title)).toBeEnabled()
+ await expect(menuRow(page, "Sizes show after the bot's next reply")).toBeDisabled()
+ await expect(menuRow(page, 'Set a size')).toHaveCount(0)
+ await menuRow(page, 'Only when full').click()
+ await expect(pill).toHaveText('Only when full')
+ await expect.poll(() => stored(page, botId!)).toBe('off')
+ } finally {
+ if (botId) await api(page, 'deleteBot', { botId }).catch(() => {})
+ await browser.close()
+ }
+})
+
+test('once the agent tells its window, Set a size lists what it holds and the size picked is kept', async () => {
+ const { browser, page } = await attach()
+ const name = `Summarize sizes e2e ${Date.now()}`
+ let botId: string | undefined
+ try {
+ const command = `python3 -X utf8 -u '${agent}' claude`
+ botId = (await api<{ bot: Bot }>(page, 'createBot', { name, backend: 'custom', command, connectors: [], skills: [], notify: false })).bot.id
+ const row = await summarizeRow(page, name)
+ await expect(row, 'a custom command shows it once it runs Claude').toHaveCount(0)
+
+ await typeMessage(page, 'USAGE 10000 SIZE 1000000')
+ const pill = row.locator('.choice-picker')
+ await expect(pill).toHaveText('Early (default)', { timeout: 20_000 })
+ await pill.click()
+ await menuRow(page, 'Set a size').click()
+ await expect(menuRow(page, /^50K$/)).toBeVisible()
+ await expect(menuRow(page, /^960K$/)).toBeAttached()
+ await menuRow(page, /^120K$/).click()
+ await expect(pill).toHaveText('120K')
+ await expect.poll(() => stored(page, botId!)).toBe(120_000)
+
+ // The submenu opens at the size picked, and its back row returns to the choices.
+ await pill.click()
+ await menuRow(page, 'Set a size').click()
+ await expect(menuRow(page, /^120K$/)).toHaveAttribute('aria-checked', 'true')
+ await menuRow(page, 'Set a size').click()
+ await menuRow(page, 'Near the limit').click()
+ await expect(pill).toHaveText('Near the limit')
+ await expect.poll(() => stored(page, botId!)).toBe('nearLimit')
+ } finally {
+ if (botId) await api(page, 'deleteBot', { botId }).catch(() => {})
+ await browser.close()
+ }
+})
+
+test('a bot on an agent Codync does not summarize for has no Summarize long chats row', async () => {
+ const { browser, page } = await attach()
+ const name = `Summarize gemini e2e ${Date.now()}`
+ let botId: string | undefined
+ try {
+ const bot = (await api<{ bot: Bot }>(page, 'createBot', { name, backend: 'gemini', connectors: [], skills: [], notify: false })).bot
+ botId = bot.id
+ expect(bot.compaction).toBeNull()
+ const row = await summarizeRow(page, name)
+ await expect(page.locator('.details-panel .value-row', { hasText: 'Workspace' })).toBeVisible()
+ await expect(row).toHaveCount(0)
+ } finally {
+ if (botId) await api(page, 'deleteBot', { botId }).catch(() => {})
+ await browser.close()
+ }
+})
diff --git a/apps/desktop/src/renderer/components/Controls.tsx b/apps/desktop/src/renderer/components/Controls.tsx
index 8bb62e00..9c019fd4 100644
--- a/apps/desktop/src/renderer/components/Controls.tsx
+++ b/apps/desktop/src/renderer/components/Controls.tsx
@@ -1,6 +1,7 @@
import { Children, Fragment, useEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type PointerEvent, type ReactNode } from 'react'
import { Icon } from './Icon'
-import { AnchoredMenu, IconButtonBase, usePresence, type MenuItem } from './Overlay'
+import { IconButtonBase, usePresence } from './Overlay'
+import { AnchoredMenu, type MenuItem } from './Menu'
import { HStack, Spacer, VStack } from './Stack'
import { useTr } from '../lib/use-language'
import { Text } from './Text'
diff --git a/apps/desktop/src/renderer/components/Menu.tsx b/apps/desktop/src/renderer/components/Menu.tsx
new file mode 100644
index 00000000..bcf68da8
--- /dev/null
+++ b/apps/desktop/src/renderer/components/Menu.tsx
@@ -0,0 +1,218 @@
+import { useEffect, useLayoutEffect, useRef, useState, type ReactNode, type RefObject } from 'react'
+import { createPortal } from 'react-dom'
+import { useTr } from '../lib/use-language'
+import { Icon } from './Icon'
+import { useEscape, usePresence } from './Overlay'
+import { HStack } from './Stack'
+import { Text } from './Text'
+
+/** What every row in a Codync menu has. */
+interface MenuRow {
+ title: string
+ /** Secondary context below the main label. */
+ detail?: string
+ icon?: string
+ /** A picture in the icon's place (an agent's logo). */
+ leading?: ReactNode
+ selected?: boolean
+ destructive?: boolean
+ divider?: boolean
+ /** The title is a name the user gave (a section): shown as typed, never translated. */
+ verbatim?: boolean
+ /** Picking it leaves the menu open, for choices made several at a time (iOS `.menuActionDismissBehavior(.disabled)`). */
+ keepsOpen?: boolean
+ /** A line that only says something: dimmed, and can't be picked. */
+ disabled?: boolean
+}
+
+/**
+ * One row in a Codync menu: an action (a choice when `selected` is set), or the rows of a submenu, one level deep. An
+ * anchored menu opens them in its place behind a back row ("Set a size ›"), the roster's right-click menu beside it.
+ */
+export type MenuItem = MenuRow & ({ action: () => void; submenu?: undefined } | { submenu: MenuItem[]; action?: undefined })
+
+/** A row of emoji above a message's menu (Slack's quick reactions). */
+export interface ReactionPick {
+ emoji: string[]
+ chosen: string[]
+ toggle: (emoji: string) => void
+}
+
+export function ReactionStrip({ pick, dismiss, size = 26 }: { pick: ReactionPick; dismiss?: () => void; size?: number }) {
+ const tr = useTr()
+ return (
+ <HStack align="stretch">
+ {pick.emoji.map((emoji) => {
+ const chosen = pick.chosen.includes(emoji)
+ return (
+ <button
+ key={emoji}
+ className={`reaction-button ${chosen ? 'chosen' : ''}`}
+ style={{ width: size, height: size, borderRadius: size * 0.28 }}
+ title={chosen ? tr('Remove {emoji}').replaceAll('{emoji}', () => emoji) : tr('React {emoji}').replaceAll('{emoji}', () => emoji)}
+ aria-label={chosen ? tr('Remove reaction {emoji}').replaceAll('{emoji}', () => emoji) : tr('React {emoji}').replaceAll('{emoji}', () => emoji)}
+ onClick={() => {
+ dismiss?.()
+ pick.toggle(emoji)
+ }}
+ >
+ <Text size={14}>{emoji}</Text>
+ </button>
+ )
+ })}
+ </HStack>
+ )
+}
+
+/** The floating panel of menu rows. */
+export function MenuPanel({ items, reactions, dismiss, maxHeight }: { items: MenuItem[]; reactions?: ReactionPick; dismiss: () => void; maxHeight?: number }) {
+ const tr = useTr()
+ const [highlight, setHighlight] = useState(-1)
+ const [opened, setOpened] = useState<MenuItem | null>(null)
+ const panel = useRef<HTMLDivElement>(null)
+ const show = (sub: MenuItem | null) => {
+ setOpened(sub)
+ setHighlight(-1)
+ }
+ const rows: MenuItem[] = opened
+ ? [{ title: opened.title, verbatim: opened.verbatim, icon: 'chevron.left', keepsOpen: true, action: () => show(null) }, ...(opened.submenu ?? [])]
+ : items
+ const pick = (item: MenuItem) => {
+ if (item.disabled) return
+ if (item.submenu) return show(item)
+ if (!item.keepsOpen) dismiss()
+ item.action()
+ }
+ // A long submenu opens at its checked row.
+ useLayoutEffect(() => {
+ if (opened) panel.current?.querySelector('[aria-checked="true"]')?.scrollIntoView({ block: 'center' })
+ }, [opened])
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
+ e.preventDefault()
+ setHighlight((h) => (h + (e.key === 'ArrowDown' ? 1 : -1) + rows.length) % rows.length)
+ } else if (e.key === 'Enter' && highlight >= 0 && rows[highlight]) {
+ e.preventDefault()
+ pick(rows[highlight])
+ } else if (e.key === 'ArrowLeft' && opened) {
+ e.preventDefault()
+ show(null)
+ }
+ }
+ window.addEventListener('keydown', onKey)
+ return () => window.removeEventListener('keydown', onKey)
+ }, [rows, highlight, dismiss, opened])
+ return (
+ <div ref={panel} className="menu-panel" role="menu" style={{ maxHeight }}>
+ {reactions && !opened ? (
+ <div className={items.length ? 'menu-reactions' : undefined}>
+ <ReactionStrip pick={reactions} dismiss={dismiss} />
+ </div>
+ ) : null}
+ {rows.map((item, i) => (
+ <div key={`${opened?.title ?? ''}-${item.title}-${i}`} role="none">
+ {item.divider ? <div className="menu-divider" role="separator" /> : null}
+ <button
+ className={`menu-row ${item.destructive ? 'destructive' : ''} ${highlight === i ? 'highlight' : ''}`}
+ role={item.selected === undefined ? 'menuitem' : 'menuitemradio'}
+ aria-checked={item.selected}
+ aria-haspopup={item.submenu ? 'menu' : undefined}
+ disabled={item.disabled}
+ title={item.verbatim ? item.title : tr(item.title)}
+ onMouseEnter={() => setHighlight(i)}
+ onClick={() => pick(item)}
+ >
+ {item.leading || item.icon ? (
+ <span className="menu-icon">
+ {item.leading ?? (item.icon ? <Icon name={item.icon} size={12} /> : null)}
+ </span>
+ ) : null}
+ <span className={`menu-title${item.detail ? ' with-detail' : ''}`}>
+ <span>{item.verbatim ? item.title : tr(item.title)}</span>
+ {item.detail && <span className="menu-detail">{tr(item.detail)}</span>}
+ </span>
+ {item.submenu ? (
+ <Icon name="chevron.right" size={10} weight="semibold" color="var(--secondary)" />
+ ) : item.selected !== undefined ? (
+ <span className={`check-slot${item.selected ? ' on' : ''}`}>
+ <Icon name="checkmark" size={10} weight="semibold" />
+ </span>
+ ) : null}
+ </button>
+ </div>
+ ))}
+ </div>
+ )
+}
+
+/**
+ * Where a panel opens beside `rect`: below it or above (whichever has more room), aligned to the
+ * anchor's leading or trailing edge and kept on screen. `room` is the height available.
+ */
+export function anchorPlacement(rect: DOMRect) {
+ const W = window.innerWidth
+ const H = window.innerHeight
+ const roomBelow = Math.max(0, H - rect.bottom - 14)
+ const roomAbove = Math.max(0, rect.top - 14)
+ const below = roomBelow >= roomAbove
+ const leading = rect.left + rect.width / 2 < W * 0.6
+ const width = Math.min(320, W - 16)
+ const inset = Math.max(8, W - width - 8)
+ const style: React.CSSProperties = {
+ [below ? 'top' : 'bottom']: below ? rect.bottom + 6 : H - rect.top + 6,
+ ...(leading ? { left: Math.min(Math.max(8, rect.left), inset) } : { right: Math.min(Math.max(8, W - rect.right), inset) }),
+ transformOrigin: `${below ? 'top' : 'bottom'} ${leading ? 'left' : 'right'}`,
+ }
+ return { style, width, room: below ? roomBelow : roomAbove }
+}
+
+/**
+ * Presents `MenuPanel` next to `anchor` (or at `point`, for right-clicks), flipping to stay on
+ * screen; a click anywhere else closes it (`.codyncMenu` / `.contextActions`).
+ */
+export function AnchoredMenu({ open, onClose, anchor, point, items, reactions }: {
+ open: boolean
+ onClose: () => void
+ anchor?: RefObject<HTMLElement | null>
+ point?: { x: number; y: number } | null
+ items: () => MenuItem[]
+ reactions?: ReactionPick
+}) {
+ const { mounted, shown } = usePresence(open, 120)
+ const [rect, setRect] = useState<DOMRect | null>(null)
+ const frozen = useRef<MenuItem[]>([])
+ const layer = useRef<HTMLDivElement>(null)
+ if (open) frozen.current = items()
+ useLayoutEffect(() => {
+ if (!open) return
+ if (point) setRect(new DOMRect(point.x, point.y, 0, 0))
+ else if (anchor?.current) setRect(anchor.current.getBoundingClientRect())
+ }, [open, point, anchor])
+ useEscape(open, onClose, layer)
+ if (!mounted || !rect) return null
+ const { style, width, room } = anchorPlacement(rect)
+ return createPortal(
+ <div ref={layer} className={`anchored ${shown ? 'shown' : ''}`} onMouseDown={(e) => e.target === e.currentTarget && onClose()} onContextMenu={(e) => { e.preventDefault(); onClose() }}>
+ <div className="anchored-panel" style={{ ...style, maxWidth: width }}>
+ <MenuPanel items={frozen.current} reactions={reactions} dismiss={onClose} maxHeight={Math.min(420, room)} />
+ </div>
+ </div>,
+ document.body,
+ )
+}
+
+/** Right-click opens a Codync menu at the pointer (kit's `.contextActions`). */
+export function useContextMenu() {
+ const [point, setPoint] = useState<{ x: number; y: number } | null>(null)
+ return {
+ point,
+ open: point !== null,
+ onContextMenu: (e: React.MouseEvent) => {
+ e.preventDefault()
+ e.stopPropagation()
+ setPoint({ x: e.clientX, y: e.clientY })
+ },
+ close: () => setPoint(null),
+ }
+}
diff --git a/apps/desktop/src/renderer/components/Overlay.tsx b/apps/desktop/src/renderer/components/Overlay.tsx
index f8de1992..a0ef60d9 100644
--- a/apps/desktop/src/renderer/components/Overlay.tsx
+++ b/apps/desktop/src/renderer/components/Overlay.tsx
@@ -5,7 +5,7 @@ import { afterExit } from '../lib/exit-delay'
import { stackModals } from '../lib/modal-stack'
import { useTr } from '../lib/use-language'
import { Icon } from './Icon'
-import { HStack, VStack } from './Stack'
+import { VStack } from './Stack'
import { Text } from './Text'
import './overlay.css'
@@ -231,188 +231,6 @@ export function Dialog({ open, title, message, actions, cancel = 'Cancel', onCan
)
}
-/** One row in a Codync menu: an action, or a choice when `selected` is set. */
-export interface MenuItem {
- title: string
- /** Secondary context below the main label. */
- detail?: string
- icon?: string
- /** A picture in the icon's place (an agent's logo). */
- leading?: ReactNode
- selected?: boolean
- destructive?: boolean
- divider?: boolean
- /** The title is a name the user gave (a section): shown as typed, never translated. */
- verbatim?: boolean
- /** Picking it leaves the menu open, for choices made several at a time (iOS `.menuActionDismissBehavior(.disabled)`). */
- keepsOpen?: boolean
- action: () => void
-}
-
-/** A row of emoji above a message's menu (Slack's quick reactions). */
-export interface ReactionPick {
- emoji: string[]
- chosen: string[]
- toggle: (emoji: string) => void
-}
-
-export function ReactionStrip({ pick, dismiss, size = 26 }: { pick: ReactionPick; dismiss?: () => void; size?: number }) {
- const tr = useTr()
- return (
- <HStack align="stretch">
- {pick.emoji.map((emoji) => {
- const chosen = pick.chosen.includes(emoji)
- return (
- <button
- key={emoji}
- className={`reaction-button ${chosen ? 'chosen' : ''}`}
- style={{ width: size, height: size, borderRadius: size * 0.28 }}
- title={chosen ? tr('Remove {emoji}').replaceAll('{emoji}', () => emoji) : tr('React {emoji}').replaceAll('{emoji}', () => emoji)}
- aria-label={chosen ? tr('Remove reaction {emoji}').replaceAll('{emoji}', () => emoji) : tr('React {emoji}').replaceAll('{emoji}', () => emoji)}
- onClick={() => {
- dismiss?.()
- pick.toggle(emoji)
- }}
- >
- <Text size={14}>{emoji}</Text>
- </button>
- )
- })}
- </HStack>
- )
-}
-
-/** The floating panel of menu rows. */
-export function MenuPanel({ items, reactions, dismiss, maxHeight }: { items: MenuItem[]; reactions?: ReactionPick; dismiss: () => void; maxHeight?: number }) {
- const tr = useTr()
- const [highlight, setHighlight] = useState(-1)
- useEffect(() => {
- const onKey = (e: KeyboardEvent) => {
- if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
- e.preventDefault()
- setHighlight((h) => (h + (e.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length)
- } else if (e.key === 'Enter' && highlight >= 0) {
- e.preventDefault()
- if (!items[highlight]?.keepsOpen) dismiss()
- items[highlight]?.action()
- }
- }
- window.addEventListener('keydown', onKey)
- return () => window.removeEventListener('keydown', onKey)
- }, [items, highlight, dismiss])
- return (
- <div className="menu-panel" role="menu" style={{ maxHeight }}>
- {reactions ? (
- <div className={items.length ? 'menu-reactions' : undefined}>
- <ReactionStrip pick={reactions} dismiss={dismiss} />
- </div>
- ) : null}
- {items.map((item, i) => (
- <div key={`${item.title}-${i}`} role="none">
- {item.divider ? <div className="menu-divider" role="separator" /> : null}
- <button
- className={`menu-row ${item.destructive ? 'destructive' : ''} ${highlight === i ? 'highlight' : ''}`}
- role={item.selected === undefined ? 'menuitem' : 'menuitemradio'}
- aria-checked={item.selected}
- title={item.verbatim ? item.title : tr(item.title)}
- onMouseEnter={() => setHighlight(i)}
- onClick={() => {
- if (!item.keepsOpen) dismiss()
- item.action()
- }}
- >
- {item.leading || item.icon ? (
- <span className="menu-icon">
- {item.leading ?? (item.icon ? <Icon name={item.icon} size={12} /> : null)}
- </span>
- ) : null}
- <span className={`menu-title${item.detail ? ' with-detail' : ''}`}>
- <span>{item.verbatim ? item.title : tr(item.title)}</span>
- {item.detail && <span className="menu-detail">{tr(item.detail)}</span>}
- </span>
- {item.selected !== undefined ? (
- <span className={`check-slot${item.selected ? ' on' : ''}`}>
- <Icon name="checkmark" size={10} weight="semibold" />
- </span>
- ) : null}
- </button>
- </div>
- ))}
- </div>
- )
-}
-
-/**
- * Where a panel opens beside `rect`: below it or above (whichever has more room), aligned to the
- * anchor's leading or trailing edge and kept on screen. `room` is the height available.
- */
-export function anchorPlacement(rect: DOMRect) {
- const W = window.innerWidth
- const H = window.innerHeight
- const roomBelow = Math.max(0, H - rect.bottom - 14)
- const roomAbove = Math.max(0, rect.top - 14)
- const below = roomBelow >= roomAbove
- const leading = rect.left + rect.width / 2 < W * 0.6
- const width = Math.min(320, W - 16)
- const inset = Math.max(8, W - width - 8)
- const style: React.CSSProperties = {
- [below ? 'top' : 'bottom']: below ? rect.bottom + 6 : H - rect.top + 6,
- ...(leading ? { left: Math.min(Math.max(8, rect.left), inset) } : { right: Math.min(Math.max(8, W - rect.right), inset) }),
- transformOrigin: `${below ? 'top' : 'bottom'} ${leading ? 'left' : 'right'}`,
- }
- return { style, width, room: below ? roomBelow : roomAbove }
-}
-
-/**
- * Presents `MenuPanel` next to `anchor` (or at `point`, for right-clicks), flipping to stay on
- * screen; a click anywhere else closes it (`.codyncMenu` / `.contextActions`).
- */
-export function AnchoredMenu({ open, onClose, anchor, point, items, reactions }: {
- open: boolean
- onClose: () => void
- anchor?: RefObject<HTMLElement | null>
- point?: { x: number; y: number } | null
- items: () => MenuItem[]
- reactions?: ReactionPick
-}) {
- const { mounted, shown } = usePresence(open, 120)
- const [rect, setRect] = useState<DOMRect | null>(null)
- const frozen = useRef<MenuItem[]>([])
- const layer = useRef<HTMLDivElement>(null)
- if (open) frozen.current = items()
- useLayoutEffect(() => {
- if (!open) return
- if (point) setRect(new DOMRect(point.x, point.y, 0, 0))
- else if (anchor?.current) setRect(anchor.current.getBoundingClientRect())
- }, [open, point, anchor])
- useEscape(open, onClose, layer)
- if (!mounted || !rect) return null
- const { style, width, room } = anchorPlacement(rect)
- return createPortal(
- <div ref={layer} className={`anchored ${shown ? 'shown' : ''}`} onMouseDown={(e) => e.target === e.currentTarget && onClose()} onContextMenu={(e) => { e.preventDefault(); onClose() }}>
- <div className="anchored-panel" style={{ ...style, maxWidth: width }}>
- <MenuPanel items={frozen.current} reactions={reactions} dismiss={onClose} maxHeight={Math.min(420, room)} />
- </div>
- </div>,
- document.body,
- )
-}
-
-/** Right-click opens a Codync menu at the pointer (kit's `.contextActions`). */
-export function useContextMenu() {
- const [point, setPoint] = useState<{ x: number; y: number } | null>(null)
- return {
- point,
- open: point !== null,
- onContextMenu: (e: React.MouseEvent) => {
- e.preventDefault()
- e.stopPropagation()
- setPoint({ x: e.clientX, y: e.clientY })
- },
- close: () => setPoint(null),
- }
-}
-
/** A sheet's content: a full-height column on the page color, usually a ModalHeader and a body. */
export function SheetPage({ className, children }: { className?: string; children: ReactNode }) {
return <div className={`sheet-page${className ? ` ${className}` : ''}`}>{children}</div>
diff --git a/apps/desktop/src/renderer/components/overlay.css b/apps/desktop/src/renderer/components/overlay.css
index ebc354d8..6f58a972 100644
--- a/apps/desktop/src/renderer/components/overlay.css
+++ b/apps/desktop/src/renderer/components/overlay.css
@@ -264,6 +264,13 @@
.menu-row.destructive {
color: var(--danger);
}
+.menu-row:disabled {
+ color: var(--secondary);
+ cursor: default;
+}
+.menu-row:disabled.highlight {
+ background: none;
+}
.menu-row.highlight {
background: rgba(var(--text-rgb), 0.07);
}
diff --git a/apps/desktop/src/renderer/lib/compaction-options.test.ts b/apps/desktop/src/renderer/lib/compaction-options.test.ts
new file mode 100644
index 00000000..a3dfc689
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/compaction-options.test.ts
@@ -0,0 +1,34 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { compactionLabel, compactionMenu, compactionSizes } from './compaction-options.ts'
+
+test('a 1M window offers every 10K from 50K to 960K', () => {
+ const sizes = compactionSizes({ min: 50_000, max: 960_000, step: 10_000 })
+ assert.equal(sizes.length, 92)
+ assert.deepEqual([sizes[0], sizes.at(-1)], [50_000, 960_000])
+ assert.deepEqual(compactionSizes({ min: 50_000, max: 960_000, step: 0 }), [], 'a bad step lists nothing')
+})
+
+test('the menu checks the choice and opens the sizes', () => {
+ const picked: unknown[] = []
+ const menu = compactionMenu(120_000, { min: 50_000, max: 160_000, step: 10_000 }, (t) => picked.push(t))
+ assert.deepEqual(menu.map((m) => m.title), ['Early (default)', 'Near the limit', 'Only when full', 'Set a size'])
+ assert.ok(menu.slice(0, 3).every((m) => m.selected === false))
+ const sizes = menu[3].submenu ?? []
+ assert.deepEqual(sizes.map((m) => m.title), ['50K', '60K', '70K', '80K', '90K', '100K', '110K', '120K', '130K', '140K', '150K', '160K'])
+ assert.deepEqual(sizes.filter((m) => m.selected).map((m) => m.title), ['120K'])
+ sizes[0].action?.()
+ menu[1].action?.()
+ assert.deepEqual(picked, [50_000, 'nearLimit'])
+})
+
+test('before the window is known the sizes wait for the next reply', () => {
+ const menu = compactionMenu('early', null, () => {})
+ assert.equal(menu[0].selected, true)
+ assert.deepEqual(menu.at(-1), { title: "Sizes show after the bot's next reply", disabled: true, divider: true, action: menu.at(-1)?.action })
+})
+
+test('the pill shows a preset translated and a size as it is', () => {
+ assert.deepEqual(compactionLabel('off'), { title: 'Only when full', verbatim: false })
+ assert.deepEqual(compactionLabel(300_000), { title: '300K', verbatim: true })
+})
diff --git a/apps/desktop/src/renderer/lib/compaction-options.ts b/apps/desktop/src/renderer/lib/compaction-options.ts
new file mode 100644
index 00000000..59e3a36a
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/compaction-options.ts
@@ -0,0 +1,33 @@
+import type { CompactionSizes, CompactionThreshold } from '@shared/models'
+import type { MenuItem } from '../components/Menu'
+
+const PRESETS: { id: Exclude<CompactionThreshold, number>; title: string }[] = [
+ { id: 'early', title: 'Early (default)' },
+ { id: 'nearLimit', title: 'Near the limit' },
+ { id: 'off', title: 'Only when full' },
+]
+
+/** A size as the apps show it: thousands of tokens, `120K`. */
+export const sizeLabel = (tokens: number) => `${Math.round(tokens / 1000)}K`
+
+/** The pill's text: a preset's English phrase (translated where it shows), or a size as it is. */
+export function compactionLabel(threshold: CompactionThreshold): { title: string; verbatim: boolean } {
+ if (typeof threshold === 'number') return { title: sizeLabel(threshold), verbatim: true }
+ return { title: PRESETS.find((p) => p.id === threshold)?.title ?? PRESETS[0].title, verbatim: false }
+}
+
+/** Every size the window allows, smallest first. */
+export function compactionSizes(sizes: CompactionSizes): number[] {
+ if (sizes.step <= 0) return []
+ const out: number[] = []
+ for (let n = sizes.min; n <= sizes.max; n += sizes.step) out.push(n)
+ return out
+}
+
+/** The presets, then "Set a size" opening the sizes; before the window is known, a line saying when they come. */
+export function compactionMenu(selection: CompactionThreshold, sizes: CompactionSizes | null, pick: (threshold: CompactionThreshold) => void): MenuItem[] {
+ const presets: MenuItem[] = PRESETS.map((p) => ({ title: p.title, selected: selection === p.id, action: () => pick(p.id) }))
+ if (!sizes) return [...presets, { title: "Sizes show after the bot's next reply", disabled: true, divider: true, action: () => {} }]
+ const submenu: MenuItem[] = compactionSizes(sizes).map((n) => ({ title: sizeLabel(n), verbatim: true, selected: selection === n, action: () => pick(n) }))
+ return [...presets, { title: 'Set a size', divider: true, submenu }]
+}
diff --git a/apps/desktop/src/renderer/views/ChatWindow.tsx b/apps/desktop/src/renderer/views/ChatWindow.tsx
index 5c8a94f9..d4b188c2 100644
--- a/apps/desktop/src/renderer/views/ChatWindow.tsx
+++ b/apps/desktop/src/renderer/views/ChatWindow.tsx
@@ -4,7 +4,8 @@ import { isSSHConnecting, showsChat as shouldShowChat } from '@shared/ssh-startu
import { draftOf, type Bot, type BotDraft } from '@shared/models'
import { CharacterAvatar } from '../components/Avatar'
import { Button, IconButton, ResizeHandle } from '../components/Controls'
-import { AnchoredMenu, Dialog, ModalHeader, Sheet, type MenuItem } from '../components/Overlay'
+import { Dialog, ModalHeader, Sheet } from '../components/Overlay'
+import { AnchoredMenu, type MenuItem } from '../components/Menu'
import { HStack, Spacer } from '../components/Stack'
import { Text } from '../components/Text'
import { useModels } from '../lib/observable'
@@ -43,7 +44,7 @@ import { PairingRequestPrompt } from './PairingRequestPrompt'
import { DeleteAccountPrompt } from './DeleteAccountPrompt'
import { OpenVoiceSettings } from './call/CallView'
import { AccountPanelLayer, ProfileAvatar } from './PanelMenus'
-import { DesktopActionMenu, type ActionItem } from './DesktopActionMenu'
+import { DesktopActionMenu } from './DesktopActionMenu'
import { moveToSectionItems, sectionHeaderItems, type SectionNaming } from './section-menus'
import { makeLeadItems, offersDelete, voiceTarget } from './lead-menus'
import { SectionNameDialog } from './SectionNameDialog'
@@ -206,7 +207,7 @@ function ChatSplitView() {
const [importing, setImporting] = useState(false)
const [newMenu, setNewMenu] = useState(false)
const [railNewMenu, setRailNewMenu] = useState(false)
- const [context, setContext] = useState<{ items: ActionItem[]; x: number; y: number } | null>(null)
+ const [context, setContext] = useState<{ items: MenuItem[]; x: number; y: number } | null>(null)
const [naming, setNaming] = useState<SectionNaming | null>(null)
const [editing, setEditing] = useState<EditTarget | null>(null)
const [confirmDelete, setConfirmDelete] = useState<BotTarget | null>(null)
@@ -299,7 +300,7 @@ function ChatSplitView() {
const openMarketplace = () => setMarketplace((selectedStore ?? app.local ?? onlineStores[0])?.computer.id ?? null)
// One plain list. The lead stays in sight: no hide.
- const botActions = (bot: Bot, store: BotStore): ActionItem[] => [
+ const botActions = (bot: Bot, store: BotStore): MenuItem[] => [
{ title: bot.pinned ? 'Unpin' : 'Pin', icon: 'pin', action: () => store.setPinned(bot, !bot.pinned) },
...moveToSectionItems(bot, store, setNaming),
{ title: 'Mark as Read', icon: 'bell.badge', action: () => store.markAllRead(bot.id) },
diff --git a/apps/desktop/src/renderer/views/ComputerFilterHeader.tsx b/apps/desktop/src/renderer/views/ComputerFilterHeader.tsx
index 1c637278..2a28ddac 100644
--- a/apps/desktop/src/renderer/views/ComputerFilterHeader.tsx
+++ b/apps/desktop/src/renderer/views/ComputerFilterHeader.tsx
@@ -2,7 +2,7 @@ import { sshSummary, sshStatusDetail } from '@shared/ssh-startup'
import { DropdownMenu } from '../components/Controls'
import { ComputerBadge } from './ComputerBadge'
import { Icon } from '../components/Icon'
-import type { MenuItem } from '../components/Overlay'
+import type { MenuItem } from '../components/Menu'
import { Text } from '../components/Text'
import { useApp } from '../store/context'
import { useSSH } from './settings/ssh-model'
diff --git a/apps/desktop/src/renderer/views/DesktopActionMenu.tsx b/apps/desktop/src/renderer/views/DesktopActionMenu.tsx
index f6ccbe48..dc7a45f4 100644
--- a/apps/desktop/src/renderer/views/DesktopActionMenu.tsx
+++ b/apps/desktop/src/renderer/views/DesktopActionMenu.tsx
@@ -1,15 +1,12 @@
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
-import type { MenuItem } from '../components/Overlay'
+import type { MenuItem } from '../components/Menu'
import { ACTION_MENU_WIDTH, menuPlacement, submenuPlacement } from '../lib/menu-placement'
import { submenuHover } from '../lib/submenu-hover'
import { useTr } from '../lib/use-language'
import { PanelRows, type PanelItem } from './PanelMenus'
-/** Roster actions, with one level of desktop submenus. */
-export type ActionItem = MenuItem | (Omit<MenuItem, 'action'> & { submenu: MenuItem[] })
-
-/** Hover opens a child beside its parent. Clicking, Enter, and → enter it; ← or Escape returns. */
-export function DesktopActionMenu({ items, onDismiss, x, y }: { items: ActionItem[]; onDismiss: () => void; x: number; y: number }) {
+/** Roster actions, with one level of submenus beside them. Hover opens a child beside its parent. Clicking, Enter, and → enter it; ← or Escape returns. */
+export function DesktopActionMenu({ items, onDismiss, x, y }: { items: MenuItem[]; onDismiss: () => void; x: number; y: number }) {
const tr = useTr()
const menu = useRef<HTMLDivElement>(null)
const child = useRef<HTMLDivElement>(null)
@@ -39,7 +36,7 @@ export function DesktopActionMenu({ items, onDismiss, x, y }: { items: ActionIte
const returnToParent = () => { closeChild(); anchor.current?.focus({ preventScroll: true }) }
const enter = (index: number, row: HTMLButtonElement | null) => {
const item = items[index]
- if (!row || !item || !('submenu' in item)) return
+ if (!row || !item?.submenu) return
hover.current?.cancel()
anchor.current = row
setOpen(index)
@@ -48,18 +45,18 @@ export function DesktopActionMenu({ items, onDismiss, x, y }: { items: ActionIte
const point = (index: number, row: HTMLButtonElement) => {
const item = items[index]
setLevel('parent')
- if (item && 'submenu' in item) {
+ if (item?.submenu) {
hoveredRow.current = row
hover.current?.schedule(index)
} else hover.current?.schedule(null)
}
- const convert = (item: ActionItem, index: number): PanelItem => ({
+ const convert = (item: MenuItem, index: number): PanelItem => ({
title: item.title, icon: item.icon ?? 'circle', detail: item.detail, verbatim: item.verbatim, destructive: item.destructive,
- ...('submenu' in item ? { chevron: true, submenu: true, expanded: open === index, action: (row: HTMLButtonElement | null) => enter(index, row) }
+ ...(item.submenu ? { chevron: true, submenu: true, expanded: open === index, action: (row: HTMLButtonElement | null) => enter(index, row) }
: { action: () => { onDismiss(); item.action() } }),
})
const branch = open === null ? null : items[open]
- const sub = branch && 'submenu' in branch ? branch : null
+ const sub = branch?.submenu ? branch : null
const placement = menuPlacement({ x, y }, { width: ACTION_MENU_WIDTH, height: size.parent }, view)
const subPlacement = sub && anchor.current && menu.current ? submenuPlacement(
{ ...placement, right: placement.left + placement.width, height: size.parent }, anchor.current.getBoundingClientRect(),
diff --git a/apps/desktop/src/renderer/views/bots/BotEditorView.tsx b/apps/desktop/src/renderer/views/bots/BotEditorView.tsx
index fc5133bb..f820c98c 100644
--- a/apps/desktop/src/renderer/views/bots/BotEditorView.tsx
+++ b/apps/desktop/src/renderer/views/bots/BotEditorView.tsx
@@ -13,6 +13,7 @@ import { useStore } from '../../store/context'
import { useAgentModels } from './agent-models'
import { AgentModelPicker } from './AgentModelPicker'
import { ApprovalRow } from './ApprovalRow'
+import { CompactionRow } from './CompactionRow'
import { agentChoice, AgentStepBanner, FallbacksRow } from './Fallbacks'
import { errorText, isValid, lastPathComponent, normalized, useFollowSaved, usePlugins, type Plugins } from './drafts'
import { FormSheet } from '../marketplace/pieces'
@@ -237,6 +238,7 @@ function BotSettingsForm({ draft, onChange, error, plugins, part = 'all' }: {
</DropdownMenu>
</ValueRow>
<ApprovalRow draft={draft} catalog={models.catalog} onChange={onChange} />
+ <CompactionRow draft={draft} bot={saved} onChange={onChange} />
</CardSection>
<CardSection title="Activity">
diff --git a/apps/desktop/src/renderer/views/bots/CompactionRow.tsx b/apps/desktop/src/renderer/views/bots/CompactionRow.tsx
new file mode 100644
index 00000000..64872503
--- /dev/null
+++ b/apps/desktop/src/renderer/views/bots/CompactionRow.tsx
@@ -0,0 +1,30 @@
+import type { Bot, BotDraft } from '@shared/models'
+import { DropdownMenu, ValueRow } from '../../components/Controls'
+import { Icon } from '../../components/Icon'
+import { compactionLabel, compactionMenu } from '../../lib/compaction-options'
+import { useTr } from '../../lib/use-language'
+
+/** When Codync summarizes the chat: a preset or a size the window allows. Only for a bot whose chat it summarizes. */
+export function CompactionRow({ draft, bot, onChange }: {
+ draft: BotDraft
+ bot: Bot | null
+ onChange: (update: (d: BotDraft) => BotDraft) => void
+}) {
+ const tr = useTr()
+ if (!bot || bot.compaction === null) return null
+ const selection = draft.compaction ?? bot.compaction
+ const { title, verbatim } = compactionLabel(selection)
+ const label = verbatim ? title : tr(title)
+ return (
+ <ValueRow label="Summarize long chats" detail="When Codync summarizes this chat so it can go on. If the chat fills up first, the agent summarizes it itself.">
+ <DropdownMenu
+ title={label}
+ className="choice-picker outlined"
+ items={() => compactionMenu(selection, bot.compactionTokens, (compaction) => onChange((d) => ({ ...d, compaction })))}
+ >
+ <span className="choice-label">{label}</span>
+ <Icon name="chevron.down" size={10} weight="semibold" color="var(--secondary)" />
+ </DropdownMenu>
+ </ValueRow>
+ )
+}
diff --git a/apps/desktop/src/renderer/views/bots/parts.tsx b/apps/desktop/src/renderer/views/bots/parts.tsx
index 63228cd0..cafe7c4e 100644
--- a/apps/desktop/src/renderer/views/bots/parts.tsx
+++ b/apps/desktop/src/renderer/views/bots/parts.tsx
@@ -2,7 +2,8 @@ import { useId, useLayoutEffect, useRef, useState, type ReactNode, type RefObjec
import { createPortal } from 'react-dom'
import { CharacterAvatar } from '../../components/Avatar'
import { RowLabel, Switch } from '../../components/Controls'
-import { anchorPlacement, useEscape, usePresence } from '../../components/Overlay'
+import { useEscape, usePresence } from '../../components/Overlay'
+import { anchorPlacement } from '../../components/Menu'
import { VStack } from '../../components/Stack'
import { useTr } from '../../lib/use-language'
import { AVATAR_COLORS, AVATAR_SHAPES } from '../../lib/theme'
diff --git a/apps/desktop/src/renderer/views/lead-menus.test.ts b/apps/desktop/src/renderer/views/lead-menus.test.ts
index cd935ff5..b32e4611 100644
--- a/apps/desktop/src/renderer/views/lead-menus.test.ts
+++ b/apps/desktop/src/renderer/views/lead-menus.test.ts
@@ -19,7 +19,7 @@ test('any other bot can be made the lead, and the lead deleted', () => {
const { store, made } = computer()
const items = makeLeadItems(bot, store)
assert.deepEqual(items.map((i) => [i.title, i.icon]), [['Make lead agent', 'star']])
- items[0]!.action()
+ items[0]!.action?.()
assert.deepEqual(made, ['bot'])
assert.deepEqual(makeLeadItems(lead, store), [], 'the lead already is')
assert.deepEqual(makeLeadItems(group, store), [], 'a group can\'t lead')
diff --git a/apps/desktop/src/renderer/views/lead-menus.ts b/apps/desktop/src/renderer/views/lead-menus.ts
index 521d7769..09461dad 100644
--- a/apps/desktop/src/renderer/views/lead-menus.ts
+++ b/apps/desktop/src/renderer/views/lead-menus.ts
@@ -1,5 +1,5 @@
import { isGroup, type Bot } from '../../shared/models.ts'
-import type { MenuItem } from '../components/Overlay'
+import type { MenuItem } from '../components/Menu'
import type { BotStore } from '../store/bot-store'
/** A bot row's "Make lead agent"; none for the lead, a group, or while its computer runs a host where the lead can't change. */
diff --git a/apps/desktop/src/renderer/views/library/ArtifactParts.tsx b/apps/desktop/src/renderer/views/library/ArtifactParts.tsx
index 8454105a..613b5de3 100644
--- a/apps/desktop/src/renderer/views/library/ArtifactParts.tsx
+++ b/apps/desktop/src/renderer/views/library/ArtifactParts.tsx
@@ -1,6 +1,6 @@
import { useEffect, useRef, useState } from 'react'
import { artifactFrameURL, type Artifact } from '@shared/artifacts'
-import type { MenuItem } from '../../components/Overlay'
+import type { MenuItem } from '../../components/Menu'
import type { BotStore } from '../../store/bot-store'
import type { ArtifactHTML } from '../../store/artifacts'
import { useTr } from '../../lib/use-language'
diff --git a/apps/desktop/src/renderer/views/section-menus.test.ts b/apps/desktop/src/renderer/views/section-menus.test.ts
index 98d5e031..09a9b476 100644
--- a/apps/desktop/src/renderer/views/section-menus.test.ts
+++ b/apps/desktop/src/renderer/views/section-menus.test.ts
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict'
import { test } from 'node:test'
import type { Bot } from '@shared/models'
import type { BotStore } from '../store/bot-store'
-import type { ActionItem } from './DesktopActionMenu'
+import type { MenuItem } from '../components/Menu'
import { moveToSectionItems, sectionHeaderItems, type SectionNaming } from './section-menus.ts'
/** A computer's store as the menus read it (`archived` is hidden, its section still counts), logging what they ask of it. */
@@ -19,10 +19,10 @@ function computer(hasRosterSections = true) {
}
/** The "Move to section" submenu. */
-function submenu(items: ActionItem[]) {
+function submenu(items: MenuItem[]) {
assert.equal(items.length, 1)
const [move] = items
- assert.ok(move && 'submenu' in move && move.title === 'Move to section')
+ assert.ok(move?.submenu && move.title === 'Move to section')
return move.submenu
}
@@ -32,9 +32,9 @@ test('Move to section offers the other sections (hidden bots\' too), a new one,
assert.deepEqual(rows.map((r) => r.title), ['archive', 'Home', 'New section…', 'Remove from section'])
// Section names show as the user typed them ("Home" stays "Home" in any language); the rest is translated.
assert.deepEqual(rows.map((r) => r.verbatim === true), [true, true, false, false])
- rows[1]!.action()
- rows[3]!.action()
- rows[2]!.action()
+ rows[1]!.action?.()
+ rows[3]!.action?.()
+ rows[2]!.action?.()
assert.deepEqual(naming.map((n) => [n.title, n.name]), [['New section', '']])
naming[0]!.save('Side')
assert.deepEqual(calls, [['move', 'work', 'Home'], ['move', 'work', null], ['move', 'work', 'Side']])
@@ -49,10 +49,10 @@ test('a header renames its section from its name, or removes it', () => {
const { store, calls, naming } = computer()
const items = sectionHeaderItems('Work', store, (n) => naming.push(n), (to) => calls.push(['rename', to]))
assert.deepEqual(items.map((i) => i.title), ['Rename section…', 'Remove section'])
- items[0]!.action()
+ items[0]!.action?.()
assert.deepEqual(naming.map((n) => [n.title, n.name]), [['Rename section', 'Work']])
naming[0]!.save('Jobs')
- items[1]!.action()
+ items[1]!.action?.()
assert.deepEqual(calls, [['rename', 'Jobs'], ['rename', null]])
})
diff --git a/apps/desktop/src/renderer/views/section-menus.ts b/apps/desktop/src/renderer/views/section-menus.ts
index 20e6c0eb..a830e777 100644
--- a/apps/desktop/src/renderer/views/section-menus.ts
+++ b/apps/desktop/src/renderer/views/section-menus.ts
@@ -1,8 +1,7 @@
import type { Bot } from '@shared/models'
-import type { MenuItem } from '../components/Overlay'
+import type { MenuItem } from '../components/Menu'
import { sectionNames } from '../lib/roster-sections.ts'
import type { BotStore } from '../store/bot-store'
-import type { ActionItem } from './DesktopActionMenu'
/** An open section name dialog: its title, the name it starts with, and what Save does with the typed one. */
export interface SectionNaming {
@@ -12,7 +11,7 @@ export interface SectionNaming {
}
/** A bot row's "Move to section"; none while its computer runs a host without sections. */
-export function moveToSectionItems(bot: Bot, store: BotStore, askName: (naming: SectionNaming) => void): ActionItem[] {
+export function moveToSectionItems(bot: Bot, store: BotStore, askName: (naming: SectionNaming) => void): MenuItem[] {
if (!store.hasRosterSections) return []
const others = sectionNames(store.bots.values()).filter((name) => name !== bot.section)
const submenu: MenuItem[] = [
diff --git a/apps/desktop/src/renderer/views/thread/ChatRows.tsx b/apps/desktop/src/renderer/views/thread/ChatRows.tsx
index 8a28d1b6..51fd6d9a 100644
--- a/apps/desktop/src/renderer/views/thread/ChatRows.tsx
+++ b/apps/desktop/src/renderer/views/thread/ChatRows.tsx
@@ -5,7 +5,7 @@ import { groupBotReactions, isGroup, isReplyable, type Bot, type Entry, type Rep
import { BotAvatar } from '../../components/Avatar'
import { Button, IconButton } from '../../components/Controls'
import { Icon } from '../../components/Icon'
-import { AnchoredMenu, useContextMenu, type MenuItem, type ReactionPick } from '../../components/Overlay'
+import { AnchoredMenu, useContextMenu, type MenuItem, type ReactionPick } from '../../components/Menu'
import { HStack, VStack } from '../../components/Stack'
import { Text } from '../../components/Text'
import { messagePreview } from '../../lib/message-preview'
diff --git a/apps/desktop/src/renderer/views/thread/DevServersSection.tsx b/apps/desktop/src/renderer/views/thread/DevServersSection.tsx
index 58b26117..dd0afb05 100644
--- a/apps/desktop/src/renderer/views/thread/DevServersSection.tsx
+++ b/apps/desktop/src/renderer/views/thread/DevServersSection.tsx
@@ -2,7 +2,8 @@ import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'
import { devServerAddress, devServerAddressTitle, devServerClick, devServerMenuRows, devServerValue, type DevServer, type DevServerMenuRow, type DevServerSummary } from '@shared/dev-servers'
import type { Bot } from '@shared/models'
import { Button, IconButton, Spinner } from '../../components/Controls'
-import { AnchoredMenu, ModalHeader, Sheet, SheetPage, type MenuItem } from '../../components/Overlay'
+import { ModalHeader, Sheet, SheetPage } from '../../components/Overlay'
+import { AnchoredMenu, type MenuItem } from '../../components/Menu'
import { HStack, VStack } from '../../components/Stack'
import { Text } from '../../components/Text'
import { useTr } from '../../lib/use-language'
diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.ts
index bea049ae..bb425ed1 100644
--- a/apps/desktop/src/shared/models.ts
+++ b/apps/desktop/src/shared/models.ts
@@ -73,6 +73,10 @@ export interface Bot {
harnessMemory: boolean | null
/** The harness keeps one memory for all its sessions that Codync can't turn off (Hermes Agent, Gemini CLI): every bot on it shares it. */
harnessMemoryShared: boolean
+ /** When Codync summarizes the chat ahead of time; null where it doesn't (an agent it can't ask, an older host). */
+ compaction: CompactionThreshold | null
+ /** The sizes the chat's window allows; null until its agent has told the window. */
+ compactionTokens: CompactionSizes | null
/** Moves whenever memory changes, so an open memory screen fetches it again. */
memoryRev: number
autoName: boolean
@@ -131,6 +135,8 @@ export function normalizeBot(raw: Partial<Bot> & { id: string }): Bot {
sharedMemory: raw.sharedMemory ?? raw.managedWorkspace ?? false,
harnessMemory: raw.harnessMemory ?? null,
harnessMemoryShared: raw.harnessMemoryShared ?? false,
+ compaction: raw.compaction ?? null,
+ compactionTokens: raw.compactionTokens ?? null,
memoryRev: raw.memoryRev ?? 0,
autoName: raw.autoName ?? false,
createdAt,
@@ -259,6 +265,16 @@ export interface BotMessage {
peerName?: string
}
+/** When Codync summarizes a bot's chat ahead of time: a preset, or at a size in tokens. */
+export type CompactionThreshold = 'early' | 'nearLimit' | 'off' | number
+
+/** The sizes a chat's window allows: `min`..`max` by `step` tokens. */
+export interface CompactionSizes {
+ min: number
+ max: number
+ step: number
+}
+
/** "Earlier context was summarized": the harness's summary, when it gave one. */
export interface Compaction {
summary?: string | null
@@ -677,6 +693,8 @@ export interface BotDraft {
reachableByAssistants?: boolean
sharedMemory?: boolean
harnessMemory?: boolean
+ /** Left out where the bot has none: the host keeps what it has. */
+ compaction?: CompactionThreshold
}
export function draftOf(bot: Bot): BotDraft {
@@ -705,6 +723,7 @@ export function draftOf(bot: Bot): BotDraft {
manageTeam: bot.manageTeam ?? undefined,
offeredToNetwork: bot.offeredToNetwork ?? undefined,
reachableByAssistants: bot.reachableByAssistants ?? undefined,
+ compaction: bot.compaction ?? undefined,
}
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Bot.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Bot.swift
index 278e706f..cff11c29 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/Bot.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Bot.swift
@@ -66,6 +66,11 @@ public struct Bot: Codable, Identifiable, Hashable, Sendable {
/// The harness keeps one memory for all its sessions that Codync can't turn off (Hermes Agent, Gemini CLI):
/// every bot on it shares it. Nil from an older host.
public var harnessMemoryShared: Bool?
+ /// When Codync summarizes its chat ahead of time. Nil where it doesn't (an agent it can't ask, a group, an
+ /// older host): no setting to show.
+ public var compaction: CompactionThreshold?
+ /// The sizes `compaction` may take; nil until the agent has told its context window.
+ public var compactionTokens: TokenRange?
/// Moves whenever memory changes, so an open memory screen fetches it again.
public var memoryRev: Int64?
/// Created without a name: the host names it after its first few conversations.
@@ -144,6 +149,8 @@ extension Bot {
sharedMemory = try c.decodeIfPresent(Bool.self, forKey: .sharedMemory)
harnessMemory = try c.decodeIfPresent(Bool.self, forKey: .harnessMemory)
harnessMemoryShared = try c.decodeIfPresent(Bool.self, forKey: .harnessMemoryShared)
+ compaction = try c.decodeIfPresent(CompactionThreshold.self, forKey: .compaction)
+ compactionTokens = try? c.decodeIfPresent(TokenRange.self, forKey: .compactionTokens)
memoryRev = try c.decodeIfPresent(Int64.self, forKey: .memoryRev)
autoName = try c.decodeIfPresent(Bool.self, forKey: .autoName) ?? false
createdAt = try c.decodeIfPresent(Int64.self, forKey: .createdAt) ?? 0
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/CompactionThreshold.swift b/apps/ios/Kit/Sources/CodyncKit/Models/CompactionThreshold.swift
new file mode 100644
index 00000000..67a8efa0
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/CompactionThreshold.swift
@@ -0,0 +1,48 @@
+import Foundation
+
+/// When Codync summarizes a bot's chat ahead of time (the bot's `compaction`): `"early"`, `"nearLimit"`, `"off"`, or a
+/// size in tokens. A value from a newer host reads as the default.
+public enum CompactionThreshold: Codable, Hashable, Sendable {
+ case early, nearLimit, off
+ case tokens(Int)
+
+ public init(from decoder: Decoder) throws {
+ let c = try decoder.singleValueContainer()
+ if let tokens = try? c.decode(Int.self) {
+ self = .tokens(tokens)
+ return
+ }
+ switch try? c.decode(String.self) {
+ case "nearLimit": self = .nearLimit
+ case "off": self = .off
+ default: self = .early
+ }
+ }
+
+ public func encode(to encoder: Encoder) throws {
+ var c = encoder.singleValueContainer()
+ switch self {
+ case .early: try c.encode("early")
+ case .nearLimit: try c.encode("nearLimit")
+ case .off: try c.encode("off")
+ case .tokens(let tokens): try c.encode(tokens)
+ }
+ }
+}
+
+/// The sizes a bot's `CompactionThreshold` may take (`compactionTokens`): `min` to `max` tokens by `step`.
+public struct TokenRange: Codable, Hashable, Sendable {
+ public var min: Int
+ public var max: Int
+ public var step: Int
+
+ public init(min: Int, max: Int, step: Int) {
+ self.min = min
+ self.max = max
+ self.step = step
+ }
+
+ public var sizes: [Int] {
+ step > 0 && min <= max ? Array(stride(from: min, through: max, by: step)) : []
+ }
+}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift
index a44c74ab..2450e370 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift
@@ -346,6 +346,8 @@ public struct BotDraft: Codable, Hashable, Sendable {
public var sharedMemory: Bool?
/// Only sent when the user changes it.
public var harnessMemory: Bool?
+ /// Nil where the host offers no setting (a new bot, an agent it can't ask), so it isn't sent.
+ public var compaction: CompactionThreshold?
public init(name: String = "", description: String = "", avatarColor: String = AvatarPalette.colors.randomElement()!.id,
avatarShape: String = AvatarPalette.shapes.randomElement()!, backend: String = "claude", cwd: String = "",
@@ -385,6 +387,7 @@ public struct BotDraft: Codable, Hashable, Sendable {
manageTeam = bot.manageTeam
offeredToNetwork = bot.offeredToNetwork
reachableByAssistants = bot.reachableByAssistants
+ compaction = bot.compaction
}
/// This draft with each field it hasn't changed from `base` (the bot as the form loaded it) taken from `fresh`
@@ -400,6 +403,7 @@ public struct BotDraft: Codable, Hashable, Sendable {
follow(\.fastMode); follow(\.fallbacks); follow(\.selfFallbacks); follow(\.pinned); follow(\.hidden)
follow(\.notify); follow(\.connectors); follow(\.skills); follow(\.computer); follow(\.manageTeam)
follow(\.sharedMemory); follow(\.harnessMemory); follow(\.offeredToNetwork); follow(\.reachableByAssistants)
+ follow(\.compaction)
return draft
}
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
index 21f80c12..7b3afbe5 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
@@ -1882,5 +1882,14 @@
"Sign in there with {email} and add it to your account, and it shows up here.": "Melde dich dort mit {email} an und füge ihn deinem Konto hinzu, dann erscheint er hier.",
"Scan with the Codync app or the iPhone Camera.": "Scanne mit der Codync-App oder der iPhone-Kamera.",
"Phones paired without this account lose access and must pair again.": "Nicht mit diesem Konto gekoppelte Telefone verlieren den Zugriff und müssen neu gekoppelt werden.",
- "This message's files aren't on this device anymore. Delete it and attach them again.": "Die Dateien dieser Nachricht sind nicht mehr auf diesem Gerät. Lösche sie und hänge die Dateien erneut an."
+ "This message's files aren't on this device anymore. Delete it and attach them again.": "Die Dateien dieser Nachricht sind nicht mehr auf diesem Gerät. Lösche sie und hänge die Dateien erneut an.",
+ "Summarize long chats": "Lange Chats zusammenfassen",
+ "When Codync summarizes this chat so it can go on. If the chat fills up first, the agent summarizes it itself.": "Wann Codync diesen Chat zusammenfasst, damit er weitergehen kann. Füllt sich der Chat vorher, fasst der Agent ihn selbst zusammen.",
+ "Early (default)": "Früh (Standard)",
+ "Near the limit": "Kurz vor dem Limit",
+ "Set a size": "Größe festlegen",
+ "Sizes show after the bot's next reply": "Größen erscheinen nach der nächsten Antwort des Bots",
+ "Only when full": "Nur wenn voll",
+ "Summarize": "Verdichten",
+ "Claude Code and Codex bots only": "Nur für Claude-Code- und Codex-Bots"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
index e6725fcf..8170d3b3 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
@@ -1882,5 +1882,14 @@
"Sign in there with {email} and add it to your account, and it shows up here.": "Inicia sesión allí con {email} y añádelo a tu cuenta, y aparecerá aquí.",
"Scan with the Codync app or the iPhone Camera.": "Escanea con la app de Codync o la cámara del iPhone.",
"Phones paired without this account lose access and must pair again.": "Los teléfonos emparejados sin esta cuenta pierden el acceso y deben emparejarse de nuevo.",
- "This message's files aren't on this device anymore. Delete it and attach them again.": "Los archivos de este mensaje ya no están en este dispositivo. Elimínalo y vuelve a adjuntarlos."
+ "This message's files aren't on this device anymore. Delete it and attach them again.": "Los archivos de este mensaje ya no están en este dispositivo. Elimínalo y vuelve a adjuntarlos.",
+ "Summarize long chats": "Resumir chats largos",
+ "When Codync summarizes this chat so it can go on. If the chat fills up first, the agent summarizes it itself.": "Cuándo Codync resume este chat para que pueda continuar. Si el chat se llena antes, el agente lo resume por su cuenta.",
+ "Early (default)": "Pronto (predeterminado)",
+ "Near the limit": "Cerca del límite",
+ "Set a size": "Elegir un tamaño",
+ "Sizes show after the bot's next reply": "Los tamaños aparecen tras la próxima respuesta del bot",
+ "Only when full": "Solo cuando esté lleno",
+ "Summarize": "Resumir",
+ "Claude Code and Codex bots only": "Solo para bots de Claude Code y Codex"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
index 7e1ef02a..d9e5acff 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
@@ -1882,5 +1882,14 @@
"Sign in there with {email} and add it to your account, and it shows up here.": "Connectez-vous-y avec {email} et ajoutez-le à votre compte : il apparaîtra ici.",
"Scan with the Codync app or the iPhone Camera.": "Scannez avec l'app Codync ou l'appareil photo de l'iPhone.",
"Phones paired without this account lose access and must pair again.": "Les téléphones jumelés sans ce compte perdent l'accès et devront être jumelés à nouveau.",
- "This message's files aren't on this device anymore. Delete it and attach them again.": "Les fichiers de ce message ne sont plus sur cet appareil. Supprimez-le et joignez-les à nouveau."
+ "This message's files aren't on this device anymore. Delete it and attach them again.": "Les fichiers de ce message ne sont plus sur cet appareil. Supprimez-le et joignez-les à nouveau.",
+ "Summarize long chats": "Résumer les longues discussions",
+ "When Codync summarizes this chat so it can go on. If the chat fills up first, the agent summarizes it itself.": "Quand Codync résume cette discussion pour qu’elle puisse continuer. Si la discussion se remplit avant, l’agent la résume lui-même.",
+ "Early (default)": "Tôt (par défaut)",
+ "Near the limit": "Près de la limite",
+ "Set a size": "Choisir une taille",
+ "Sizes show after the bot's next reply": "Les tailles apparaissent après la prochaine réponse du bot",
+ "Only when full": "Seulement quand c'est plein",
+ "Summarize": "Résumés",
+ "Claude Code and Codex bots only": "Uniquement pour les bots Claude Code et Codex"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json
index f47832b7..6e4a2d48 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json
@@ -1882,5 +1882,14 @@
"Sign in there with {email} and add it to your account, and it shows up here.": "Accedi lì con {email} e aggiungilo al tuo account: comparirà qui.",
"Scan with the Codync app or the iPhone Camera.": "Scansiona con l'app Codync o la fotocamera dell'iPhone.",
"Phones paired without this account lose access and must pair again.": "I telefoni associati senza questo account perdono l'accesso e devono essere associati di nuovo.",
- "This message's files aren't on this device anymore. Delete it and attach them again.": "I file di questo messaggio non sono più su questo dispositivo. Eliminalo e allega di nuovo i file."
+ "This message's files aren't on this device anymore. Delete it and attach them again.": "I file di questo messaggio non sono più su questo dispositivo. Eliminalo e allega di nuovo i file.",
+ "Summarize long chats": "Riassunto delle chat lunghe",
+ "When Codync summarizes this chat so it can go on. If the chat fills up first, the agent summarizes it itself.": "Quando Codync riassume questa chat perché possa continuare. Se la chat si riempie prima, l'agente la riassume da solo.",
+ "Early (default)": "Presto (predefinito)",
+ "Near the limit": "Vicino al limite",
+ "Set a size": "Imposta una dimensione",
+ "Sizes show after the bot's next reply": "Le dimensioni compaiono dopo la prossima risposta del bot",
+ "Only when full": "Solo quando è pieno",
+ "Summarize": "Riassunti",
+ "Claude Code and Codex bots only": "Solo per i bot di Claude Code e Codex"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
index 306886bb..9a107454 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
@@ -1882,5 +1882,14 @@
"Sign in there with {email} and add it to your account, and it shows up here.": "そこで {email} でサインインしてアカウントに追加すると、ここに表示されます。",
"Scan with the Codync app or the iPhone Camera.": "Codync アプリまたは iPhone のカメラでスキャンしてください。",
"Phones paired without this account lose access and must pair again.": "このアカウントでペアリングしていないスマートフォンはアクセスを失い、再度ペアリングが必要です。",
- "This message's files aren't on this device anymore. Delete it and attach them again.": "このメッセージのファイルはこの端末にもうありません。メッセージを削除して、もう一度ファイルを添付してください。"
+ "This message's files aren't on this device anymore. Delete it and attach them again.": "このメッセージのファイルはこの端末にもうありません。メッセージを削除して、もう一度ファイルを添付してください。",
+ "Summarize long chats": "長いチャットを要約",
+ "When Codync summarizes this chat so it can go on. If the chat fills up first, the agent summarizes it itself.": "Codync がこのチャットを要約して続けられるようにするタイミングです。先にチャットがいっぱいになった場合は、エージェントが自分で要約します。",
+ "Early (default)": "早め(デフォルト)",
+ "Near the limit": "上限の手前",
+ "Set a size": "サイズを指定",
+ "Sizes show after the bot's next reply": "ボットの次の返信後にサイズを選べます",
+ "Only when full": "満杯になったときだけ",
+ "Summarize": "要約",
+ "Claude Code and Codex bots only": "Claude Code と Codex のボットのみ"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
index 382409c0..1d95d10a 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
@@ -1882,5 +1882,14 @@
"Sign in there with {email} and add it to your account, and it shows up here.": "거기서 {email}(으)로 로그인하고 계정에 추가하면 여기에 표시됩니다.",
"Scan with the Codync app or the iPhone Camera.": "Codync 앱 또는 iPhone 카메라로 스캔하세요.",
"Phones paired without this account lose access and must pair again.": "이 계정으로 페어링하지 않은 휴대폰은 접근 권한을 잃으며 다시 페어링해야 합니다.",
- "This message's files aren't on this device anymore. Delete it and attach them again.": "이 메시지의 파일이 더 이상 이 기기에 없습니다. 메시지를 삭제하고 파일을 다시 첨부하세요."
+ "This message's files aren't on this device anymore. Delete it and attach them again.": "이 메시지의 파일이 더 이상 이 기기에 없습니다. 메시지를 삭제하고 파일을 다시 첨부하세요.",
+ "Summarize long chats": "긴 채팅 요약",
+ "When Codync summarizes this chat so it can go on. If the chat fills up first, the agent summarizes it itself.": "Codync가 이 채팅을 요약해 계속 이어갈 수 있게 하는 시점입니다. 채팅이 먼저 가득 차면 에이전트가 직접 요약합니다.",
+ "Early (default)": "일찍(기본값)",
+ "Near the limit": "한도 직전",
+ "Set a size": "크기 지정",
+ "Sizes show after the bot's next reply": "봇의 다음 답장 후에 크기를 고를 수 있습니다",
+ "Only when full": "가득 찼을 때만",
+ "Summarize": "압축",
+ "Claude Code and Codex bots only": "Claude Code와 Codex 봇에서만"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json
index c88f1519..5bb749e1 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json
@@ -1882,5 +1882,14 @@
"Sign in there with {email} and add it to your account, and it shows up here.": "Entre lá com {email} e adicione-o à sua conta, e ele aparece aqui.",
"Scan with the Codync app or the iPhone Camera.": "Escaneie com o app Codync ou a câmera do iPhone.",
"Phones paired without this account lose access and must pair again.": "Celulares pareados sem esta conta perdem o acesso e precisam parear de novo.",
- "This message's files aren't on this device anymore. Delete it and attach them again.": "Os arquivos desta mensagem não estão mais neste dispositivo. Exclua a mensagem e anexe os arquivos de novo."
+ "This message's files aren't on this device anymore. Delete it and attach them again.": "Os arquivos desta mensagem não estão mais neste dispositivo. Exclua a mensagem e anexe os arquivos de novo.",
+ "Summarize long chats": "Resumir conversas longas",
+ "When Codync summarizes this chat so it can go on. If the chat fills up first, the agent summarizes it itself.": "Quando o Codync resume esta conversa para que ela possa continuar. Se a conversa encher antes, o agente a resume sozinho.",
+ "Early (default)": "Cedo (padrão)",
+ "Near the limit": "Perto do limite",
+ "Set a size": "Definir um tamanho",
+ "Sizes show after the bot's next reply": "Os tamanhos aparecem após a próxima resposta do bot",
+ "Only when full": "Só quando estiver cheio",
+ "Summarize": "Resumir",
+ "Claude Code and Codex bots only": "Só para bots do Claude Code e do Codex"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json
index 9e5a670b..fa759c4f 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json
@@ -1882,5 +1882,14 @@
"Sign in there with {email} and add it to your account, and it shows up here.": "Войдите там как {email} и добавьте его в аккаунт: он появится здесь.",
"Scan with the Codync app or the iPhone Camera.": "Отсканируйте в приложении Codync или камерой iPhone.",
"Phones paired without this account lose access and must pair again.": "Телефоны, сопряжённые без этого аккаунта, потеряют доступ, и их нужно будет сопрячь заново.",
- "This message's files aren't on this device anymore. Delete it and attach them again.": "Файлов этого сообщения больше нет на этом устройстве. Удалите его и прикрепите файлы заново."
+ "This message's files aren't on this device anymore. Delete it and attach them again.": "Файлов этого сообщения больше нет на этом устройстве. Удалите его и прикрепите файлы заново.",
+ "Summarize long chats": "Сжатие длинных чатов",
+ "When Codync summarizes this chat so it can go on. If the chat fills up first, the agent summarizes it itself.": "Когда Codync сжимает этот чат в сводку, чтобы его можно было продолжить. Если чат заполнится раньше, агент сожмёт его сам.",
+ "Early (default)": "Рано (по умолчанию)",
+ "Near the limit": "У предела",
+ "Set a size": "Задать размер",
+ "Sizes show after the bot's next reply": "Размеры появятся после следующего ответа бота",
+ "Only when full": "Только когда заполнится",
+ "Summarize": "Сжатие",
+ "Claude Code and Codex bots only": "Только для ботов Claude Code и Codex"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
index b07709f6..3aa87c28 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
@@ -1882,5 +1882,14 @@
"Sign in there with {email} and add it to your account, and it shows up here.": "在那里用 {email} 登录并将电脑加入账户,它就会显示在这里。",
"Scan with the Codync app or the iPhone Camera.": "用 Codync App 或 iPhone 相机扫描。",
"Phones paired without this account lose access and must pair again.": "未用此账户配对的手机将失去访问权限,必须重新配对。",
- "This message's files aren't on this device anymore. Delete it and attach them again.": "此消息的文件已不在此设备上。请删除这条消息并重新添加文件。"
+ "This message's files aren't on this device anymore. Delete it and attach them again.": "此消息的文件已不在此设备上。请删除这条消息并重新添加文件。",
+ "Summarize long chats": "压缩对话",
+ "When Codync summarizes this chat so it can go on. If the chat fills up first, the agent summarizes it itself.": "Codync 何时把这个对话压缩成摘要,好让对话继续下去。对话若先塞满,agent 会自己压缩。",
+ "Early (default)": "提早(默认)",
+ "Near the limit": "接近上限",
+ "Set a size": "指定数量",
+ "Sizes show after the bot's next reply": "Bot 下次回复后就能指定数量",
+ "Only when full": "不主动压缩",
+ "Summarize": "压缩",
+ "Claude Code and Codex bots only": "仅适用于 Claude Code 和 Codex 的 bot"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
index d100c379..7ba168a2 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
@@ -1882,5 +1882,14 @@
"Sign in there with {email} and add it to your account, and it shows up here.": "在那裡用 {email} 登入並將電腦加入賬戶,它就會顯示在這裡。",
"Scan with the Codync app or the iPhone Camera.": "用 Codync App 或 iPhone 相機掃描。",
"Phones paired without this account lose access and must pair again.": "未用此賬戶配對的手機將失去存取權,必須重新配對。",
- "This message's files aren't on this device anymore. Delete it and attach them again.": "這則訊息的檔案已不在此裝置上。請刪除這則訊息並重新新增檔案。"
+ "This message's files aren't on this device anymore. Delete it and attach them again.": "這則訊息的檔案已不在此裝置上。請刪除這則訊息並重新新增檔案。",
+ "Summarize long chats": "壓縮對話",
+ "When Codync summarizes this chat so it can go on. If the chat fills up first, the agent summarizes it itself.": "Codync 何時把這個對話壓縮成摘要,好讓對話繼續下去。對話若先塞滿,agent 會自己壓縮。",
+ "Early (default)": "提早(預設)",
+ "Near the limit": "接近上限",
+ "Set a size": "指定數量",
+ "Sizes show after the bot's next reply": "Bot 下次回覆後就能指定數量",
+ "Only when full": "不主動壓縮",
+ "Summarize": "壓縮",
+ "Claude Code and Codex bots only": "只適用於 Claude Code 和 Codex 的 bot"
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swift
index b98dfedc..2d9fbb7b 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swift
@@ -215,6 +215,11 @@ struct BotSettingsForm: View {
.help(draft.cwd.isEmpty ? "A persistent workspace allocated for this bot" : draft.cwd)
}
ApprovalPicker(draft: $draft, reload: modelReload)
+ // Only where the host summarizes this bot's chat (its bot says).
+ if bot?.compaction != nil, draft.compaction != nil {
+ CompactionPicker(selection: Binding(get: { draft.compaction ?? .early }, set: { draft.compaction = $0 }),
+ range: bot?.compactionTokens)
+ }
}
.animation(Motion.reduced(Motion.layout, reduceMotion), value: bot?.agentStep)
diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/CompactionPicker.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/CompactionPicker.swift
new file mode 100644
index 00000000..c2172bf3
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/CompactionPicker.swift
@@ -0,0 +1,45 @@
+import CodyncKit
+import SwiftUI
+
+/// When Codync summarizes the bot's chat ahead of time: early, near the limit, off, or a size its window holds.
+struct CompactionPicker: View {
+ @Binding var selection: CompactionThreshold
+ /// Nil until the agent has told its window.
+ let range: TokenRange?
+
+ private static let presets: [(CompactionThreshold, String)] =
+ [(.early, "Early (default)"), (.nearLimit, "Near the limit"), (.off, "Only when full")]
+
+ var body: some View {
+ ValueRow("Summarize long chats",
+ detail: "When Codync summarizes this chat so it can go on. If the chat fills up first, the agent summarizes it itself.") {
+ DropdownMenu { items } label: {
+ HStack(spacing: 6) {
+ Text(verbatim: label).lineLimit(1)
+ Image(systemName: "chevron.down").font(.caption2.weight(.semibold)).foregroundStyle(Palette.secondary)
+ }
+ .foregroundStyle(Palette.text)
+ .outlinedPill()
+ }
+ }
+ }
+
+ private var items: [MenuItem] {
+ let rows = Self.presets.map { choice, title in MenuItem(title, selected: selection == choice) { selection = choice } }
+ guard let sizes = range?.sizes, !sizes.isEmpty else {
+ return rows + [MenuItem("Sizes show after the bot's next reply", divider: true, enabled: false) {}]
+ }
+ let picks = sizes.map { tokens in
+ MenuItem(Self.size(tokens), selected: selection == .tokens(tokens), verbatim: true) { selection = .tokens(tokens) }
+ }
+ return rows + [MenuItem("Set a size", divider: true, submenu: picks)]
+ }
+
+ private var label: String {
+ if case .tokens(let tokens) = selection { return Self.size(tokens) }
+ return L10n.tr((Self.presets.first { $0.0 == selection } ?? Self.presets[0]).1)
+ }
+
+ /// "120K".
+ static func size(_ tokens: Int) -> String { "\(tokens / 1000)K" }
+}
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/CompactionTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/CompactionTests.swift
new file mode 100644
index 00000000..f3a3044d
--- /dev/null
+++ b/apps/ios/Kit/Tests/CodyncKitTests/CompactionTests.swift
@@ -0,0 +1,40 @@
+import Foundation
+import Testing
+@testable import CodyncKit
+
+private func bot(_ extra: String) throws -> Bot {
+ try JSONDecoder().decode(Bot.self, from: Data(#"{"id":"b","name":"Ada","backend":"claude","cwd":"/tmp"\#(extra)}"#.utf8))
+}
+
+@Test func compactionReadsEachWireValue() throws {
+ #expect(try bot(#","compaction":"early""#).compaction == .early)
+ #expect(try bot(#","compaction":"nearLimit""#).compaction == .nearLimit)
+ #expect(try bot(#","compaction":"off""#).compaction == .off)
+ #expect(try bot(#","compaction":120000"#).compaction == .tokens(120_000))
+ #expect(try bot(#","compaction":"later""#).compaction == .early, "a newer host's value reads as the default")
+ #expect(try bot(#","compaction":null"#).compaction == nil, "no setting where Codync can't summarize")
+ #expect(try bot("").compaction == nil, "an older host")
+
+ let sized = try bot(#","compaction":"early","compactionTokens":{"min":50000,"max":80000,"step":10000}"#)
+ #expect(sized.compactionTokens?.sizes == [50_000, 60_000, 70_000, 80_000])
+ #expect(try bot(#","compaction":"early","compactionTokens":null"#).compactionTokens == nil, "window not known yet")
+}
+
+@Test func theDraftSendsCompactionOnlyWhereTheHostOffersIt() throws {
+ func sent(_ draft: BotDraft) throws -> [String: Any] {
+ try #require(JSONSerialization.jsonObject(with: JSONEncoder().encode(BotUpdate(draft: draft))) as? [String: Any])
+ }
+ var draft = BotDraft(try bot(#","compaction":"early""#))
+ draft.compaction = .tokens(300_000)
+ #expect(try sent(draft)["compaction"] as? Int == 300_000)
+ draft.compaction = .nearLimit
+ #expect(try sent(draft)["compaction"] as? String == "nearLimit")
+ #expect(try sent(BotDraft(try bot("")))["compaction"] == nil, "nothing to send to a host without it")
+ #expect(try sent(BotDraft())["compaction"] == nil, "a new bot takes the host's default")
+
+ // A change made elsewhere comes through unless this form changed it too.
+ let base = BotDraft(try bot(#","compaction":"early""#))
+ let fresh = BotDraft(try bot(#","compaction":"off""#))
+ #expect(base.rebased(from: base, onto: fresh).compaction == .off)
+ #expect(draft.rebased(from: base, onto: fresh).compaction == .nearLimit)
+}
diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.md
index 094197a8..c0a36877 100644
--- a/apps/ios/WhatsNew.md
+++ b/apps/ios/WhatsNew.md
@@ -6,6 +6,13 @@ any left). tools/asc-submit.py reads the released version's section;
a version without one gets a generic "Bug fixes and improvements" line. Delete old sections.
-->
+## 2.42.0
+### zh-Hant
+- bot 設定新增「壓縮對話」:選擇 Codync 什麼時候把長對話壓縮成摘要。可以選提早(預設)、接近上限、不主動壓縮,或以 10K 為一級自己指定數量,最多到模型裝得下的上限。適用於 Claude Code 和 Codex 的 bot。
+
+### en-US
+- New Summarize long chats setting for a bot: choose when Codync summarizes a long chat. Pick Early (default), Near the limit, Only when full, or a size you set in 10K steps, up to what the model holds. For Claude Code and Codex bots.
+
## 2.41.0
### zh-Hant
- 不登入也能用了:在歡迎畫面選擇「不登入繼續」,手機掃電腦的 QR 碼就能配對,透過 Wi-Fi 或 Tailscale 連線。之後登入,配對會留在手機上;到「管理電腦」按「加入帳號」,電腦確認後就能從任何地方連線。
diff --git a/apps/maestro/compaction.js b/apps/maestro/compaction.js
new file mode 100644
index 00000000..f23c652f
--- /dev/null
+++ b/apps/maestro/compaction.js
@@ -0,0 +1,32 @@
+// Makes the bot `compaction.yaml` opens, on the host the phone is paired with (HOST_PORT and HOST_TOKEN, passed with
+// `-e`), and has it reply once. Its agent is host/tests/fixtures/instructions_agent.py (FIXTURE_AGENT, its full path),
+// which answers as Claude's adapter does and reports the window its message names, so the bot offers sizes. `STORED`
+// checks the host keeps that setting; `CLEANUP`, when the flow completes, deletes the bot again.
+const api = (method, body) => {
+ const res = http.post(`http://127.0.0.1:${HOST_PORT}/api/${method}`, {
+ headers: { Authorization: `Bearer ${HOST_TOKEN}`, 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ })
+ if (res.status !== 200) throw new Error(`${method}: ${res.status} ${res.body}`)
+ return json(res.body)
+}
+
+if (typeof CLEANUP !== 'undefined') {
+ if (output.bot) api('deleteBot', { botId: output.bot.id })
+} else if (typeof STORED !== 'undefined') {
+ // The apps save 600 ms after the last change. An update that changes nothing answers with the bot as the host keeps it.
+ let kept
+ for (let tries = 0; tries < 10 && String(kept) !== STORED; tries++) {
+ const until = Date.now() + 300
+ while (Date.now() < until) {} // ponytail: the script has no sleep; a busy wait of at most 3 s
+ kept = api('updateBot', { id: output.bot.id }).bot.compaction
+ }
+ if (String(kept) !== STORED) throw new Error(`the host keeps ${kept}, not ${STORED}`)
+} else {
+ const name = `Summarize check ${Math.random().toString(36).slice(2, 6)}`
+ const bot = api('createBot', {
+ name, backend: 'custom', command: `python3 -X utf8 -u '${FIXTURE_AGENT}' claude`, connectors: [], skills: [], notify: false,
+ }).bot
+ api('send', { botId: bot.id, text: 'USAGE 10000 SIZE 1000000', clientNonce: `compaction-${bot.id}` })
+ output.bot = { name, id: bot.id }
+}
diff --git a/apps/maestro/compaction.yaml b/apps/maestro/compaction.yaml
new file mode 100644
index 00000000..e49bad73
--- /dev/null
+++ b/apps/maestro/compaction.yaml
@@ -0,0 +1,62 @@
+# A bot's Summarize long chats setting on the phones: once its agent has replied and told its window, the menu has the
+# three choices and Set a size, whose sizes go up to what the window holds; a size picked shows on the pill and the host
+# keeps it, and so does a choice. The phone must already be signed in and paired with the host (a worktree's sandbox,
+# docs/guides/dev-app.md#worktree-sandboxes), so run it apart from `welcome`, whose clearState undoes that; the flow
+# makes its own bot there:
+# maestro --device "<simulator udid>,<adb serial>" test --shard-all 2 --include-tags bot-settings \
+# -e HOST_PORT=<sandbox port> -e HOST_TOKEN="$(cat ~/.codync-dev-<sandbox name>/token)" \
+# -e FIXTURE_AGENT="$PWD/host/tests/fixtures/instructions_agent.py" apps/maestro
+appId: com.pokai.Codync.ios.dev
+tags:
+ - bot-settings
+onFlowComplete:
+ - runScript:
+ file: compaction.js
+ env:
+ CLEANUP: "true"
+---
+- runScript: compaction.js
+- runFlow:
+ when:
+ platform: iOS
+ commands:
+ - launchApp:
+ appId: com.pokai.Codync.ios.dev
+ arguments:
+ "-reviewInvitationOff": true
+- runFlow:
+ when:
+ platform: Android
+ commands:
+ - launchApp:
+ appId: com.pokai.Codync.android.dev
+- tapOn: ${output.bot.name}
+# The agent's reply: by then the host knows the window.
+- extendedWaitUntil:
+ visible: "ok"
+ timeout: 20000
+- tapOn: "${output.bot.name}, view details"
+- tapOn: "Settings"
+# Centered, so the pill under the label is on screen too (on Android the label alone can stop at the bottom edge).
+- scrollUntilVisible:
+ element: "Summarize long chats"
+ centerElement: true
+- tapOn: "Early \\(default\\)"
+- assertVisible: "Near the limit"
+- assertVisible: "Only when full"
+- tapOn: "Set a size"
+- assertVisible: "50K"
+- tapOn: "120K"
+- assertVisible: "120K"
+- takeScreenshot: compaction-size
+- runScript:
+ file: compaction.js
+ env:
+ STORED: "120000"
+- tapOn: "120K"
+- tapOn: "Only when full"
+- assertVisible: "Only when full"
+- runScript:
+ file: compaction.js
+ env:
+ STORED: "off"
diff --git a/docs/design/bot-memory.md b/docs/design/bot-memory.md
index 425d3aa0..40e155c4 100644
--- a/docs/design/bot-memory.md
+++ b/docs/design/bot-memory.md
@@ -427,6 +427,24 @@ doubles the write cost on API billing.
| **Rollover** | Any of: (1) returning with a cold cache and `used ≥ 100k`; (2) away ≥ 8 hours with ≥ 3 compactions; (3) the loop guard fires | Summaries of summaries drift. A new session starts with a handoff. |
| **Safety net** | A single turn fills the window | The harness's own auto-compaction |
+These are the defaults. Each Claude Code or Codex bot has a **Summarize long chats** setting (`compaction` in its
+config, `codync_mem::compaction::Threshold`) that moves the end-of-turn trigger:
+
+| Setting | End-of-turn trigger | Idle compaction and cold rollover |
+|---|---|---|
+| Early (`"early"`, the default) | `min(0.75 × size, 200k)` | Past 100k, as above |
+| Near the limit (`"nearLimit"`) | The largest size the window allows: `size − 40k`, rounded down to 10k (960k on a 1M window), never below Early's trigger | Only past the trigger |
+| A size (a number) | That many tokens, a multiple of 10k and at least 50k, held to the largest size the window allows | Only past the trigger (and 100k) |
+| Only when full (`"off"`) | None | None: the harness's own auto-compaction is all there is |
+
+The 40k headroom is the compaction turn itself (its prompt and a summary of about 20k). Below 50k, the summary and
+the opening alone would trip the trigger every few turns. The long-absence rollover (8 hours, 3 compactions) and
+the loop guard apply to every setting but Only when full. The apps list the sizes from `compactionTokens`
+(`{min, max, step}`), which the host sends once the bot's own agent (not a fallback) has reported the main chat's
+window (kept in `context.window.<bot>`); before that they offer only the three choices. A custom command that
+reported a window keeps its setting while its agent isn't running. Other agents have no setting (`compaction` is
+`null`) and keep the defaults for rollovers.
+
The `idleCompaction` setting needs no change. The harness never idle-compacts in SDK/ACP sessions, and setting it
to true "does not turn idle compaction on".
diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.md
index d760d65c..b2cd688d 100644
--- a/docs/design/ui-conventions.md
+++ b/docs/design/ui-conventions.md
@@ -57,13 +57,13 @@ The chat window's account menu copies Grok Bot's: Usage, Get Codync for mobile,
The iPhone and the desktop no longer share UI code. `CodyncUI` (`apps/ios/Kit/`) is the iPhone app's own package; the desktop app (`apps/desktop/src/renderer/`) is a TypeScript port of the same screens with its own `BotStore`, chat items (`views/thread/chat-items.ts`) and Markdown blocks (`markdown-blocks.ts`).
- The iPhone chat's chrome is in `ThreadView.swift` (`body`, `chrome`, `header`). The iPhone conversation is a UIKit collection view of hosted SwiftUI rows (`ConversationList.swift`): it loads earlier messages from the computer as the reader scrolls up, runs under the bars and the composer (the list sits in the safe area and reaches past it, so rows never get a safe area of their own), follows the newest message until they scroll away (with a round "Jump to latest" button), and pops each new message in ([chat messages](../features/chat-messages.md)).
-- The desktop UI rules (custom controls, no system menus except the tray, icon-only buttons, fill or border) are implemented in `apps/desktop/src/renderer/components/` (`Controls.tsx`, `Overlay.tsx`, `Icon.tsx`, `Text.tsx`, `Stack.tsx`); how views use them and the theme tokens: [desktop styles](../guides/desktop-styles.md). Chrome on the sidebar (its header actions, the computer filter, Extensions) is outlined; chrome floating over the conversation (the title pill, the composer) is filled with a shadow, and the composer also carries the floating-layer outline. Corner radii and shadows come from the `--radius-*` and `--shadow-*` scale in `styles/theme.css`. Status text uses `--attention` (`--warning` is for dots and fills only), and destructive fills use `--danger-fill` with `--on-danger`, so both stay readable in light and dark. Sheets and dialogs hold focus while open: the window behind goes inert, Tab cycles inside, and focus returns to where it was on close. With several open at once, only the one drawn on top (a dialog over a sheet) and the menus opened from it take clicks, focus and Escape; the next one down takes over when it closes, and focus goes back to the first one's opener when the last closes.
+- The desktop UI rules (custom controls, no system menus except the tray, icon-only buttons, fill or border) are implemented in `apps/desktop/src/renderer/components/` (`Controls.tsx`, `Overlay.tsx`, `Menu.tsx`, `Icon.tsx`, `Text.tsx`, `Stack.tsx`); how views use them and the theme tokens: [desktop styles](../guides/desktop-styles.md). Chrome on the sidebar (its header actions, the computer filter, Extensions) is outlined; chrome floating over the conversation (the title pill, the composer) is filled with a shadow, and the composer also carries the floating-layer outline. Corner radii and shadows come from the `--radius-*` and `--shadow-*` scale in `styles/theme.css`. Status text uses `--attention` (`--warning` is for dots and fills only), and destructive fills use `--danger-fill` with `--on-danger`, so both stay readable in light and dark. Sheets and dialogs hold focus while open: the window behind goes inert, Tab cycles inside, and focus returns to where it was on close. With several open at once, only the one drawn on top (a dialog over a sheet) and the menus opened from it take clicks, focus and Escape; the next one down takes over when it closes, and focus goes back to the first one's opener when the last closes.
- The Android app (`apps/android/`) ports the iPhone screens one to one in Compose. Where iOS uses system UI (the tab bar, menus, sheets, Liquid Glass), Android draws the same look with its `design` module: glass from Kyant's backdrop library (blur, lens refraction and highlight on RenderEffect/RuntimeShader), the iOS sheet with its grabber and drag-to-close, glass menus and context menus, Inter for SF Pro and Material Symbols for SF Symbols (`Symbol("sf.name")`), and the soft scroll edge under its bars (`ScrollEdge`: the content behind the header, composer and tab bar blurs and washes out). Android has no Liquid Glass of its own; Material widgets aren't used.
- A change to one lands in the other and the TUI in the same change; see [native client parity](#native-client-parity).
## Shared application controls
-Other custom iPhone screens use `Chrome.swift` and `Controls.swift`. The desktop equivalents are in `Overlay.tsx` (`Sheet`, `Dialog`, `AnchoredMenu`, `ModalHeader`) and `Controls.tsx` (`IconButton`, `DropdownMenu`, `ChoicePicker`, `ChipChoice`, `Switch`, `CardForm`, `CardSection`, `ValueRow`).
+Other custom iPhone screens use `Chrome.swift` and `Controls.swift`. The desktop equivalents are in `Overlay.tsx` (`Sheet`, `Dialog`, `ModalHeader`), `Menu.tsx` (`AnchoredMenu`) and `Controls.tsx` (`IconButton`, `DropdownMenu`, `ChoicePicker`, `ChipChoice`, `Switch`, `CardForm`, `CardSection`, `ValueRow`).
| Need | Component |
|---|---|
@@ -109,7 +109,7 @@ New bot and New group chat (the + menu on every client) are one short sheet each
New bots use automatically allocated personal workspaces. Settings offer Personal or an optional project folder; see [bot workspaces](../features/bot-workspaces.md).
-Desktop menus (`AnchoredMenu` in `Overlay.tsx`) scroll vertically when their content exceeds 420 points or the available space beside the trigger. Menus open toward the side with more vertical room; short lists keep their content height. Menu width is capped at 320 points and constrained to the window, and long option titles remain available through help text. This applies to Agent, Model, and other choice menus on the desktop. On iOS every menu is the system one: `DropdownMenu` and `ChoicePicker` present the native `Menu` (choices as checkmarked toggles) and `.contextActions` the native `contextMenu` (reactions as a palette row), because an overlay anchored by global frame lands in the wrong place inside `.codyncSheet`, scroll views and the composer (the + menu opened mid-screen on iPhone, 2026-09-30). Each computer has its own marketplace; its header names the computer and, with several online, switches between them. With more than one computer that can take a bot, the New bot sheet on iPhone has a Computer dropdown listing them (every computer in the current account that doesn't need an update, including computers hidden by the roster filter and offline computers). Offline choices stay selectable and are labeled; creation waits until the selected computer is online.
+Desktop menus (`AnchoredMenu` in `Menu.tsx`) scroll vertically when their content exceeds 420 points or the available space beside the trigger. Menus open toward the side with more vertical room; short lists keep their content height. Menu width is capped at 320 points and constrained to the window, and long option titles remain available through help text. This applies to Agent, Model, and other choice menus on the desktop. On iOS every menu is the system one: `DropdownMenu` and `ChoicePicker` present the native `Menu` (choices as checkmarked toggles) and `.contextActions` the native `contextMenu` (reactions as a palette row), because an overlay anchored by global frame lands in the wrong place inside `.codyncSheet`, scroll views and the composer (the + menu opened mid-screen on iPhone, 2026-09-30). Each computer has its own marketplace; its header names the computer and, with several online, switches between them. With more than one computer that can take a bot, the New bot sheet on iPhone has a Computer dropdown listing them (every computer in the current account that doesn't need an update, including computers hidden by the roster filter and offline computers). Offline choices stay selectable and are labeled; creation waits until the selected computer is online.
## Reading conversations
diff --git a/docs/features/context-and-memory.md b/docs/features/context-and-memory.md
index 9bf16bb1..2655170a 100644
--- a/docs/features/context-and-memory.md
+++ b/docs/features/context-and-memory.md
@@ -167,6 +167,13 @@ Claude Code's own memory; the rules live in the `codync-mem` crate, and `chat/me
It runs as a hidden turn: dreaming first, then the opening rendered again (a Claude session reloads only when
it changed), then `/compact <keep-list>` for Claude, or `/compact` for Codex, whose keep-list is its
`CODEX_CONFIG` `compact_prompt`. Other harnesses compact on their own. The keep-list is also in the opening.
+- **The user's threshold** (*Summarize long chats* in a Claude Code or Codex bot's settings, the bot's
+ `compaction`): Early (the default above), Near the limit, Only when full (no compaction or rollover from the
+ host), or a size in 10k steps from 50k up to the window less 40k. A size or Near the limit also keeps idle
+ compaction and the cold rollover away until the context reaches it. The bot's JSON carries `compaction`
+ (`null` for other agents, or a custom command until it turns out to run Claude's or Codex's adapter) and
+ `compactionTokens` (`{min, max, step}`, `null` until the agent has reported the window, kept in
+ `context.window.<bot>`). The rules and the table are in the [design](../design/bot-memory.md#compaction).
- **Loop guard:** after three host compactions in a day, or one that left 60% of the trigger in use, or one
fewer than five turns ago, the host rolls over instead of compacting again.
- **Rollover:** also due when a conversation over 100k went cold (its cache expired) or after eight hours away
diff --git a/docs/guides/desktop-styles.md b/docs/guides/desktop-styles.md
index 1dfaaf58..bccd9d11 100644
--- a/docs/guides/desktop-styles.md
+++ b/docs/guides/desktop-styles.md
@@ -21,7 +21,7 @@ How the desktop renderer (`apps/desktop/src/renderer/`) styles its views. Views
| Reorder by dragging | `pointerDrag` (`lib/pointer-drag.ts`), not native drag and drop: the pointer holds a closed hand, and a roster row lifts as a smaller, translucent copy that settles into its slot |
| A sheet's content | `<SheetPage>` with a `ModalHeader` (`Overlay.tsx`); `ModalHeader` takes an `icon` (an SF Symbol name on a tile, or a logo element), a title that wraps to two lines, a `subtitle` (up to two lines, the rest in its tooltip), and `onClose` when it heads a panel instead of a modal. A `Sheet` without `height` fits its content up to `maxHeight` (and the window); `FormSheet` does that unless `fixed` (content that fills the card or slides in pages that do: a terminal, an agent sheet) |
| One line with an ellipsis on an element that isn't `Text` | `.truncate` |
-| Controls | `Controls.tsx`, `Overlay.tsx`, `Icon.tsx`; `Hairline`, `Pill`, `Switch` and `ProgressBar` take a `className` for a view's own sizing, and a panel beside an anchor is placed with `anchorPlacement` |
+| Controls | `Controls.tsx`, `Overlay.tsx`, `Menu.tsx`, `Icon.tsx`; `Hairline`, `Pill`, `Switch` and `ProgressBar` take a `className` for a view's own sizing, and a panel beside an anchor is placed with `anchorPlacement` |
## Where a style goes
diff --git a/docs/reference/analytics-events.md b/docs/reference/analytics-events.md
index 7620525c..8d1e9373 100644
--- a/docs/reference/analytics-events.md
+++ b/docs/reference/analytics-events.md
@@ -75,7 +75,7 @@ host answers and sends it once the host is up.
| `screen_viewed` | host `track` (desktop, TUI), iOS, Android | A screen, sheet or tab is shown | `screen` (see *Screens*) |
| `bot_created` | host | `createBot` | `kind` (`bot`/`group`), `agent`, `model` or `members` (count) |
| `bots_imported` | host | `importBots` (bots it makes send no `bot_created`) | `source` (`grok-bot`/`openbot`/`other`), `bots`, `groups` (counts) |
-| `bot_updated` | host | `updateBot` | `fields`: the settings that changed, as the bot config's own camelCase keys (`model`, `permission`, `pinned`, `section`, `modelOptions`, `fastMode`, …), never their values |
+| `bot_updated` | host | `updateBot` | `fields`: the settings that changed, as the bot config's own camelCase keys (`model`, `permission`, `pinned`, `section`, `modelOptions`, `fastMode`, …), never their values; when the edit changes `compaction`, also `compaction`: the kind picked (`early`/`nearLimit`/`off`/`tokens`, never the size) |
| `bots_reordered` | host | `reorderBots` | — |
| `section_renamed` | host | `renameSection` | `removed`: whether it removed the section (`to` empty or `null`); never the names |
| `bot_deleted` | host | `deleteBot` | — |
@@ -85,6 +85,7 @@ host answers and sends it once the host is up.
| `turn_stopped` | host | `stop` | — |
| `turn_finished` | host | An agent's turn ends: once per agent it ran on, so a turn that fell back once and then answered sends a `failed` and a `done` | `agent`, `outcome` (`done`/`stopped`/`failed`/`needs_setup`/`incomplete`; `needs_setup` is a failure whose `error` is `sign_in` or `not_installed`: the user has a step to take, nothing broke), `stop_reason`, `source` (`user`/`routine`/`group`/`bot`/`host`: the lead opening a call), `seconds`; when failed or needs_setup, `error` (`not_installed`/`timeout`/`exited`/`no_model`/`sign_in`/`agent_error`/`io`/`other`) and, for `agent_error`, `rpc_code` and `agent_reason` (the adapter's own category, else one the host reads from the message, which is never sent: `session_ended`/`rate_limit`/`quota`/`overloaded`/`context`/`model`/`network`/`provider`/`unknown`) |
| `agent_fell_back` | host | A turn moves on to the bot's next agent ([agent fallbacks](../features/agent-fallback.md)) | `agent` (the one that couldn't answer), `reason` (`usageLimit`/`outOfCredits`/`rateLimited`/`overloaded`/`signedOut`/`notStarting`/`modelMissing`) |
+| `context_compacted` | host | Codync starts summarizing a bot's chat ([context and memory](../features/context-and-memory.md)) | `agent`, `when` (`turn_end`/`idle`), `threshold` (the bot's Summarize long chats: `early`/`nearLimit`/`tokens`) |
| `usage_read_failed` | host | Reading an agent's usage stopped, once per failing run, for the readers that start the agent's server or read a CLI's JSON report ([usage limits](../features/usage-limits.md#failures)) | `agent`, `stage` (`start`/`session`/`no_command`/`prompt`/`timeout`/`parse`: the agent's report changed format) |
| `session_reset` | host | `newSession` | — |
| `permission_answered` | host | `respondPermission` | `choice` (`allow_once`/`allow_always`/`reject_once`/`reject_always`/`other`) |
diff --git a/host/crates/memory/README.md b/host/crates/memory/README.md
index de1339ce..4f4e0ab3 100644
--- a/host/crates/memory/README.md
+++ b/host/crates/memory/README.md
@@ -101,8 +101,8 @@ cargo add [email protected] --features bundled
run also tidies it into the notes of their topics.
- `legacy`: the memory entries of codync-mem 0.1, read once to move them into files.
- `evidence`: what counts as the user's own words (not pasted, quoted or forwarded text).
-- `compaction`: when to summarize a conversation ahead of time, the loop guard, the keep-list and the handoff to
- a fresh conversation.
+- `compaction`: when to summarize a conversation ahead of time (by default or at the size the user picks), the loop
+ guard, the keep-list and the handoff to a fresh conversation.
- `tokens`: the token estimate the caps count in (one per CJK character, one per four others).
## License
diff --git a/host/crates/memory/src/compaction.rs b/host/crates/memory/src/compaction.rs
index 36cb81c2..282c572e 100644
--- a/host/crates/memory/src/compaction.rs
+++ b/host/crates/memory/src/compaction.rs
@@ -2,7 +2,12 @@
//!
//! The harness writes the summary, because it knows the work; the caller decides when, because it knows how full the
//! context is, whether the user is around and whether the prompt cache is still warm. The caller reports what it
-//! sees into a [`Conversation`] and asks [`at_turn_end`], [`while_idle`] and [`rollover_due`].
+//! sees into a [`Conversation`] and asks [`at_turn_end`], [`while_idle`] and [`rollover_due`], with the user's
+//! [`Threshold`] for it.
+
+mod threshold;
+
+pub use threshold::{Sizes, Threshold, sizes};
use serde::{Deserialize, Serialize};
@@ -10,9 +15,6 @@ const MINUTE_MS: i64 = 60_000;
const HOUR_MS: i64 = 60 * MINUTE_MS;
const DAY_MS: i64 = 24 * HOUR_MS;
-/// At the end of a turn, compact past three quarters of the window or this many tokens, whichever is less: the
-/// summary needs room, and a hot cache makes reading the history cheap.
-const TURN_END_CAP: u64 = 200_000;
/// Idle compaction and rollover only pay for themselves past this much context.
const LARGE: u64 = 100_000;
/// How long before a one-hour cache expires an idle conversation is compacted.
@@ -116,49 +118,59 @@ impl Conversation {
self.idle_compacted |= idle;
}
- fn trigger(&self) -> u64 {
- (self.size / 4 * 3).min(TURN_END_CAP)
+ /// The context use past which idle compaction and a cold rollover pay off. With a size the user chose, never short
+ /// of it: nothing summarizes the conversation or starts it over sooner.
+ fn large(&self, at: Threshold) -> Option<u64> {
+ match at {
+ Threshold::Early => Some(LARGE),
+ _ => at.trigger(self.size).map(|trigger| trigger.max(LARGE)),
+ }
}
/// Compacting again wouldn't help: too many today, too little gained last time, or too soon after the last.
- fn thrashing(&self, now: i64) -> bool {
+ fn thrashing(&self, trigger: u64, now: i64) -> bool {
let today = self.host_compactions.iter().filter(|at| now - **at < DAY_MS).count();
today >= PER_DAY
- || self.after.is_some_and(|after| after * 100 >= self.trigger() * THRASH_PERCENT)
+ || self.after.is_some_and(|after| after * 100 >= trigger * THRASH_PERCENT)
|| (self.compactions > 0 && self.turns_since < THRASH_TURNS)
}
}
/// At the end of a turn in the conversation the user returns to.
-pub fn at_turn_end(c: &Conversation, now: i64) -> Decision {
- if c.size == 0 || c.used < c.trigger() {
- Decision::Keep
- } else if c.thrashing(now) {
- Decision::Rollover
- } else {
- Decision::Compact
+pub fn at_turn_end(c: &Conversation, at: Threshold, now: i64) -> Decision {
+ match at.trigger(c.size) {
+ Some(trigger) if c.size > 0 && c.used >= trigger => {
+ if c.thrashing(trigger, now) {
+ Decision::Rollover
+ } else {
+ Decision::Compact
+ }
+ }
+ _ => Decision::Keep,
}
}
/// While nothing runs: compact a large conversation just before a one-hour cache expires, which is cheaper than
/// reading it cold when the user returns. A five-minute cache expires before this pays off.
-pub fn while_idle(c: &Conversation, life: CacheLife, now: i64) -> Decision {
+pub fn while_idle(c: &Conversation, at: Threshold, life: CacheLife, now: i64) -> Decision {
+ let (Some(trigger), Some(large)) = (at.trigger(c.size), c.large(at)) else { return Decision::Keep };
let idle = now - c.last_turn;
let due = life == CacheLife::OneHour
- && c.used >= LARGE
+ && c.used >= large
&& !c.idle_compacted
&& idle >= life.ms() - BEFORE_EXPIRY_MS
&& idle < life.ms();
- if due && !c.thrashing(now) { Decision::Compact } else { Decision::Keep }
+ if due && !c.thrashing(trigger, now) { Decision::Compact } else { Decision::Keep }
}
/// Whether the next message should start a new conversation from a handoff instead of carrying on: a large context
-/// whose cache went cold, or a long absence after several compactions.
-pub fn rollover_due(c: &Conversation, life: CacheLife, now: i64) -> bool {
+/// whose cache went cold, or a long absence after several compactions. Never when the user turned compaction off.
+pub fn rollover_due(c: &Conversation, at: Threshold, life: CacheLife, now: i64) -> bool {
+ let Some(large) = c.large(at) else { return false };
let away = now - c.last_turn;
c.last_turn > 0
&& !c.rollover_declined
- && ((away >= life.ms() && c.used >= LARGE) || (away >= AWAY_MS && c.compactions >= AWAY_COMPACTIONS))
+ && ((away >= life.ms() && c.used >= large) || (away >= AWAY_MS && c.compactions >= AWAY_COMPACTIONS))
}
/// What a summary must keep. It goes with every compaction the caller starts, and in the opening for the ones the
@@ -240,6 +252,7 @@ mod tests {
use super::*;
const NOW: i64 = 100 * DAY_MS;
+ const E: Threshold = Threshold::Early;
fn full() -> Conversation {
Conversation { used: 210_000, size: 1_000_000, last_turn: NOW, turns_since: 9, ..Conversation::default() }
@@ -247,12 +260,12 @@ mod tests {
#[test]
fn a_turn_ending_past_the_trigger_compacts() {
- assert_eq!(at_turn_end(&full(), NOW), Decision::Compact);
+ assert_eq!(at_turn_end(&full(), E, NOW), Decision::Compact);
let small = Conversation { used: 150_000, size: 200_000, ..full() };
- assert_eq!(at_turn_end(&small, NOW), Decision::Compact, "three quarters of a smaller window");
+ assert_eq!(at_turn_end(&small, E, NOW), Decision::Compact, "three quarters of a smaller window");
let room = Conversation { used: 120_000, ..full() };
- assert_eq!(at_turn_end(&room, NOW), Decision::Keep);
- assert_eq!(at_turn_end(&Conversation::default(), NOW), Decision::Keep, "no usage reported yet");
+ assert_eq!(at_turn_end(&room, E, NOW), Decision::Keep);
+ assert_eq!(at_turn_end(&Conversation::default(), E, NOW), Decision::Keep, "no usage reported yet");
}
#[test]
@@ -264,14 +277,14 @@ mod tests {
c.turn_ended(NOW);
}
c.used = 210_000;
- assert_eq!(at_turn_end(&c, NOW), Decision::Rollover, "the last one left 65% of the trigger");
+ assert_eq!(at_turn_end(&c, E, NOW), Decision::Rollover, "the last one left 65% of the trigger");
let mut c = full();
c.compacted(true, false, NOW);
c.usage(20_000, 1_000_000);
c.turn_ended(NOW);
c.used = 210_000;
- assert_eq!(at_turn_end(&c, NOW), Decision::Rollover, "two compactions within five turns");
+ assert_eq!(at_turn_end(&c, E, NOW), Decision::Rollover, "two compactions within five turns");
let mut c = full();
for hour in 0..3 {
@@ -280,40 +293,78 @@ mod tests {
c.usage(20_000, 1_000_000);
c.turns_since = 9;
c.used = 210_000;
- assert_eq!(at_turn_end(&c, NOW), Decision::Rollover, "three today");
- assert_eq!(at_turn_end(&c, NOW + DAY_MS), Decision::Compact, "a day later");
+ assert_eq!(at_turn_end(&c, E, NOW), Decision::Rollover, "three today");
+ assert_eq!(at_turn_end(&c, E, NOW + DAY_MS), Decision::Compact, "a day later");
}
#[test]
fn idle_compaction_runs_just_before_a_one_hour_cache_expires() {
let c = Conversation { used: 120_000, ..full() };
- let at = |minutes: i64| while_idle(&c, CacheLife::OneHour, NOW + minutes * MINUTE_MS);
+ let at = |minutes: i64| while_idle(&c, E, CacheLife::OneHour, NOW + minutes * MINUTE_MS);
assert_eq!(at(30), Decision::Keep);
assert_eq!(at(56), Decision::Compact);
assert_eq!(at(61), Decision::Keep, "already cold");
- assert_eq!(while_idle(&c, CacheLife::FiveMinutes, NOW + 4 * MINUTE_MS), Decision::Keep);
+ assert_eq!(while_idle(&c, E, CacheLife::FiveMinutes, NOW + 4 * MINUTE_MS), Decision::Keep);
let small = Conversation { used: 60_000, ..c.clone() };
- assert_eq!(while_idle(&small, CacheLife::OneHour, NOW + 56 * MINUTE_MS), Decision::Keep);
+ assert_eq!(while_idle(&small, E, CacheLife::OneHour, NOW + 56 * MINUTE_MS), Decision::Keep);
let mut done = c;
done.compacted(true, true, NOW + 56 * MINUTE_MS);
- assert_eq!(while_idle(&done, CacheLife::OneHour, NOW + 57 * MINUTE_MS), Decision::Keep, "once");
+ assert_eq!(while_idle(&done, E, CacheLife::OneHour, NOW + 57 * MINUTE_MS), Decision::Keep, "once");
}
#[test]
fn a_cold_large_or_long_away_conversation_rolls_over() {
let c = Conversation { used: 120_000, ..full() };
- assert!(!rollover_due(&c, CacheLife::OneHour, NOW + 30 * MINUTE_MS));
- assert!(rollover_due(&c, CacheLife::OneHour, NOW + 61 * MINUTE_MS));
- assert!(rollover_due(&c, CacheLife::FiveMinutes, NOW + 6 * MINUTE_MS));
+ assert!(!rollover_due(&c, E, CacheLife::OneHour, NOW + 30 * MINUTE_MS));
+ assert!(rollover_due(&c, E, CacheLife::OneHour, NOW + 61 * MINUTE_MS));
+ assert!(rollover_due(&c, E, CacheLife::FiveMinutes, NOW + 6 * MINUTE_MS));
let small = Conversation { used: 30_000, ..full() };
- assert!(!rollover_due(&small, CacheLife::FiveMinutes, NOW + 6 * HOUR_MS));
+ assert!(!rollover_due(&small, E, CacheLife::FiveMinutes, NOW + 6 * HOUR_MS));
let summarized = Conversation { compactions: 3, ..small };
- assert!(rollover_due(&summarized, CacheLife::FiveMinutes, NOW + 9 * HOUR_MS));
- assert!(!rollover_due(&Conversation::default(), CacheLife::OneHour, NOW), "never used");
+ assert!(rollover_due(&summarized, E, CacheLife::FiveMinutes, NOW + 9 * HOUR_MS));
+ assert!(!rollover_due(&Conversation::default(), E, CacheLife::OneHour, NOW), "never used");
let mut kept = Conversation { rollover_declined: true, ..c.clone() };
- assert!(!rollover_due(&kept, CacheLife::OneHour, NOW + 61 * MINUTE_MS), "the user carried on");
+ assert!(!rollover_due(&kept, E, CacheLife::OneHour, NOW + 61 * MINUTE_MS), "the user carried on");
kept.turn_ended(NOW + 62 * MINUTE_MS);
- assert!(rollover_due(&kept, CacheLife::OneHour, NOW + 130 * MINUTE_MS), "until the next quiet spell");
+ assert!(rollover_due(&kept, E, CacheLife::OneHour, NOW + 130 * MINUTE_MS), "until the next quiet spell");
+ }
+
+ #[test]
+ fn the_users_threshold_moves_the_trigger_within_the_window() {
+ let at = |used: u64, size: u64, threshold: Threshold| {
+ at_turn_end(&Conversation { used, size, ..full() }, threshold, NOW)
+ };
+ assert_eq!(at(500_000, 1_000_000, Threshold::Tokens(600_000)), Decision::Keep);
+ assert_eq!(at(600_000, 1_000_000, Threshold::Tokens(600_000)), Decision::Compact);
+ assert_eq!(at(950_000, 1_000_000, Threshold::NearLimit), Decision::Keep, "960k is the most a 1M window allows");
+ assert_eq!(at(960_000, 1_000_000, Threshold::NearLimit), Decision::Compact);
+ assert_eq!(at(160_000, 200_000, Threshold::Tokens(900_000)), Decision::Compact, "held to the smaller window");
+ assert_eq!(at(50_000, 1_000_000, Threshold::Tokens(10_000)), Decision::Compact, "never below the minimum");
+ assert_eq!(at(40_000, 1_000_000, Threshold::Tokens(10_000)), Decision::Keep);
+ assert_eq!(at(990_000, 1_000_000, Threshold::Off), Decision::Keep, "left to the harness");
+ assert_eq!(at(60_000, 64_000, Threshold::NearLimit), Decision::Compact, "too small a window: the default's");
+ }
+
+ #[test]
+ fn a_size_of_the_users_own_keeps_idle_compaction_and_cold_rollovers_away_until_it() {
+ let c = Conversation { used: 300_000, ..full() };
+ let idle = NOW + 56 * MINUTE_MS;
+ let cold = NOW + 61 * MINUTE_MS;
+ assert_eq!(while_idle(&c, E, CacheLife::OneHour, idle), Decision::Compact);
+ assert!(rollover_due(&c, E, CacheLife::OneHour, cold));
+ for threshold in [Threshold::Tokens(500_000), Threshold::NearLimit, Threshold::Off] {
+ assert_eq!(while_idle(&c, threshold, CacheLife::OneHour, idle), Decision::Keep, "{threshold:?}");
+ assert!(!rollover_due(&c, threshold, CacheLife::OneHour, cold), "{threshold:?}");
+ }
+ let low = Threshold::Tokens(60_000);
+ assert_eq!(while_idle(&c, low, CacheLife::OneHour, idle), Decision::Compact, "past 100k, as by default");
+ let summarized = Conversation { used: 30_000, compactions: 3, ..full() };
+ let away = NOW + 9 * HOUR_MS;
+ assert!(
+ rollover_due(&summarized, Threshold::NearLimit, CacheLife::FiveMinutes, away),
+ "summaries of summaries"
+ );
+ assert!(!rollover_due(&summarized, Threshold::Off, CacheLife::FiveMinutes, away));
}
#[test]
diff --git a/host/crates/memory/src/compaction/threshold.rs b/host/crates/memory/src/compaction/threshold.rs
new file mode 100644
index 00000000..40d5fa7b
--- /dev/null
+++ b/host/crates/memory/src/compaction/threshold.rs
@@ -0,0 +1,164 @@
+//! The user's choice of when a conversation is compacted, its wire form, and the sizes a window allows.
+
+use serde::{Deserialize, Serialize};
+
+/// By default, compact past three quarters of the window or this many tokens, whichever is less: the summary needs
+/// room, and a hot cache makes reading the history cheap.
+const TURN_END_CAP: u64 = 200_000;
+/// A size the user sets is a multiple of this...
+const STEP: u64 = 10_000;
+/// ...at least this: the summary and the opening alone take some 20k, so less would compact every few turns...
+const MIN_TOKENS: u64 = 50_000;
+/// ...and leaves this much of the window to the compaction turn: its prompt and a summary of about 20k.
+const HEADROOM: u64 = 40_000;
+
+/// When the caller compacts a conversation: the user's choice. On the wire `"early"`, `"nearLimit"`, `"off"`, or the
+/// size in tokens; anything else reads as the default.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(from = "Wire", into = "Wire")]
+pub enum Threshold {
+ /// At three quarters of the window or 200k, whichever is less; idle compaction and rollovers past 100k.
+ #[default]
+ Early,
+ /// At the largest size the window allows ([`sizes`]), never sooner than [`Threshold::Early`].
+ NearLimit,
+ /// Never: the harness's own compaction, when a turn fills the window, is all there is.
+ Off,
+ /// At this many tokens, held to the [`sizes`] the window allows.
+ Tokens(u64),
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(untagged)]
+enum Wire {
+ Tokens(u64),
+ Name(Name),
+ /// A value from a newer caller.
+ #[serde(skip_serializing)]
+ Other(serde::de::IgnoredAny),
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+enum Name {
+ Early,
+ NearLimit,
+ Off,
+}
+
+impl From<Wire> for Threshold {
+ fn from(wire: Wire) -> Self {
+ match wire {
+ Wire::Tokens(n) => Self::Tokens(n),
+ Wire::Name(Name::Early) | Wire::Other(_) => Self::Early,
+ Wire::Name(Name::NearLimit) => Self::NearLimit,
+ Wire::Name(Name::Off) => Self::Off,
+ }
+ }
+}
+
+impl From<Threshold> for Wire {
+ fn from(threshold: Threshold) -> Self {
+ match threshold {
+ Threshold::Early => Self::Name(Name::Early),
+ Threshold::NearLimit => Self::Name(Name::NearLimit),
+ Threshold::Off => Self::Name(Name::Off),
+ Threshold::Tokens(n) => Self::Tokens(n),
+ }
+ }
+}
+
+impl Threshold {
+ /// Its name without the size, for analytics.
+ pub fn kind(self) -> &'static str {
+ match self {
+ Self::Early => "early",
+ Self::NearLimit => "nearLimit",
+ Self::Off => "off",
+ Self::Tokens(_) => "tokens",
+ }
+ }
+
+ /// Whether the user may set it: a size is a multiple of 10k, at least 50k. Its upper bound is the window's, which
+ /// it is held to as the conversation runs, since the window can change with the model.
+ pub fn check(self) -> Result<(), String> {
+ match self {
+ Self::Tokens(n) if n < MIN_TOKENS || n % STEP != 0 => {
+ Err(format!("compaction size must be a multiple of {STEP} tokens, at least {MIN_TOKENS}"))
+ }
+ _ => Ok(()),
+ }
+ }
+
+ /// The context use that compacts a conversation in a window of `window` tokens at the end of a turn; `None` when
+ /// the user turned that off. A window too small for a size gets the default's.
+ pub(super) fn trigger(self, window: u64) -> Option<u64> {
+ let early = (window / 4 * 3).min(TURN_END_CAP);
+ let max = max_tokens(window);
+ match self {
+ Self::Early => Some(early),
+ Self::NearLimit => Some(max.map_or(early, |max| max.max(early))),
+ Self::Off => None,
+ Self::Tokens(n) => Some(max.map_or(early, |max| n.clamp(MIN_TOKENS, max))),
+ }
+ }
+}
+
+/// The sizes a user may set in one window: `min` to `max` tokens by `step`.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
+pub struct Sizes {
+ pub min: u64,
+ pub max: u64,
+ pub step: u64,
+}
+
+/// The sizes a window of `window` tokens allows; `None` for a window too small to offer one.
+pub fn sizes(window: u64) -> Option<Sizes> {
+ max_tokens(window).map(|max| Sizes { min: MIN_TOKENS, max, step: STEP })
+}
+
+/// The largest size a window allows, leaving the compaction turn its headroom.
+fn max_tokens(window: u64) -> Option<u64> {
+ let max = window.saturating_sub(HEADROOM) / STEP * STEP;
+ (max >= MIN_TOKENS).then_some(max)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn a_threshold_reads_back_as_written() {
+ for (threshold, wire) in [
+ (Threshold::Early, json!("early")),
+ (Threshold::NearLimit, json!("nearLimit")),
+ (Threshold::Off, json!("off")),
+ (Threshold::Tokens(120_000), json!(120_000)),
+ ] {
+ assert_eq!(serde_json::to_value(threshold).unwrap(), wire);
+ assert_eq!(serde_json::from_value::<Threshold>(wire).unwrap(), threshold);
+ }
+ assert_eq!(serde_json::from_value::<Threshold>(json!("later")).unwrap(), Threshold::Early, "a newer app's");
+ }
+
+ #[test]
+ fn a_window_offers_sizes_in_steps_short_of_its_headroom() {
+ assert_eq!(sizes(1_000_000), Some(Sizes { min: 50_000, max: 960_000, step: 10_000 }));
+ assert_eq!(sizes(272_000).map(|s| s.max), Some(230_000));
+ assert_eq!(sizes(64_000), None);
+ for ok in [Threshold::NearLimit, Threshold::Tokens(50_000), Threshold::Tokens(2_000_000)] {
+ assert!(ok.check().is_ok(), "{ok:?}");
+ }
+ for bad in [40_000, 125_000] {
+ assert!(Threshold::Tokens(bad).check().is_err(), "{bad}");
+ }
+ }
+
+ #[test]
+ fn near_the_limit_is_never_sooner_than_early() {
+ assert_eq!(Threshold::NearLimit.trigger(1_000_000), Some(960_000));
+ assert_eq!(Threshold::NearLimit.trigger(128_000), Some(96_000), "a small window: three quarters of it");
+ assert_eq!(Threshold::NearLimit.trigger(64_000), Some(48_000), "too small for a size: the default's");
+ }
+}
diff --git a/host/src/agent/bot/compaction.rs b/host/src/agent/bot/compaction.rs
index 2fde1467..04e7a3b5 100644
--- a/host/src/agent/bot/compaction.rs
+++ b/host/src/agent/bot/compaction.rs
@@ -4,13 +4,49 @@
use super::{Actor, Adapter, Done, Instructions, Queued};
use crate::chat::{context, handoff, memory};
-use crate::store::{EntryKind, Lane, now_ms};
-use codync_mem::compaction::{self as rules, CacheLife, Conversation, Decision};
+use crate::store::{BotConfig, EntryKind, Lane, Store, now_ms};
+use codync_mem::compaction::{self as rules, CacheLife, Conversation, Decision, Threshold};
use serde_json::{Value, json};
/// Context use below which a fall isn't read as a compaction: a short session has little to summarize.
const COMPACTED_FROM: u64 = 20_000;
+/// Whether Codync summarizes the bot's chat ahead of time, so the apps offer the user a [`Threshold`] for it: its
+/// agent is Claude Code or Codex, or a custom command turned out to run one of their adapters.
+pub fn offers_threshold(store: &Store, cfg: &BotConfig) -> bool {
+ !cfg.is_group()
+ && match harness_adapter(&cfg.backend) {
+ Adapter::Other => cfg.backend == "custom" && context_window(store, &cfg.id).is_some(),
+ _ => true,
+ }
+}
+
+/// The adapter a backend runs, before its agent has answered.
+fn harness_adapter(backend: &str) -> Adapter {
+ match backend {
+ "claude" => Adapter::Claude,
+ "codex" => Adapter::Codex,
+ _ => Adapter::Other,
+ }
+}
+
+/// The user's threshold where Codync compacts the bot's chat: by the adapter running it, or with none running (a
+/// custom command released or not started yet) by what its agent last reported. Elsewhere rollovers follow the
+/// default's.
+fn threshold(store: &Store, cfg: &BotConfig, running: Option<Adapter>) -> Threshold {
+ let compacts = running.map_or_else(|| offers_threshold(store, cfg), |adapter| adapter != Adapter::Other);
+ if compacts { cfg.compaction } else { Threshold::default() }
+}
+
+fn window_key(bot: &str) -> String {
+ format!("context.window.{bot}")
+}
+
+/// The context window of the bot's own chat, as its agent last reported it; kept only for an agent Codync compacts.
+pub fn context_window(store: &Store, bot: &str) -> Option<u64> {
+ store.kv_get(&window_key(bot)).and_then(|v| v.parse().ok())
+}
+
impl Actor {
fn conversation_key(&self, session: &str) -> String {
format!("compaction.{}.{session}", self.cfg.id)
@@ -48,8 +84,7 @@ impl Actor {
.iter()
.any(|(k, _)| k == "ANTHROPIC_API_KEY")
|| std::env::var_os("ANTHROPIC_API_KEY").is_some();
- let claude = self.conn.as_ref().is_some_and(|c| c.adapter == Adapter::Claude) || self.cfg.backend == "claude";
- if claude && !api_key { CacheLife::OneHour } else { CacheLife::FiveMinutes }
+ if self.adapter() == Adapter::Claude && !api_key { CacheLife::OneHour } else { CacheLife::FiveMinutes }
}
/// The bot's own chat, not a room, a routine or another bot's request: the conversation the user comes
@@ -63,24 +98,50 @@ impl Actor {
&& self.turn_session == self.session_id
}
- /// The command that makes the agent compact, with the keep-list where it takes one. Before the agent runs, its
- /// harness stands in for the adapter.
+ /// The adapter the bot's agent runs; before it runs, its harness's.
+ fn adapter(&self) -> Adapter {
+ self.conn.as_ref().map_or_else(|| harness_adapter(&self.cfg.backend), |c| c.adapter)
+ }
+
+ /// The command that makes the agent compact, with the keep-list where it takes one.
fn compact_command(&self) -> Option<String> {
- let adapter = self.conn.as_ref().map_or(
- match self.cfg.backend.as_str() {
- "claude" => Adapter::Claude,
- "codex" => Adapter::Codex,
- _ => Adapter::Other,
- },
- |c| c.adapter,
- );
- match adapter {
+ match self.adapter() {
Adapter::Claude => Some(format!("/compact {}", rules::KEEP)),
Adapter::Codex => Some("/compact".into()),
Adapter::Other => None,
}
}
+ fn threshold(&self) -> Threshold {
+ threshold(&self.hub.store, &self.cfg, self.conn.as_ref().map(|c| c.adapter))
+ }
+
+ /// Keeps the main chat's window for the apps, which offer sizes up to what it holds; none for an agent Codync
+ /// doesn't compact. Only the bot's own agent tells it: the sizes are for that agent's window, not a fallback's.
+ fn note_window(&self, size: u64) {
+ if self.cfg.backend != self.base.backend {
+ return;
+ }
+ let window = match (self.adapter(), size) {
+ (Adapter::Other, _) => None,
+ (_, 0) => return,
+ (_, size) => Some(size),
+ };
+ if context_window(&self.hub.store, &self.cfg.id) == window {
+ return;
+ }
+ let key = window_key(&self.cfg.id);
+ let saved = match window {
+ Some(size) => self.hub.store.kv_set(&key, &size.to_string()),
+ None => self.hub.store.kv_delete(&key),
+ };
+ if let Err(error) = saved {
+ tracing::warn!(bot = %self.cfg.id, error = format!("{error:#}"), "couldn't record the window");
+ return;
+ }
+ self.hub.emit_bot(&self.cfg.id);
+ }
+
/// The agent reported its context use.
pub(super) fn track_usage(&mut self, used: u64, size: u64) {
let Some(sid) = self.turn_session.clone() else { return };
@@ -169,6 +230,7 @@ impl Actor {
let mut c = self.conversation(&sid);
if let Some(&(used, size)) = self.conn.as_ref().and_then(|conn| conn.usage.get(&sid)) {
c.usage(used, size);
+ self.note_window(size);
}
// The compaction turn itself is no turn of the conversation: it neither counts nor resets the idle clock.
if compacting.is_some() {
@@ -183,7 +245,7 @@ impl Actor {
}
c.turn_ended(now);
self.save_conversation(&sid, &c);
- match rules::at_turn_end(&c, now) {
+ match rules::at_turn_end(&c, self.threshold(), now) {
Decision::Compact if self.compact_command().is_some() => {
self.queue.push_back(Queued::Compact { idle: false });
}
@@ -202,9 +264,10 @@ impl Actor {
}
let now = now_ms();
let life = self.cache_life();
- if rules::while_idle(&c, life, now) == Decision::Compact && self.compact_command().is_some() {
+ let at = self.threshold();
+ if rules::while_idle(&c, at, life, now) == Decision::Compact && self.compact_command().is_some() {
self.queue.push_back(Queued::Compact { idle: true });
- } else if rules::rollover_due(&c, life, now) && handoff::pending(&self.hub.store, &self.cfg.id).is_none() {
+ } else if rules::rollover_due(&c, at, life, now) && handoff::pending(&self.hub.store, &self.cfg.id).is_none() {
let reason = if now - c.last_turn >= life.ms() { handoff::Reason::Cold } else { handoff::Reason::Away };
self.draft_handoff(&sid, reason);
}
@@ -233,6 +296,7 @@ impl Actor {
/// opening is rendered again, so the compaction keeps current memory (render, load, compact).
pub(super) async fn start_compaction(&mut self, idle: bool, done_tx: &tokio::sync::mpsc::UnboundedSender<Done>) {
let (Some(sid), Some(command)) = (self.session_id.clone(), self.compact_command()) else { return };
+ crate::analytics::context_compacted(&self.hub, &self.cfg.backend, idle, self.threshold());
let _ = self.dreamer.send(memory::DreamEvent::Flush);
if let Err(error) = context::refresh(&self.hub.store, &self.cfg.id, &sid) {
tracing::warn!(bot = %self.cfg.id, error = format!("{error:#}"), "couldn't refresh the opening");
@@ -254,7 +318,7 @@ impl Actor {
{
let c = self.settle_kept(&sid);
let life = self.cache_life();
- if rules::rollover_due(&c, life, now_ms()) {
+ if rules::rollover_due(&c, self.threshold(), life, now_ms()) {
let reason =
if now_ms() - c.last_turn >= life.ms() { handoff::Reason::Cold } else { handoff::Reason::Away };
self.draft_handoff(&sid, reason);
@@ -292,6 +356,22 @@ mod tests {
assert!(!compacted_by_usage(None, 1_000), "the session's first report");
}
+ #[test]
+ fn a_custom_command_keeps_its_threshold_while_no_agent_runs() {
+ let path = std::env::temp_dir().join(format!("codync-threshold-{}.db", uuid::Uuid::new_v4()));
+ let store = Store::open(&path).unwrap();
+ let cfg: BotConfig =
+ serde_json::from_value(json!({"id": "b", "name": "B", "backend": "custom", "compaction": "off"})).unwrap();
+ assert_eq!(threshold(&store, &cfg, None), Threshold::Early, "not known to run Claude's or Codex's adapter yet");
+ store.kv_set(&window_key("b"), "1000000").unwrap();
+ assert_eq!(threshold(&store, &cfg, None), Threshold::Off, "released after it reported its window");
+ assert_eq!(threshold(&store, &cfg, Some(Adapter::Claude)), Threshold::Off);
+ assert_eq!(threshold(&store, &cfg, Some(Adapter::Other)), Threshold::Early, "now running another adapter");
+ let cold = Conversation { used: 150_000, size: 1_000_000, last_turn: 1, ..Conversation::default() };
+ assert!(!rules::rollover_due(&cold, threshold(&store, &cfg, None), CacheLife::FiveMinutes, 2 * 3_600_000));
+ std::fs::remove_file(&path).ok();
+ }
+
#[test]
fn a_turn_after_a_pause_tells_the_cache_life() {
let warm = json!({"usage": {"inputTokens": 2, "cachedReadTokens": 40_000, "cachedWriteTokens": 300}});
diff --git a/host/src/agent/bot/mod.rs b/host/src/agent/bot/mod.rs
index 35d1962f..930595bd 100644
--- a/host/src/agent/bot/mod.rs
+++ b/host/src/agent/bot/mod.rs
@@ -36,6 +36,7 @@ mod updates;
pub use cmd::Cmd;
use cmd::Queued;
+pub use compaction::{context_window, offers_threshold};
pub(crate) use launch::{launch_commands, select_model, start_agent, system_prompt};
use crate::agent::acp::{self, Acp, Incoming};
diff --git a/host/src/analytics.rs b/host/src/analytics.rs
index 40e3bb19..ad0e46d4 100644
--- a/host/src/analytics.rs
+++ b/host/src/analytics.rs
@@ -27,7 +27,7 @@ pub use lifecycle::{
};
pub use observe::{answered, failed, observe_call};
pub use reported::track;
-pub use turns::{Steer, TurnOutcome, TurnSource, agent_fell_back, message_steered, turn_finished};
+pub use turns::{Steer, TurnOutcome, TurnSource, agent_fell_back, context_compacted, message_steered, turn_finished};
const KV_ENABLED: &str = "analytics_enabled";
/// The account the install id was merged into. An id merges into one account and a second is
@@ -75,6 +75,8 @@ pub enum Event {
TurnFinished,
/// A turn moved on to the bot's next agent (`agent::fallback`).
AgentFellBack,
+ /// Codync started summarizing a bot's chat (`agent::bot::compaction`).
+ ContextCompacted,
UsageReadFailed,
SessionReset,
PermissionAnswered,
@@ -165,6 +167,7 @@ impl Event {
Self::TurnStopped => "turn_stopped",
Self::TurnFinished => "turn_finished",
Self::AgentFellBack => "agent_fell_back",
+ Self::ContextCompacted => "context_compacted",
Self::UsageReadFailed => "usage_read_failed",
Self::SessionReset => "session_reset",
Self::PermissionAnswered => "permission_answered",
diff --git a/host/src/analytics/observe.rs b/host/src/analytics/observe.rs
index 89b3cc43..6c71368e 100644
--- a/host/src/analytics/observe.rs
+++ b/host/src/analytics/observe.rs
@@ -5,6 +5,8 @@ use super::{Event, platform_of};
use crate::api::devices::Caller;
use crate::hub::Hub;
use crate::store::BotConfig;
+use codync_mem::compaction::Threshold;
+use serde::Deserialize;
use serde_json::{Map, Value};
/// Methods that stand for one event with one fixed property.
@@ -207,7 +209,13 @@ pub fn observe_call(hub: &Hub, caller: &Caller, method: &str, b: &Value) -> Opti
}
Event::BotUpdated => {
if let Ok(Some(row)) = hub.store.bot(b["id"].as_str().unwrap_or_default()) {
- p.insert("fields".into(), changed_fields(&row.config, b).into());
+ let fields = changed_fields(&row.config, b);
+ // Which kind of threshold the user picked, never its size.
+ if fields.iter().any(|f| f == "compaction") {
+ let picked = Threshold::deserialize(&b["compaction"]).unwrap_or_default();
+ p.insert("compaction".into(), picked.kind().into());
+ }
+ p.insert("fields".into(), fields.into());
}
}
Event::PermissionAnswered => {
diff --git a/host/src/analytics/observe/tests.rs b/host/src/analytics/observe/tests.rs
index f728cec5..802a3c08 100644
--- a/host/src/analytics/observe/tests.rs
+++ b/host/src/analytics/observe/tests.rs
@@ -262,6 +262,15 @@ async fn store_lookups_add_fields_choice_and_platform() {
hub.store.save_bot(&cfg).unwrap();
let (_, p) = observe_call(&hub, &Caller::Local, "updateBot", &json!({"id": "b1", "permission": "auto"})).unwrap();
assert_eq!(p["fields"], json!(["permission"]));
+ assert!(p.get("compaction").is_none());
+ let (_, p) = observe_call(&hub, &Caller::Local, "updateBot", &json!({"id": "b1", "compaction": 120_000})).unwrap();
+ assert_eq!((&p["fields"], &p["compaction"]), (&json!(["compaction"]), &json!("tokens")), "the kind, not the size");
+ // The apps send the whole form: an unchanged threshold in it isn't a pick.
+ let (_, p) =
+ observe_call(&hub, &Caller::Local, "updateBot", &json!({"id": "b1", "name": "c", "compaction": "early"}))
+ .unwrap();
+ assert_eq!(p["fields"], json!(["name"]));
+ assert!(p.get("compaction").is_none());
let card = json!({"status": "pending", "options": [{"optionId": "o1", "name": "Allow", "kind": "allow_always"}]});
let e =
diff --git a/host/src/analytics/turns.rs b/host/src/analytics/turns.rs
index c442812b..b9d5fb7e 100644
--- a/host/src/analytics/turns.rs
+++ b/host/src/analytics/turns.rs
@@ -85,6 +85,14 @@ pub fn agent_fell_back(hub: &Hub, agent: &str, reason: crate::agent::fallback::R
capture(hub, Event::AgentFellBack, p.as_object().cloned().unwrap_or_default());
}
+/// `context_compacted`: Codync started summarizing a bot's chat, at the end of a turn or while it rested, and at
+/// which of the user's thresholds.
+pub fn context_compacted(hub: &Hub, agent: &str, idle: bool, threshold: codync_mem::compaction::Threshold) {
+ let when = if idle { "idle" } else { "turn_end" };
+ let p = json!({"agent": agent, "when": when, "threshold": threshold.kind()});
+ capture(hub, Event::ContextCompacted, p.as_object().cloned().unwrap_or_default());
+}
+
/// What became of a queued message the user had handled now (`message_steered`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
diff --git a/host/src/chat/calls/context.rs b/host/src/chat/calls/context.rs
index ec1ccacc..6fe6360e 100644
--- a/host/src/chat/calls/context.rs
+++ b/host/src/chat/calls/context.rs
@@ -387,6 +387,7 @@ pub(super) mod tests {
created_by: None,
shared_memory: Some(true),
harness_memory: false,
+ compaction: codync_mem::compaction::Threshold::Early,
auto_name: false,
lead: false,
created_at: 0,
diff --git a/host/src/hub/sync.rs b/host/src/hub/sync.rs
index f341e021..7323eab0 100644
--- a/host/src/hub/sync.rs
+++ b/host/src/hub/sync.rs
@@ -14,6 +14,11 @@ impl Hub {
// Null where there is no switch to show.
v["harnessMemory"] =
(!cfg.is_group() && crate::agent::own_memory::switchable(cfg)).then_some(cfg.harness_memory).into();
+ // Null where Codync doesn't summarize the chat. The sizes it may take: none until the agent tells its window.
+ let compacts = crate::agent::bot::offers_threshold(&self.store, cfg);
+ v["compaction"] = if compacts { v["compaction"].take() } else { Value::Null };
+ let window = compacts.then(|| crate::agent::bot::context_window(&self.store, &cfg.id)).flatten();
+ v["compactionTokens"] = json!(window.and_then(codync_mem::compaction::sizes));
if !cfg.is_group() {
v["harnessMemoryShared"] = crate::agent::own_memory::shared(cfg).into();
v["sharedMemory"] = crate::chat::memory::shared(cfg).into();
@@ -59,3 +64,36 @@ impl Hub {
Ok(self.store.bots()?.iter().filter(|b| b.rev > since).map(|b| self.bot_json(b)).collect())
}
}
+
+#[cfg(test)]
+mod tests {
+ use crate::hub::Hub;
+ use crate::remote::identity::Identity;
+ use crate::store::Store;
+ use serde_json::json;
+
+ #[test]
+ fn a_bot_offers_compaction_sizes_once_its_agent_tells_the_window() {
+ let dir = std::env::temp_dir().join(format!("codync-compaction-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let store = Store::open(&dir.join("t.db")).unwrap();
+ for (id, backend) in [("c", "claude"), ("g", "gemini")] {
+ let bot = json!({"id": id, "name": id, "backend": backend, "cwd": "/tmp", "compaction": 300_000});
+ store.save_bot(&serde_json::from_value(bot).unwrap()).unwrap();
+ }
+ let hub = Hub::new(store, "test".into(), Identity::load_or_create(&dir).unwrap(), "token".into(), 0);
+
+ let claude = hub.bot_value_for_test("c");
+ assert_eq!(claude["compaction"], 300_000);
+ assert!(claude["compactionTokens"].is_null(), "no window reported yet");
+ hub.store.kv_set("context.window.c", "1000000").unwrap();
+ assert_eq!(
+ hub.bot_value_for_test("c")["compactionTokens"],
+ json!({"min": 50_000, "max": 960_000, "step": 10_000})
+ );
+
+ let gemini = hub.bot_value_for_test("g");
+ assert!(gemini["compaction"].is_null() && gemini["compactionTokens"].is_null(), "Codync can't compact it");
+ std::fs::remove_dir_all(&dir).ok();
+ }
+}
diff --git a/host/src/hub/validate.rs b/host/src/hub/validate.rs
index 44036649..9be9abcf 100644
--- a/host/src/hub/validate.rs
+++ b/host/src/hub/validate.rs
@@ -26,5 +26,6 @@ pub(crate) fn validate(cfg: &BotConfig) -> Result<()> {
if cfg.mode.as_deref().is_some_and(|m| m.trim().is_empty() || m.len() > 64) {
bail!("mode must be one of the agent's mode ids, or null for its default");
}
+ cfg.compaction.check().map_err(anyhow::Error::msg)?;
crate::agent::fallback::check(cfg)
}
diff --git a/host/src/store/bots.rs b/host/src/store/bots.rs
index 0d2a7690..72cb9fda 100644
--- a/host/src/store/bots.rs
+++ b/host/src/store/bots.rs
@@ -90,6 +90,17 @@ impl Store {
"DELETE FROM kv WHERE k GLOB ?1 OR k GLOB ?2",
[format!("context.{id}.*"), format!("context.epoch.{id}.*")],
)?;
+ // Its conversations as compaction tracks them, their summaries, its window and cache life
+ // (`agent::bot::compaction`).
+ c.execute(
+ "DELETE FROM kv WHERE k GLOB ?1 OR k GLOB ?2 OR k = ?3 OR k = ?4",
+ [
+ format!("compaction.{id}.*"),
+ format!("compaction.summary.{id}.*"),
+ format!("context.window.{id}"),
+ format!("cache.life.{id}"),
+ ],
+ )?;
// Its artifacts' details (`chat::artifacts`).
c.execute("DELETE FROM kv WHERE k GLOB ?1", [format!("artifact.{id}.*")])?;
Ok(rev)
@@ -197,6 +208,7 @@ mod tests {
created_by: None,
shared_memory: None,
harness_memory: false,
+ compaction: codync_mem::compaction::Threshold::Early,
auto_name: false,
created_at: 0,
};
@@ -235,8 +247,15 @@ mod tests {
s.kv_set("fallback.session.b1.codex", "s1").unwrap();
s.kv_set("fallback.on.b1", "codex").unwrap();
s.kv_set("fallback.on.b10", "codex").unwrap();
+ let compaction = ["compaction.b1.s1", "compaction.summary.b1.s1", "context.window.b1", "cache.life.b1"];
+ for k in compaction {
+ s.kv_set(k, "1").unwrap();
+ }
+ s.kv_set("context.window.b10", "1").unwrap();
s.delete_bot("b1").unwrap();
assert_eq!((s.kv_get("fallback.session.b1.codex"), s.kv_get("fallback.on.b1")), (None, None));
+ assert!(compaction.iter().all(|k| s.kv_get(k).is_none()), "its compaction records");
+ assert!(s.kv_get("context.window.b10").is_some(), "another bot's window");
assert!(s.kv_get("fallback.on.b10").is_some(), "another bot's");
assert!(s.insert_entry(&Lane::main("b1"), EntryKind::Notice, 3, &reply).is_err());
s.save_bot(&cfg).unwrap();
diff --git a/host/src/store/model.rs b/host/src/store/model.rs
index e71722f4..4dc23c7c 100644
--- a/host/src/store/model.rs
+++ b/host/src/store/model.rs
@@ -146,6 +146,10 @@ pub struct BotConfig {
/// it got it sends `null` where there is no switch.
#[serde(default, deserialize_with = "null_as_false")]
pub harness_memory: bool,
+ /// When Codync summarizes the bot's chat ahead of time (see `agent::bot::compaction`); only for an agent it can
+ /// ask to, and the apps show it only there. `null` and values from a newer app read as the default.
+ #[serde(default)]
+ pub compaction: codync_mem::compaction::Threshold,
/// Created without a name: the host names it from its first conversations (see `naming`)
/// until the user renames it.
#[serde(default)]
diff --git a/host/src/tui/app/bot.rs b/host/src/tui/app/bot.rs
index 5c5182a1..02694fed 100644
--- a/host/src/tui/app/bot.rs
+++ b/host/src/tui/app/bot.rs
@@ -60,6 +60,10 @@ pub struct Bot {
pub created_at: i64,
/// The harness's own memory beside Codync's; `None` where the screen says nothing about it.
pub harness_memory: Option<OwnMemory>,
+ /// When Codync summarizes its chat; `None` where it doesn't.
+ pub compaction: Option<codync_mem::compaction::Threshold>,
+ /// The sizes it may take, smallest first; none until the agent has told its window.
+ pub compaction_sizes: Vec<u64>,
/// Agents that carry on, in order, when its own can't answer (`agent::fallback`).
pub fallbacks: Vec<crate::store::Fallback>,
/// The bot may set its own fallbacks.
@@ -97,6 +101,17 @@ fn strs(v: &Value) -> Vec<String> {
v.as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect()
}
+/// `compactionTokens` (`{min, max, step}`) as the sizes it offers.
+fn sizes(v: &Value) -> Vec<u64> {
+ let (Some(min), Some(max), Some(step)) = (v["min"].as_u64(), v["max"].as_u64(), v["step"].as_u64()) else {
+ return vec![];
+ };
+ if step == 0 {
+ return vec![];
+ }
+ (min..=max).step_by(usize::try_from(step).unwrap_or(usize::MAX)).collect()
+}
+
/// A model an agent offers (`agentModels`), with its own settings.
pub struct AgentModel {
pub id: String,
@@ -204,6 +219,8 @@ impl Bot {
.as_bool()
.map(OwnMemory::Switch)
.or_else(|| (v["harnessMemoryShared"] == true).then_some(OwnMemory::Shared)),
+ compaction: serde_json::from_value(v["compaction"].clone()).ok().flatten(),
+ compaction_sizes: sizes(&v["compactionTokens"]),
fallbacks: serde_json::from_value(v["fallbacks"].clone()).unwrap_or_default(),
self_fallbacks: v["selfFallbacks"].as_bool().unwrap_or(true),
agent_step: v["agentStep"]["agent"].as_str().map(str::to_owned),
diff --git a/host/src/tui/app/forms.rs b/host/src/tui/app/forms.rs
index 976bba71..06ec72cc 100644
--- a/host/src/tui/app/forms.rs
+++ b/host/src/tui/app/forms.rs
@@ -1,5 +1,6 @@
//! The bot settings form.
+use codync_mem::compaction::Threshold;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde_json::{Value, json};
use std::collections::BTreeMap;
@@ -51,6 +52,8 @@ impl App {
manage_team: b.manage_team,
offered_to_network: b.offered_to_network,
reachable_by_assistants: b.reachable_by_assistants,
+ compaction: b.compaction,
+ compaction_sizes: b.compaction_sizes.clone(),
color: COLORS.iter().position(|c| *c == b.color).unwrap_or(7),
shape: SHAPES.iter().position(|s| *s == b.shape).unwrap_or(0),
connectors: b.connectors.iter().map(|id| Toggle { id: id.clone(), name: id.clone(), on: true }).collect(),
@@ -146,6 +149,7 @@ impl App {
| Field::Fast
| Field::SelfFallbacks
| Field::Approvals
+ | Field::Compaction
| Field::Notify
| Field::Computer
| Field::Team
@@ -179,6 +183,7 @@ impl App {
Field::Fast => f.fast = !f.fast,
Field::SelfFallbacks => f.self_fallbacks = !f.self_fallbacks,
Field::Approvals => self.cycle_approval(&mut f, d),
+ Field::Compaction => f.cycle_compaction(d),
Field::Notify => f.notify = !f.notify,
Field::Computer => f.computer = !f.computer,
Field::Team => f.manage_team = f.manage_team.map(|on| !on),
@@ -283,6 +288,7 @@ impl Form {
"manageTeam": self.manage_team.unwrap_or_default(),
"offeredToNetwork": self.offered_to_network.unwrap_or(true),
"reachableByAssistants": self.reachable_by_assistants.unwrap_or(true),
+ "compaction": self.compaction,
"avatarColor": COLORS[self.color],
"avatarShape": SHAPES[self.shape],
"connectors": self.connectors.iter().filter(|t| t.on).map(|t| t.id.clone()).collect::<Vec<_>>(),
@@ -290,6 +296,21 @@ impl Form {
})
}
+ /// When Codync summarizes the chat, in the order ← → steps through: the three choices, then each size.
+ pub fn compaction_choices(&self) -> Vec<Threshold> {
+ [Threshold::Early, Threshold::NearLimit, Threshold::Off]
+ .into_iter()
+ .chain(self.compaction_sizes.iter().map(|&n| Threshold::Tokens(n)))
+ .collect()
+ }
+
+ fn cycle_compaction(&mut self, d: isize) {
+ let Some(now) = self.compaction else { return };
+ let choices = self.compaction_choices();
+ let i = choices.iter().position(|c| *c == now).unwrap_or(0);
+ self.compaction = Some(choices[cycle(i, d, choices.len())]);
+ }
+
/// Whether anything changed since the form opened.
pub fn dirty(&self) -> bool {
self.body() != self.opened
@@ -360,6 +381,33 @@ mod tests {
assert_eq!(f.changes(), json!({"notify": false}), "a model changed elsewhere meanwhile stays");
}
+ #[tokio::test]
+ async fn the_compaction_threshold_steps_through_choices_then_sizes() {
+ let mut app = test_app();
+ let bot = json!({"id": "b", "name": "B", "backend": "claude", "compaction": "off",
+ "compactionTokens": {"min": 50_000, "max": 70_000, "step": 10_000}});
+ app.bots.insert("b".into(), Bot::parse(&bot).expect("a bot"));
+ app.selected = Some("b".into());
+ app.edit_bot();
+ let Some(Overlay::Form(mut f)) = app.overlays.pop() else { panic!("the editor opens") };
+ f.field = FIELDS.iter().position(|x| *x == Field::Compaction).expect("a compaction field");
+ let right = KeyEvent::from(KeyCode::Right);
+ let Some(Overlay::Form(f)) = app.form_key(f, right) else { panic!("the editor stays") };
+ assert_eq!(f.changes(), json!({"compaction": 50_000}));
+ let Some(Overlay::Form(f)) = app.form_key(f, KeyEvent::from(KeyCode::Left)) else { panic!("stays") };
+ assert_eq!(f.changes(), json!({}));
+ assert_eq!(f.compaction_choices().len(), 6, "early, near the limit, only when full, 50K, 60K, 70K");
+
+ let other = json!({"id": "g", "name": "G", "backend": "gemini", "compaction": null});
+ app.bots.insert("g".into(), Bot::parse(&other).expect("a bot"));
+ app.selected = Some("g".into());
+ app.edit_bot();
+ let Some(Overlay::Form(mut f)) = app.overlays.pop() else { panic!("the editor opens") };
+ f.field = FIELDS.iter().position(|x| *x == Field::Compaction).expect("a compaction field");
+ let Some(Overlay::Form(f)) = app.form_key(f, right) else { panic!("the editor stays") };
+ assert_eq!(f.changes(), json!({}), "nothing to choose where Codync doesn't summarize");
+ }
+
#[tokio::test]
async fn the_network_switches_need_a_host_that_has_them() {
let mut app = test_app();
diff --git a/host/src/tui/app/tests.rs b/host/src/tui/app/tests.rs
index 62b8adb1..43a2cb6e 100644
--- a/host/src/tui/app/tests.rs
+++ b/host/src/tui/app/tests.rs
@@ -164,3 +164,21 @@ async fn lead_role_opens_from_the_keyboard_and_badge_without_changing_selection(
app.on_key(KeyEvent::from(KeyCode::Enter));
assert!(app.overlays.is_empty());
}
+
+#[tokio::test]
+async fn the_settings_form_scrolls_to_keep_the_focused_field_in_sight() {
+ use ratatui::{Terminal, backend::TestBackend};
+ let mut app = test_app();
+ app.bots.insert("b".into(), Bot::parse(&json!({"id": "b", "name": "B", "backend": "claude"})).expect("valid bot"));
+ app.selected = Some("b".into());
+ app.edit_bot();
+ let mut drawn = |field: usize| {
+ let Some(Overlay::Form(f)) = app.overlays.last_mut() else { panic!("the editor opens") };
+ f.field = field;
+ let mut terminal = Terminal::new(TestBackend::new(100, 44)).expect("terminal");
+ terminal.draw(|frame| crate::tui::view::draw(frame, &mut app)).expect("draw the form");
+ terminal.backend().buffer().content().iter().map(ratatui::buffer::Cell::symbol).collect::<String>()
+ };
+ assert!(!drawn(0).contains("Skills"), "more fields than the form has rows");
+ assert!(drawn(FIELDS.len() - 1).contains("Skills"), "scrolled to the focused one");
+}
diff --git a/host/src/tui/app/ui.rs b/host/src/tui/app/ui.rs
index c429c46e..bbd0b267 100644
--- a/host/src/tui/app/ui.rs
+++ b/host/src/tui/app/ui.rs
@@ -179,6 +179,7 @@ pub enum Field {
SelfFallbacks,
Folder,
Approvals,
+ Compaction,
Notify,
Computer,
Team,
@@ -190,7 +191,7 @@ pub enum Field {
Skills,
}
-pub const FIELDS: [Field; 19] = [
+pub const FIELDS: [Field; 20] = [
Field::Name,
Field::Instructions,
Field::Agent,
@@ -201,6 +202,7 @@ pub const FIELDS: [Field; 19] = [
Field::SelfFallbacks,
Field::Folder,
Field::Approvals,
+ Field::Compaction,
Field::Notify,
Field::Computer,
Field::Team,
@@ -242,6 +244,9 @@ pub struct Form {
/// `None`: the host has no per-bot network switches.
pub offered_to_network: Option<bool>,
pub reachable_by_assistants: Option<bool>,
+ /// `None`: Codync doesn't summarize this agent's chats.
+ pub compaction: Option<codync_mem::compaction::Threshold>,
+ pub compaction_sizes: Vec<u64>,
pub color: usize,
pub shape: usize,
pub connectors: Vec<Toggle>,
diff --git a/host/src/tui/view/forms.rs b/host/src/tui/view/forms.rs
index ffd4f39c..d721317d 100644
--- a/host/src/tui/view/forms.rs
+++ b/host/src/tui/view/forms.rs
@@ -15,6 +15,17 @@ use super::overlay::input_line;
use super::set_cursor;
use super::style::{FACE, avatar, bot_color, face_style, theme};
use super::time::{MONTHS, local, month_day};
+use codync_mem::compaction::Threshold;
+
+/// A compaction threshold as the apps name it: a choice, or the size as "120K".
+fn compaction_label(at: Threshold) -> String {
+ match at {
+ Threshold::Early => tr("Early (default)").into_owned(),
+ Threshold::NearLimit => tr("Near the limit").into_owned(),
+ Threshold::Off => tr("Only when full").into_owned(),
+ Threshold::Tokens(n) => format!("{}K", n / 1000),
+ }
+}
/// "created by Lead · Oct 20" for a bot another bot created (`chat::manage`).
fn created_by(app: &App, id: &str) -> Option<String> {
@@ -24,6 +35,53 @@ fn created_by(app: &App, id: &str) -> Option<String> {
Some(format!("created by {creator} · {} {day}", MONTHS[month]))
}
+/// The rows a field's value takes.
+fn field_rows(field: Field) -> u16 {
+ if field == Field::Instructions { 3 } else { 1 }
+}
+
+/// The line under the fields: why saving failed, else what the focused field does.
+fn field_help(app: &App, f: &Form, agent_name: &str) -> Option<(String, Style)> {
+ let t = theme();
+ if let Some(e) = &f.error {
+ return Some((e.clone(), t.red));
+ }
+ let line = match f.current() {
+ Field::Fast => match app.bots.get(&f.bot_id).and_then(super::super::app::Bot::fast_refusal) {
+ Some(why) => return Some((why, t.amber)),
+ None => tr("Faster replies for more usage, on models that offer it (Claude Code, Codex)").into_owned(),
+ },
+ Field::Computer => tr("Set up on the computer: Codync → Settings → Computer access").into_owned(),
+ Field::Fallbacks => tr("If {agent} runs out of usage or can't answer, the bot carries on with the next one. Chat, memory and workspace carry over.")
+ .replace("{agent}", agent_name),
+ Field::SelfFallbacks => {
+ tr("Let the bot change its fallbacks: it can set this list itself, for example when you ask it to.").into_owned()
+ }
+ Field::Approvals => {
+ let choice = app.approval(f);
+ [choice.note.unwrap_or_default(), tr(choice.detail).into_owned()].join(" ").trim().to_owned()
+ }
+ Field::Compaction if f.compaction.is_none() => tr("Claude Code and Codex bots only").into_owned(),
+ Field::Compaction => {
+ let about = tr(
+ "When Codync summarizes this chat so it can go on. If the chat fills up first, the agent summarizes it itself.",
+ );
+ let sizes = if f.compaction_sizes.is_empty() { tr("Sizes show after the bot's next reply") } else { "".into() };
+ [about, sizes].join(" ").trim().to_owned()
+ }
+ Field::Team => {
+ "Let this bot create bots and change any bot's setup, its own included. The bots it creates can too.".to_owned()
+ }
+ Field::Network => tr("Offered to the network: bots on your other computers can see and message this bot.").into_owned(),
+ Field::Assistants => {
+ tr("Reachable by cloud assistants: ChatGPT or Claude in your Codync account can see and message this bot.")
+ .into_owned()
+ }
+ _ => return None,
+ };
+ Some((line, t.dim))
+}
+
pub(super) fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {
let t = theme();
let r = centered(area, 88, 42);
@@ -44,7 +102,13 @@ pub(super) fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {
let vw = inner.right().saturating_sub(vx);
let mut y = inner.y + 1;
let agent_name = app.agent_name(&f.backend);
- for (i, field) in FIELDS.iter().enumerate() {
+ // The form can outgrow the terminal: it starts as far down as keeps the focused field in sight.
+ let room = inner.bottom().saturating_sub(2).saturating_sub(y);
+ let mut first = 0;
+ while first < f.field && FIELDS[first..f.field].iter().map(|field| field_rows(*field) + 1).sum::<u16>() >= room {
+ first += 1;
+ }
+ for (i, field) in FIELDS.iter().enumerate().skip(first) {
let active = i == f.field;
let base = if active { t.sel } else { t.panel };
let lab = match field {
@@ -58,6 +122,7 @@ pub(super) fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {
Field::SelfFallbacks => "Bot edits",
Field::Folder => "Workspace",
Field::Approvals => "Approvals",
+ Field::Compaction => "Summarize",
Field::Notify => "Notify",
Field::Computer => "Use computer",
Field::Team => "Manage team",
@@ -70,7 +135,7 @@ pub(super) fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {
};
let label = tr(lab);
put(buf, fx, y, label_w, &label, if active { t.bold } else { t.secondary }.patch(t.panel));
- let rows = if *field == Field::Instructions { 3 } else { 1 };
+ let rows = field_rows(*field);
if active {
restyle(buf, Rect::new(vx.saturating_sub(1), y, vw + 1, rows), t.sel);
}
@@ -213,6 +278,13 @@ pub(super) fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {
let label = app.approval(f).label;
put(buf, vx, y, vw, &format!("‹ {} ›", tr(&label)), t.text.patch(base));
}
+ Field::Compaction => {
+ let (value, style) = match f.compaction {
+ Some(at) => (format!("‹ {} ›", compaction_label(at)), t.text),
+ None => ("—".to_owned(), t.dim),
+ };
+ put(buf, vx, y, vw, &value, style.patch(base));
+ }
Field::Computer => {
let s = if f.computer { "◉ On ○ Off" } else { "○ On ◉ Off" };
let status = super::computer_access::status(&app.screen, app.online);
@@ -279,48 +351,8 @@ pub(super) fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {
}
}
let by = inner.bottom() - 1;
- if let Some(e) = &f.error {
- put(buf, inner.x, by - 1, inner.width, e, t.red.patch(t.panel));
- } else if f.current() == Field::Fast {
- let refusal = app.bots.get(&f.bot_id).and_then(super::super::app::Bot::fast_refusal);
- let (line, style) = match refusal {
- Some(why) => (why, t.amber),
- None => {
- (tr("Faster replies for more usage, on models that offer it (Claude Code, Codex)").into_owned(), t.dim)
- }
- };
+ if let Some((line, style)) = field_help(app, f, &agent_name) {
put(buf, inner.x, by - 1, inner.width, &line, style.patch(t.panel));
- } else if f.current() == Field::Computer {
- put(
- buf,
- inner.x,
- by - 1,
- inner.width,
- &tr("Set up on the computer: Codync → Settings → Computer access"),
- t.dim.patch(t.panel),
- );
- } else if f.current() == Field::Fallbacks {
- let line = tr("If {agent} runs out of usage or can't answer, the bot carries on with the next one. Chat, memory and workspace carry over.")
- .replace("{agent}", &agent_name);
- put(buf, inner.x, by - 1, inner.width, &line, t.dim.patch(t.panel));
- } 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.";
- put(buf, inner.x, by - 1, inner.width, line, t.dim.patch(t.panel));
- } else if f.current() == Field::Network {
- let line = tr("Offered to the network: bots on your other computers can see and message this bot.");
- put(buf, inner.x, by - 1, inner.width, &line, t.dim.patch(t.panel));
- } else if f.current() == Field::Assistants {
- let line =
- tr("Reachable by cloud assistants: ChatGPT or Claude in your Codync account can see and message this bot.");
- put(buf, inner.x, by - 1, inner.width, &line, t.dim.patch(t.panel));
}
let save = if f.saving {
" … Saving "
@@ -344,6 +376,7 @@ pub(super) fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {
| Field::Color
| Field::Shape
| Field::Approvals
+ | Field::Compaction
| Field::Notify
| Field::Computer
| Field::Team
diff --git a/host/tests/compaction_e2e.rs b/host/tests/compaction_e2e.rs
index 0a08f251..08f3408f 100644
--- a/host/tests/compaction_e2e.rs
+++ b/host/tests/compaction_e2e.rs
@@ -47,6 +47,38 @@ async fn a_full_conversation_is_compacted_with_its_keep_list() {
assert!(host.prompts(&codex).iter().any(|p| p == "/compact"), "Codex's keep-list is in its config");
}
+#[tokio::test]
+async fn the_users_threshold_decides_when_the_host_compacts() {
+ let host = Host::start().await;
+ let bot = host.fixture_bot("Roomy", "instructions_agent.py", "claude").await;
+ let shown = common::bot(&host.snapshot().await, &bot).clone();
+ assert!(shown["compaction"].is_null(), "a custom command shows it once it runs Claude");
+ host.reply(&bot, "USAGE 10000 SIZE 1000000").await;
+ let deadline = Instant::now() + Duration::from_secs(10);
+ let shown = loop {
+ let shown = common::bot(&host.snapshot().await, &bot).clone();
+ if !shown["compactionTokens"].is_null() || Instant::now() > deadline {
+ break shown;
+ }
+ };
+ assert_eq!(shown["compaction"], "early");
+ assert_eq!(shown["compactionTokens"], json!({"min": 50_000, "max": 960_000, "step": 10_000}));
+
+ host.call("updateBot", json!({"id": bot, "compaction": 300_000})).await;
+ host.reply(&bot, "USAGE 210000 SIZE 1000000").await;
+ host.reply(&bot, "still short of it").await;
+ assert!(!host.prompts(&bot).iter().any(|p| p.starts_with("/compact")), "200k is short of the user's 300k");
+ host.reply(&bot, "USAGE 300000 SIZE 1000000").await;
+ notice(&host, &bot, "compaction").await;
+
+ let off = host.fixture_bot("Off", "instructions_agent.py", "codex").await;
+ host.call("updateBot", json!({"id": off, "compaction": "off"})).await;
+ host.reply(&off, "USAGE 950000 SIZE 1000000").await;
+ host.reply(&off, "next").await;
+ assert!(!host.prompts(&off).iter().any(|p| p == "/compact"), "left to the agent's own compaction");
+ assert!(host.refused("updateBot", json!({"id": off, "compaction": 123_456})).await.contains("multiple of"));
+}
+
#[tokio::test]
async fn compacting_too_often_turns_into_a_rollover_the_user_can_edit_or_turn_down() {
let host = Host::start().await;
diff --git a/host/tests/fixtures/wire-shape.json b/host/tests/fixtures/wire-shape.json
index cb421357..cc5269d2 100644
--- a/host/tests/fixtures/wire-shape.json
+++ b/host/tests/fixtures/wire-shape.json
@@ -10,6 +10,8 @@
"event:bot.bot.avatarShape": "string",
"event:bot.bot.backend": "string",
"event:bot.bot.command": "string",
+ "event:bot.bot.compaction": "null",
+ "event:bot.bot.compactionTokens": "null",
"event:bot.bot.computer": "bool",
"event:bot.bot.connectors": "array",
"event:bot.bot.createdAt": "number",
diff --git a/web/content/docs/bots.mdx b/web/content/docs/bots.mdx
index f4cc939f..1702eaa2 100644
--- a/web/content/docs/bots.mdx
+++ b/web/content/docs/bots.mdx
@@ -81,6 +81,19 @@ The same setting covers changes a bot makes to other bots with **Manage the team
How approval cards work: [Conversations](/docs/conversations#approval-cards).
+## Summarize long chats
+
+For a Claude Code or Codex bot, **Summarize long chats** decides when Codync summarizes the bot's chat so the conversation can go on with room to spare. It sits right after Permissions.
+
+| Setting | When Codync summarizes |
+| --- | --- |
+| **Early** (default) | Once the chat uses three quarters of the model's window or 200K tokens, whichever is less. It may also summarize a chat over 100K just before its cache expires, or start a [fresh conversation](/docs/conversations#fresh-conversations) when you come back after the cache went cold. |
+| **Near the limit** | Just before the window fills: 40K short of it (960K on a 1M window), and never sooner than Early. |
+| **Only when full** | Never ahead of time. The agent summarizes on its own when a chat fills its window. |
+| **Set a size** | At the size you pick, in 10K steps from 50K up to the largest the window allows. |
+
+With Near the limit or a size, nothing summarizes the chat or starts it over before it reaches that size, except that a chat already summarized three times starts fresh after eight hours away. The sizes appear once the bot has replied and its agent has said how large its window is. A size larger than a new model's window counts as that window's largest. A longer chat costs more usage on every turn, because the agent reads all of it each time. In the terminal UI this field is called **Summarize**, and ←/→ goes through the same choices, then each size.
+
## Activity
- **Notifications:** notify you when this bot finishes, fails or needs you. Turn it off to keep the bot quiet.
diff --git a/web/content/docs/conversations.mdx b/web/content/docs/conversations.mdx
index 9d290714..5a659666 100644
--- a/web/content/docs/conversations.mdx
+++ b/web/content/docs/conversations.mdx
@@ -132,6 +132,8 @@ Before your next message, you can:
Afterwards the card folds into one line that unfolds to what was carried.
+When Codync summarizes, and whether it starts fresh conversations at all, is the bot's [Summarize long chats](/docs/bots#summarize-long-chats) setting.
+
## Notifications
Your iPhone gets a notification when a bot: