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: move Summarize long chats under the agent and let users type a size

leepokai40f174bbb4c3
diff --git a/apps/android/WhatsNew.md b/apps/android/WhatsNew.md
index 9c207c64..27536ac1 100644
--- a/apps/android/WhatsNew.md
+++ b/apps/android/WhatsNew.md
@@ -9,10 +9,10 @@ else a generic "Bug fixes and improvements" line. Delete old sections.
## 2.42.0
### zh-Hant
-- bot 設定新增「壓縮對話」:選擇 Codync 什麼時候把長對話壓縮成摘要。可以選提早(預設)、接近上限、不主動壓縮,或以 10K 為一級自己指定數量,最多到模型裝得下的上限。適用於 Claude Code 和 Codex 的 bot。
+- bot 詳情的「智慧體」區塊新增「壓縮對話」:選擇 Codync 什麼時候把長對話壓縮成摘要。可以選提早(預設)、接近上限、不主動壓縮,或指定數量:從 100K、200K… 裡挑,或自己輸入,最多到模型裝得下的上限。適用於 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.
+- New Summarize long chats setting in a bot's Agent section: choose when Codync summarizes a long chat. Pick Early (default), Near the limit, Only when full, or a size: 100K, 200K and so on, or one you type, up to what the model holds. For Claude Code and Codex bots.
## 2.41.0
### zh-Hant
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 09590f0c..ec771bc6 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
@@ -59,8 +59,8 @@ 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)
+ agentRows(state, store, draft, change, bot, modelReload, reloadModels = { modelReload++ }) { addingFallback = true }
+ compactionRow(bot, draft, change); placeRows(state, store, draft, change, modelReload) { folders = true }
}
CardSection("Activity") {
notifyRow(draft, change); computerUseRow(state, draft, change); manageTeamRow(state, draft, change); reachRows(state, draft, change)
@@ -72,6 +72,7 @@ internal enum class FormPart { All, Often, Rarely }
CardSection("Agent") {
fallbackBanner(state, store, bot)
agentRows(state, store, draft, change, bot, modelReload, reloadModels = { modelReload++ }) { addingFallback = true }
+ compactionRow(bot, draft, change)
if (!online) row { OfflineNote() }
}
}
@@ -82,7 +83,7 @@ internal enum class FormPart { All, Often, Rarely }
}
// 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 }; compactionRow(bot, draft, change)
+ computerRow(state, online); placeRows(state, store, draft, change, modelReload) { folders = true }
}
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
index 65af5f5b..3e7fc363 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/CompactionPicker.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/CompactionPicker.kt
@@ -2,11 +2,25 @@ package com.codync.android
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.text.KeyboardActions
+import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.focus.FocusRequester
+import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.text.input.ImeAction
+import androidx.compose.ui.text.TextRange
+import androidx.compose.ui.text.input.KeyboardType
+import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.codync.android.core.Bot
@@ -25,25 +39,45 @@ internal fun CardRows.compactionRow(bot: Bot?, draft: BotDraft, change: (BotDraf
}
}
-/** The pill and its menu: the three choices, then the sizes the agent's window allows (a scrolling submenu). */
+/** The pill and its menu: the three choices, then the sizes the menu lists and one the user types. */
@Composable private fun CompactionPicker(choice: Compaction, tokens: CompactionTokens?, select: (Compaction) -> Unit) {
+ var typing by remember { mutableStateOf(false) }
val current = if (choice is Compaction.Tokens) choice.label else tr(choice.label)
- DropdownMenu({ compactionRows(choice, tokens, select) }, label = "${tr("Summarize long chats")}: $current") {
+ DropdownMenu({ compactionRows(choice, tokens, select) { typing = true } }, 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)
}
}
+ if (tokens != null) CustomSizeDialog(typing, (choice as? Compaction.Tokens)?.tokens, tokens, { typing = false }) { select(Compaction.Tokens(it)) }
}
-private fun compactionRows(choice: Compaction, tokens: CompactionTokens?, select: (Compaction) -> Unit): List<MenuItem> {
+private fun compactionRows(choice: Compaction, tokens: CompactionTokens?, select: (Compaction) -> Unit, custom: () -> Unit): List<MenuItem> {
val presets = listOf(Compaction.Early, Compaction.NearLimit, Compaction.Off).map { preset ->
MenuItem(preset.label, selected = choice == preset) { select(preset) }
}
+ if (tokens == null) return presets + MenuItem("Sizes show after the bot's next reply", divider = true, enabled = false)
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 ->
+ val sizes = tokens.presets.map { size ->
MenuItem(Compaction.sizeLabel(size), selected = size == picked, verbatim = true) { select(Compaction.Tokens(size)) }
- })
- return presets + sizes
+ }
+ val own = MenuItem("Custom size…", selected = picked != null && picked !in tokens.presets, action = custom)
+ return presets + MenuItem("Set a size", divider = true, children = sizes + own)
+}
+
+/** "Custom size": thousands of tokens, saved as the nearest size the window takes; Save waits for a number. */
+@Composable private fun CustomSizeDialog(shown: Boolean, current: Long?, tokens: CompactionTokens, dismiss: () -> Unit, save: (Long) -> Unit) {
+ var text by remember { mutableStateOf(TextFieldValue()) }
+ // Set when it opens, with the cursor after the size; kept while it fades away.
+ LaunchedEffect(shown) { if (shown) text = current?.let { (it / 1000).toString() }.orEmpty().let { TextFieldValue(it, TextRange(it.length)) } }
+ val typed = Compaction.typed(text.text)
+ val submit: () -> Unit = { typed?.let { save(tokens.fit(it)) } }
+ CodyncDialog("Custom size", shown, dismiss, message = "Thousands of tokens, rounded to 10K, up to what the model holds.", field = {
+ val focus = remember { FocusRequester() }
+ LaunchedEffect(Unit) { focus.requestFocus() }
+ PlainTextField(text, { text = it }, Modifier.fillMaxWidth().focusRequester(focus).pill(Palette.background),
+ "${tokens.min / 1000}–${tokens.max / 1000}", singleLine = true,
+ keyboard = KeyboardOptions(keyboardType = KeyboardType.Decimal, imeAction = ImeAction.Done),
+ actions = KeyboardActions(onDone = { if (typed != null) { dismiss(); submit() } }))
+ }) { listOf(DialogAction("Save", enabled = typed != null, action = submit)) }
}
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
index 49ed7d8c..bcf5eb10 100644
--- 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
@@ -31,13 +31,24 @@ sealed interface Compaction {
companion object {
fun sizeLabel(tokens: Long): String = "${tokens / 1000}K"
+
+ /** A size the user typed, in thousands of tokens ("350", "350K", "1.5k"), as tokens; null when it isn't one. */
+ fun typed(text: String): Long? {
+ val k = text.trim().removeSuffix("k").removeSuffix("K").trim().toDoubleOrNull() ?: return null
+ // Past a billion thousands no window holds it, and the tokens would overflow when fitted.
+ return if (k > 0 && k < 1e9) Math.round(k * 1000) else null
+ }
}
}
-/** The sizes the bot's window allows (`compactionTokens`): [min] to [max] by [step]. */
+/** The sizes the bot's window allows (`compactionTokens`): [min] to [max] by [step], and the few a menu lists. */
@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()
+data class CompactionTokens(val min: Long, val max: Long, val step: Long, val presets: List<Long> = emptyList()) {
+ /** A typed size as one the window takes: to the nearest [step], within [min] and [max]. */
+ fun fit(tokens: Long): Long {
+ val step = step.coerceAtLeast(1)
+ return ((tokens + step / 2) / step * step).coerceAtLeast(min).coerceAtMost(max)
+ }
}
/** `"early"`, `"nearLimit"`, `"off"` or a number of tokens; a name from a newer host reads as early, rather than losing the bot. */
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
index afc815a6..983c246a 100644
--- 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
@@ -17,14 +17,25 @@ class CompactionTest {
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())
+ @Test fun `the menu lists the presets, and a typed size fits the window`() {
+ val read = bot(""", "compaction": "early", "compactionTokens": {"min": 50000, "max": 960000, "step": 10000, "presets": [100000, 200000]}""")
+ val tokens = read.compactionTokens!!
+ assertEquals(listOf(100_000L, 200_000L), tokens.presets)
+ assertEquals(listOf(350_000L, 360_000L, 50_000L, 960_000L), listOf(354_000L, 355_000L, 10_000L, 5_000_000L).map(tokens::fit))
assertEquals("120K", Compaction.Tokens(120_000).label)
assertNull(bot(""", "compactionTokens": null""").compactionTokens)
+ val small = bot(""", "compactionTokens": {"min": 50000, "max": 90000, "step": 10000, "presets": []}""")
+ assertEquals(emptyList<Long>(), small.compactionTokens!!.presets)
+ }
+
+ @Test fun `a typed size reads in thousands of tokens`() {
+ assertEquals(350_000L, Compaction.typed("350"))
+ assertEquals(350_000L, Compaction.typed("350k"))
+ assertEquals(1_500L, Compaction.typed(" 1.5K "))
+ assertNull(Compaction.typed("abc"))
+ assertNull(Compaction.typed(""))
+ assertNull(Compaction.typed("0"))
+ assertNull(Compaction.typed("99999999999999999"))
}
@Test fun `a draft sends the choice as the host reads it, and nothing where there is none`() {
diff --git a/apps/android/design/src/main/kotlin/com/codync/android/design/Dialog.kt b/apps/android/design/src/main/kotlin/com/codync/android/design/Dialog.kt
index 0dfe1784..15e7cb65 100644
--- a/apps/android/design/src/main/kotlin/com/codync/android/design/Dialog.kt
+++ b/apps/android/design/src/main/kotlin/com/codync/android/design/Dialog.kt
@@ -35,8 +35,8 @@ import androidx.compose.ui.unit.dp
import com.kyant.shapes.Capsule
import com.kyant.shapes.RoundedRectangle
-/** A button in a Codync dialog. */
-class DialogAction(val title: String, val destructive: Boolean = false, val action: () -> Unit)
+/** A button in a Codync dialog; [enabled] is off while what it asks for isn't valid yet (a field that doesn't read). */
+class DialogAction(val title: String, val destructive: Boolean = false, val enabled: Boolean = true, val action: () -> Unit)
/**
* A centered card over a dimmed screen with the actions and Cancel: the replacement for
@@ -70,7 +70,7 @@ class DialogAction(val title: String, val destructive: Boolean = false, val acti
}
field?.invoke()
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
- for (action in actions()) DialogButton(tr(action.title), action.destructive, prominent = true) { dismiss(); action.action() }
+ for (action in actions()) DialogButton(tr(action.title), action.destructive, prominent = true, enabled = action.enabled) { dismiss(); action.action() }
if (cancel != null) DialogButton(tr(cancel), destructive = false, prominent = false) { dismiss() }
}
}
@@ -78,11 +78,11 @@ class DialogAction(val title: String, val destructive: Boolean = false, val acti
}
}
-@Composable private fun DialogButton(title: String, destructive: Boolean, prominent: Boolean, action: () -> Unit) {
+@Composable private fun DialogButton(title: String, destructive: Boolean, prominent: Boolean, enabled: Boolean = true, action: () -> Unit) {
val (source, pressed) = rememberPress()
- Box(Modifier.fillMaxWidth().pressScale(pressed).graphicsLayer { alpha = if (pressed) 0.85f else 1f }.clip(Capsule())
+ Box(Modifier.fillMaxWidth().pressScale(pressed).graphicsLayer { alpha = if (enabled) (if (pressed) 0.85f else 1f) else 0.4f }.clip(Capsule())
.background(if (destructive) Palette.danger else if (prominent) Palette.accentFill else Palette.bubbleUser)
- .clickable(source, null, role = Role.Button, onClick = action).padding(vertical = 12.dp), contentAlignment = Alignment.Center) {
+ .clickable(source, null, enabled = enabled, role = Role.Button, onClick = action).padding(vertical = 12.dp), contentAlignment = Alignment.Center) {
Text(title, style = Type.body.medium, color = if (destructive) Color.White else if (prominent) Palette.onAccent else Palette.text)
}
}
diff --git a/apps/desktop/e2e/compaction.spec.ts b/apps/desktop/e2e/compaction.spec.ts
index 4f6e45a9..735b4a57 100644
--- a/apps/desktop/e2e/compaction.spec.ts
+++ b/apps/desktop/e2e/compaction.spec.ts
@@ -8,12 +8,12 @@ const agent = join(resolve(__dirname, '../../..'), 'host/tests/fixtures/instruct
type Bot = { id: string; compaction: unknown }
-/** The bot's Summarize long chats row, on the Settings tab of the details beside its chat. */
+/** The bot's Summarize long chats row, in the Agent card on the Details 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()
+ await details.getByRole('tab', { name: 'Details' }).click()
return details.locator('.value-row', { hasText: 'Summarize long chats' })
}
@@ -28,7 +28,8 @@ test('before its first reply a Claude Code bot offers only the three choices', a
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')
+ const row = await summarizeRow(page, name)
+ const pill = row.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()
@@ -37,13 +38,19 @@ test('before its first reply a Claude Code bot offers only the three choices', a
await menuRow(page, 'Only when full').click()
await expect(pill).toHaveText('Only when full')
await expect.poll(() => stored(page, botId!)).toBe('off')
+
+ // It moved off the Settings tab.
+ const details = page.locator('.details-panel')
+ await details.getByRole('tab', { name: 'Settings' }).click()
+ await expect(details.locator('.value-row', { hasText: 'Workspace' })).toBeVisible()
+ await expect(row).toHaveCount(0)
} 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 () => {
+test('once the agent tells its window, Set a size lists sizes by 100K and takes one typed', async () => {
const { browser, page } = await attach()
const name = `Summarize sizes e2e ${Date.now()}`
let botId: string | undefined
@@ -58,16 +65,29 @@ test('once the agent tells its window, Set a size lists what it holds and the si
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)
+ await expect(menuRow(page, /^100K$/)).toBeVisible()
+ await expect(menuRow(page, /^900K$/)).toBeAttached()
+ await expect(menuRow(page, /^50K$/)).toHaveCount(0)
+ await menuRow(page, /^100K$/).click()
+ await expect(pill).toHaveText('100K')
+ await expect.poll(() => stored(page, botId!)).toBe(100_000)
+
+ // A size of one's own: typed in thousands, kept to the nearest 10K.
+ await pill.click()
+ await menuRow(page, 'Set a size').click()
+ await menuRow(page, 'Custom size…').click()
+ const field = page.locator('.dialog-field')
+ await expect(field).toHaveAttribute('placeholder', '50–960')
+ await expect(field).toHaveValue('100')
+ await field.fill('354')
+ await page.locator('.dialog-button', { hasText: 'Save' }).click()
+ await expect(pill).toHaveText('350K')
+ await expect.poll(() => stored(page, botId!)).toBe(350_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 expect(menuRow(page, 'Custom size…')).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')
@@ -87,7 +107,7 @@ test('a bot on an agent Codync does not summarize for has no Summarize long chat
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(page.locator('.details-panel h3', { hasText: 'Agent' })).toBeVisible()
await expect(row).toHaveCount(0)
} finally {
if (botId) await api(page, 'deleteBot', { botId }).catch(() => {})
diff --git a/apps/desktop/src/renderer/components/Overlay.tsx b/apps/desktop/src/renderer/components/Overlay.tsx
index a0ef60d9..efc75f35 100644
--- a/apps/desktop/src/renderer/components/Overlay.tsx
+++ b/apps/desktop/src/renderer/components/Overlay.tsx
@@ -1,4 +1,4 @@
-import { createContext, useContext, useEffect, useId, useLayoutEffect, useRef, useState, type ReactElement, type ReactNode, type RefObject } from 'react'
+import { createContext, useContext, useEffect, useId, useLayoutEffect, useRef, useState, type HTMLAttributes, type ReactElement, type ReactNode, type RefObject } from 'react'
import { createPortal } from 'react-dom'
import { reduceMotion } from '../lib/theme'
import { afterExit } from '../lib/exit-delay'
@@ -231,6 +231,26 @@ export function Dialog({ open, title, message, actions, cancel = 'Cancel', onCan
)
}
+/** A `Dialog`'s text box, focused as it opens: Return, once the IME has finished composing, runs `onSubmit`. */
+export function DialogField({ value, onChange, onSubmit, placeholder, label, inputMode }: {
+ value: string
+ onChange: (value: string) => void
+ onSubmit: () => void
+ placeholder: string
+ label: string
+ inputMode?: HTMLAttributes<HTMLInputElement>['inputMode']
+}) {
+ return (
+ <input className="dialog-field" data-autofocus value={value} placeholder={placeholder} aria-label={label} inputMode={inputMode} spellCheck={false}
+ onChange={(e) => onChange(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key !== 'Enter' || e.nativeEvent.isComposing || e.keyCode === 229) return
+ e.preventDefault()
+ onSubmit()
+ }} />
+ )
+}
+
/** 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/lib/compaction-options.test.ts b/apps/desktop/src/renderer/lib/compaction-options.test.ts
index a3dfc689..70080ae4 100644
--- a/apps/desktop/src/renderer/lib/compaction-options.test.ts
+++ b/apps/desktop/src/renderer/lib/compaction-options.test.ts
@@ -1,34 +1,42 @@
import assert from 'node:assert/strict'
import { test } from 'node:test'
-import { compactionLabel, compactionMenu, compactionSizes } from './compaction-options.ts'
+import { compactionLabel, compactionMenu, fitSize, parseTypedSize } 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')
+const million = { min: 50_000, max: 960_000, step: 10_000, presets: [100_000, 200_000, 300_000] }
+
+test('a typed size goes to the nearest 10K the window takes', () => {
+ assert.deepEqual([354_000, 355_000, 10_000, 5_000_000].map((n) => fitSize(million, n)), [350_000, 360_000, 50_000, 960_000])
+})
+
+test('a size is typed in thousands of tokens', () => {
+ assert.deepEqual(['350', '350k', ' 1.5K ', 'abc', '', '0', '-5'].map(parseTypedSize), [350_000, 350_000, 1500, null, null, null, null])
})
-test('the menu checks the choice and opens the sizes', () => {
+test('the menu lists the presets, then the sizes and a custom one', () => {
const picked: unknown[] = []
- const menu = compactionMenu(120_000, { min: 50_000, max: 160_000, step: 10_000 }, (t) => picked.push(t))
+ let custom = 0
+ const menu = compactionMenu(200_000, million, (t) => picked.push(t), () => custom++)
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'])
+ assert.deepEqual(sizes.map((m) => m.title), ['100K', '200K', '300K', 'Custom size…'])
+ assert.deepEqual(sizes.filter((m) => m.selected).map((m) => m.title), ['200K'])
sizes[0].action?.()
menu[1].action?.()
- assert.deepEqual(picked, [50_000, 'nearLimit'])
+ sizes.at(-1)?.action?.()
+ assert.deepEqual(picked, [100_000, 'nearLimit'])
+ assert.equal(custom, 1)
+ const own = compactionMenu(350_000, million, () => {}, () => {})[3].submenu ?? []
+ assert.deepEqual(own.filter((m) => m.selected).map((m) => m.title), ['Custom size…'], 'a size of the user\'s own')
})
test('before the window is known the sizes wait for the next reply', () => {
- const menu = compactionMenu('early', null, () => {})
+ 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 })
+ assert.deepEqual(compactionLabel(350_000), { title: '350K', verbatim: true })
})
diff --git a/apps/desktop/src/renderer/lib/compaction-options.ts b/apps/desktop/src/renderer/lib/compaction-options.ts
index 59e3a36a..4ba9260f 100644
--- a/apps/desktop/src/renderer/lib/compaction-options.ts
+++ b/apps/desktop/src/renderer/lib/compaction-options.ts
@@ -16,18 +16,27 @@ export function compactionLabel(threshold: CompactionThreshold): { title: string
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
+/** A typed size as one the window takes: to the nearest step, within `min` and `max`. */
+export function fitSize(sizes: CompactionSizes, tokens: number): number {
+ const step = Math.max(sizes.step, 1)
+ return Math.min(Math.max(Math.floor((tokens + step / 2) / step) * step, sizes.min), sizes.max)
}
-/** 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[] {
+/** What the user typed, in thousands of tokens (`350`, `350K`), as tokens; null when it isn't a size. */
+export function parseTypedSize(text: string): number | null {
+ const k = Number(text.trim().replace(/k$/i, ''))
+ return text.trim() && Number.isFinite(k) && k > 0 ? Math.round(k * 1000) : null
+}
+
+/**
+ * The presets, then "Set a size" opening the window's few listed sizes and "Custom size…" (`custom`); before the
+ * window is known, a line saying when they come.
+ */
+export function compactionMenu(selection: CompactionThreshold, sizes: CompactionSizes | null,
+ pick: (threshold: CompactionThreshold) => void, custom: () => 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 }]
+ const listed: MenuItem[] = sizes.presets.map((n) => ({ title: sizeLabel(n), verbatim: true, selected: selection === n, action: () => pick(n) }))
+ const own = typeof selection === 'number' && !sizes.presets.includes(selection)
+ return [...presets, { title: 'Set a size', divider: true, submenu: [...listed, { title: 'Custom size…', selected: own, action: custom }] }]
}
diff --git a/apps/desktop/src/renderer/views/SectionNameDialog.tsx b/apps/desktop/src/renderer/views/SectionNameDialog.tsx
index a31c415d..8a20e18e 100644
--- a/apps/desktop/src/renderer/views/SectionNameDialog.tsx
+++ b/apps/desktop/src/renderer/views/SectionNameDialog.tsx
@@ -1,5 +1,5 @@
import { useState } from 'react'
-import { Dialog } from '../components/Overlay'
+import { Dialog, DialogField } from '../components/Overlay'
import { limitSectionName, sectionName } from '../lib/roster-sections'
import { useTr } from '../lib/use-language'
import type { SectionNaming } from './section-menus'
@@ -21,11 +21,8 @@ export function SectionNameDialog({ naming, onClose }: { naming: SectionNaming |
return (
<Dialog open={naming !== null} title={naming ? tr(naming.title) : ''} actions={[{ title: 'Save', action: save }]} onClose={onClose}>
{/* The host refuses longer names; the field stops there first. */}
- <input className="dialog-field" data-autofocus value={name} placeholder={tr('Section name')} aria-label={tr('Section name')} spellCheck={false}
- onChange={(e) => setName(limitSectionName(e.target.value))}
- onKeyDown={(e) => {
- if (e.key !== 'Enter' || e.nativeEvent.isComposing || e.keyCode === 229) return
- e.preventDefault()
+ <DialogField value={name} placeholder={tr('Section name')} label={tr('Section name')} onChange={(text) => setName(limitSectionName(text))}
+ onSubmit={() => {
onClose()
save()
}} />
diff --git a/apps/desktop/src/renderer/views/bots/BotEditorView.tsx b/apps/desktop/src/renderer/views/bots/BotEditorView.tsx
index f820c98c..b8c9ca1b 100644
--- a/apps/desktop/src/renderer/views/bots/BotEditorView.tsx
+++ b/apps/desktop/src/renderer/views/bots/BotEditorView.tsx
@@ -168,6 +168,8 @@ function BotSettingsForm({ draft, onChange, error, plugins, part = 'all' }: {
onChange={(on) => set('selfFallbacks', on)}
/>,
] : null
+ // Only where Codync summarizes the chat (its bot says): CardSection gives every child a row.
+ const compaction = saved && saved.compaction !== null ? <CompactionRow key="compaction" draft={draft} bot={saved} onChange={onChange} /> : null
if (part === 'often') {
return (
@@ -178,6 +180,7 @@ function BotSettingsForm({ draft, onChange, error, plugins, part = 'all' }: {
{step}
{agent}
{fallbacks}
+ {compaction}
</CardSection>
{error ? <Text size="footnote" tone="danger" className="fade-in">{error}</Text> : null}
</div>
@@ -216,6 +219,7 @@ function BotSettingsForm({ draft, onChange, error, plugins, part = 'all' }: {
</ValueRow>
{part === 'all' ? agent : null}
{part === 'all' ? fallbacks : null}
+ {part === 'all' ? compaction : null}
<ValueRow
label="Workspace"
detail={
@@ -238,7 +242,6 @@ 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
index 64872503..5ca9024a 100644
--- a/apps/desktop/src/renderer/views/bots/CompactionRow.tsx
+++ b/apps/desktop/src/renderer/views/bots/CompactionRow.tsx
@@ -1,30 +1,63 @@
-import type { Bot, BotDraft } from '@shared/models'
+import { useState } from 'react'
+import type { Bot, BotDraft, CompactionSizes } from '@shared/models'
import { DropdownMenu, ValueRow } from '../../components/Controls'
import { Icon } from '../../components/Icon'
-import { compactionLabel, compactionMenu } from '../../lib/compaction-options'
+import { Dialog, DialogField } from '../../components/Overlay'
+import { compactionLabel, compactionMenu, fitSize, parseTypedSize } 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. */
+/** When Codync summarizes the chat: a preset or a size the window allows. For a bot whose chat it summarizes. */
export function CompactionRow({ draft, bot, onChange }: {
draft: BotDraft
- bot: Bot | null
+ bot: Bot
onChange: (update: (d: BotDraft) => BotDraft) => void
}) {
const tr = useTr()
- if (!bot || bot.compaction === null) return null
- const selection = draft.compaction ?? bot.compaction
+ const [typing, setTyping] = useState<string | null>(null)
+ const selection = draft.compaction ?? bot.compaction ?? 'early'
const { title, verbatim } = compactionLabel(selection)
const label = verbatim ? title : tr(title)
+ const pick = (compaction: BotDraft['compaction']) => onChange((d) => ({ ...d, compaction }))
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 })))}
+ items={() => compactionMenu(selection, bot.compactionTokens, pick, () => setTyping(typeof selection === 'number' ? String(selection / 1000) : ''))}
>
<span className="choice-label">{label}</span>
<Icon name="chevron.down" size={10} weight="semibold" color="var(--secondary)" />
</DropdownMenu>
+ {bot.compactionTokens ? (
+ <CustomSizeDialog text={typing} sizes={bot.compactionTokens} onText={setTyping} onClose={() => setTyping(null)} onSave={pick} />
+ ) : null}
</ValueRow>
)
}
+
+/** "Custom size": a number of thousands of tokens, held to what the window takes. Open while `text` is set. */
+function CustomSizeDialog({ text, sizes, onText, onClose, onSave }: {
+ text: string | null
+ sizes: CompactionSizes
+ onText: (text: string) => void
+ onClose: () => void
+ onSave: (tokens: number) => void
+}) {
+ const tr = useTr()
+ const typed = parseTypedSize(text ?? '')
+ const save = () => {
+ if (typed !== null) onSave(fitSize(sizes, typed))
+ }
+ return (
+ <Dialog open={text !== null} title={tr('Custom size')} message={tr('Thousands of tokens, rounded to 10K, up to what the model holds.')}
+ actions={[{ title: 'Save', disabled: typed === null, action: save }]} onClose={onClose}>
+ <DialogField value={text ?? ''} placeholder={`${sizes.min / 1000}–${sizes.max / 1000}`} label={tr('Custom size')} inputMode="decimal"
+ onChange={onText}
+ onSubmit={() => {
+ if (typed === null) return
+ onClose()
+ save()
+ }} />
+ </Dialog>
+ )
+}
diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.ts
index bb425ed1..30629d8a 100644
--- a/apps/desktop/src/shared/models.ts
+++ b/apps/desktop/src/shared/models.ts
@@ -268,11 +268,12 @@ export interface BotMessage {
/** 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. */
+/** The sizes a chat's window allows: `min`..`max` by `step` tokens, and the few a menu lists. */
export interface CompactionSizes {
min: number
max: number
step: number
+ presets: number[]
}
/** "Earlier context was summarized": the harness's summary, when it gave one. */
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/CompactionThreshold.swift b/apps/ios/Kit/Sources/CodyncKit/Models/CompactionThreshold.swift
index 67a8efa0..a2ec9cb9 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/CompactionThreshold.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/CompactionThreshold.swift
@@ -30,19 +30,33 @@ public enum CompactionThreshold: Codable, Hashable, Sendable {
}
}
-/// The sizes a bot's `CompactionThreshold` may take (`compactionTokens`): `min` to `max` tokens by `step`.
+/// The sizes a bot's `CompactionThreshold` may take (`compactionTokens`): `min` to `max` tokens by `step`, and the few
+/// its menu lists.
public struct TokenRange: Codable, Hashable, Sendable {
public var min: Int
public var max: Int
public var step: Int
+ public var presets: [Int]
- public init(min: Int, max: Int, step: Int) {
+ public init(min: Int, max: Int, step: Int, presets: [Int] = []) {
self.min = min
self.max = max
self.step = step
+ self.presets = presets
}
- public var sizes: [Int] {
- step > 0 && min <= max ? Array(stride(from: min, through: max, by: step)) : []
+ /// A size typed as `tokens`, as one this window takes: to the nearest step, within `min` and `max`.
+ public func fit(_ tokens: Int) -> Int {
+ let step = Swift.max(step, 1)
+ return Swift.min(Swift.max((tokens + step / 2) / step * step, min), max)
+ }
+
+ /// What the user typed, in thousands of tokens ("350", "350K", "1.5k"), as tokens; nil for anything else.
+ public static func typed(_ text: String) -> Int? {
+ var number = text.trimmingCharacters(in: .whitespaces)
+ if number.last == "k" || number.last == "K" { number.removeLast() }
+ // Past a billion thousands, no window holds it, and Int(_:) would trap.
+ guard let thousands = Double(number), thousands > 0, thousands < 1e9 else { return nil }
+ return Int((thousands * 1000).rounded())
}
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
index 7b3afbe5..e992094d 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json
@@ -1891,5 +1891,9 @@
"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"
+ "Claude Code and Codex bots only": "Nur für Claude-Code- und Codex-Bots",
+ "Custom size…": "Eigene Größe…",
+ "Custom size": "Eigene Größe",
+ "Thousands of tokens, rounded to 10K, up to what the model holds.": "In Tausend Tokens, auf 10K gerundet, bis zu dem, was das Modell fasst.",
+ "Or type a size in K:": "Oder eine Größe in K eingeben:"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
index 8170d3b3..5402880f 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json
@@ -1891,5 +1891,9 @@
"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"
+ "Claude Code and Codex bots only": "Solo para bots de Claude Code y Codex",
+ "Custom size…": "Tamaño personalizado…",
+ "Custom size": "Tamaño personalizado",
+ "Thousands of tokens, rounded to 10K, up to what the model holds.": "En miles de tokens, redondeado a 10K, hasta lo que admite el modelo.",
+ "Or type a size in K:": "O escribe un tamaño en K:"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
index d9e5acff..00f54674 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json
@@ -1891,5 +1891,9 @@
"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"
+ "Claude Code and Codex bots only": "Uniquement pour les bots Claude Code et Codex",
+ "Custom size…": "Taille personnalisée…",
+ "Custom size": "Taille personnalisée",
+ "Thousands of tokens, rounded to 10K, up to what the model holds.": "En milliers de tokens, arrondi à 10K, jusqu’à ce que le modèle peut contenir.",
+ "Or type a size in K:": "Ou saisissez une taille en K :"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json
index 6e4a2d48..4bfd0409 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/it.json
@@ -1891,5 +1891,9 @@
"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"
+ "Claude Code and Codex bots only": "Solo per i bot di Claude Code e Codex",
+ "Custom size…": "Dimensione personalizzata…",
+ "Custom size": "Dimensione personalizzata",
+ "Thousands of tokens, rounded to 10K, up to what the model holds.": "In migliaia di token, arrotondato a 10K, fino a quanto il modello può contenere.",
+ "Or type a size in K:": "Oppure digita una dimensione in K:"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
index 9a107454..de2988eb 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json
@@ -1891,5 +1891,9 @@
"Sizes show after the bot's next reply": "ボットの次の返信後にサイズを選べます",
"Only when full": "満杯になったときだけ",
"Summarize": "要約",
- "Claude Code and Codex bots only": "Claude Code と Codex のボットのみ"
+ "Claude Code and Codex bots only": "Claude Code と Codex のボットのみ",
+ "Custom size…": "カスタムサイズ…",
+ "Custom size": "カスタムサイズ",
+ "Thousands of tokens, rounded to 10K, up to what the model holds.": "千トークン単位で、10K 単位に丸められ、モデルが扱える上限までです。",
+ "Or type a size in K:": "サイズを K 単位で入力することもできます:"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
index 1d95d10a..75ef4f9a 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json
@@ -1891,5 +1891,9 @@
"Sizes show after the bot's next reply": "봇의 다음 답장 후에 크기를 고를 수 있습니다",
"Only when full": "가득 찼을 때만",
"Summarize": "압축",
- "Claude Code and Codex bots only": "Claude Code와 Codex 봇에서만"
+ "Claude Code and Codex bots only": "Claude Code와 Codex 봇에서만",
+ "Custom size…": "직접 입력…",
+ "Custom size": "직접 입력",
+ "Thousands of tokens, rounded to 10K, up to what the model holds.": "천 토큰 단위이며 10K 단위로 맞춰지고, 모델이 담을 수 있는 한도까지입니다.",
+ "Or type a size in K:": "크기를 K 단위로 직접 입력할 수도 있습니다:"
}
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 5bb749e1..b85d36e6 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/pt-BR.json
@@ -1891,5 +1891,9 @@
"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"
+ "Claude Code and Codex bots only": "Só para bots do Claude Code e do Codex",
+ "Custom size…": "Tamanho personalizado…",
+ "Custom size": "Tamanho personalizado",
+ "Thousands of tokens, rounded to 10K, up to what the model holds.": "Em milhares de tokens, arredondado para 10K, até o que o modelo comporta.",
+ "Or type a size in K:": "Ou digite um tamanho em K:"
}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json
index fa759c4f..1873f12d 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ru.json
@@ -1891,5 +1891,9 @@
"Sizes show after the bot's next reply": "Размеры появятся после следующего ответа бота",
"Only when full": "Только когда заполнится",
"Summarize": "Сжатие",
- "Claude Code and Codex bots only": "Только для ботов Claude Code и Codex"
+ "Claude Code and Codex bots only": "Только для ботов Claude Code и Codex",
+ "Custom size…": "Свой размер…",
+ "Custom size": "Свой размер",
+ "Thousands of tokens, rounded to 10K, up to what the model holds.": "В тысячах токенов, с округлением до 10K, не больше, чем вмещает модель.",
+ "Or type a size in K:": "Или введите размер в K:"
}
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 3aa87c28..6533a0f1 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json
@@ -1891,5 +1891,9 @@
"Sizes show after the bot's next reply": "Bot 下次回复后就能指定数量",
"Only when full": "不主动压缩",
"Summarize": "压缩",
- "Claude Code and Codex bots only": "仅适用于 Claude Code 和 Codex 的 bot"
+ "Claude Code and Codex bots only": "仅适用于 Claude Code 和 Codex 的 bot",
+ "Custom size…": "自定义数量…",
+ "Custom size": "自定义数量",
+ "Thousands of tokens, rounded to 10K, up to what the model holds.": "以千 token 为单位,会取到 10K 的倍数,最多到模型容纳的上限。",
+ "Or type a size in K:": "也可以直接输入数量(K):"
}
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 7ba168a2..12174c40 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json
@@ -1891,5 +1891,9 @@
"Sizes show after the bot's next reply": "Bot 下次回覆後就能指定數量",
"Only when full": "不主動壓縮",
"Summarize": "壓縮",
- "Claude Code and Codex bots only": "只適用於 Claude Code 和 Codex 的 bot"
+ "Claude Code and Codex bots only": "只適用於 Claude Code 和 Codex 的 bot",
+ "Custom size…": "自訂數量…",
+ "Custom size": "自訂數量",
+ "Thousands of tokens, rounded to 10K, up to what the model holds.": "以千 token 為單位,會取到 10K 的倍數,最多到模型裝得下的上限。",
+ "Or type a size in K:": "也可以直接輸入數量(K):"
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swift b/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swift
index 2d9fbb7b..73b9fd34 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/BotEditorView.swift
@@ -108,6 +108,7 @@ struct BotSettingsForm: View {
fallbackBanner
modelPicker
fallbackList
+ compactionPicker
}
.animation(Motion.reduced(Motion.layout, reduceMotion), value: bot?.agentStep)
if let error {
@@ -145,6 +146,14 @@ struct BotSettingsForm: View {
if draft.fallbacks != nil { FallbackList(draft: $draft, bot: bot) }
}
+ /// Only where the host summarizes this bot's chat (its bot says).
+ @ViewBuilder private var compactionPicker: some View {
+ if bot?.compaction != nil, draft.compaction != nil {
+ CompactionPicker(selection: Binding(get: { draft.compaction ?? .early }, set: { draft.compaction = $0 }),
+ range: bot?.compactionTokens)
+ }
+ }
+
@ViewBuilder private var sections: some View {
if part == .often { oftenSections } else { allSections }
}
@@ -189,8 +198,9 @@ struct BotSettingsForm: View {
Text(model.hostName).lineLimit(1)
}
if part == .all {
- modelPicker
+ modelPicker
fallbackList
+ compactionPicker
}
ValueRow("Workspace", detail: draft.cwd.isEmpty
? "This bot has its own space for files. It can work in other folders when you ask."
@@ -215,11 +225,6 @@ 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
index c2172bf3..ec75694d 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Bots/CompactionPicker.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Bots/CompactionPicker.swift
@@ -6,6 +6,8 @@ struct CompactionPicker: View {
@Binding var selection: CompactionThreshold
/// Nil until the agent has told its window.
let range: TokenRange?
+ @State private var typing = false
+ @State private var typed = ""
private static let presets: [(CompactionThreshold, String)] =
[(.early, "Early (default)"), (.nearLimit, "Near the limit"), (.off, "Only when full")]
@@ -22,17 +24,30 @@ struct CompactionPicker: View {
.outlinedPill()
}
}
+ .codyncDialog("Custom size", isPresented: $typing, message: "Thousands of tokens, rounded to 10K, up to what the model holds.",
+ field: DialogField(range.map { "\($0.min / 1000)–\($0.max / 1000)" } ?? "", text: $typed, keyboard: .numbersAndPunctuation)) {
+ let tokens = TokenRange.typed(typed)
+ return [DialogAction("Save", enabled: tokens != nil) {
+ if let range, let tokens { selection = .tokens(range.fit(tokens)) }
+ }]
+ }
}
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 {
+ guard let range else {
return rows + [MenuItem("Sizes show after the bot's next reply", divider: true, enabled: false) {}]
}
- let picks = sizes.map { tokens in
+ let picks = range.presets.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)]
+ var own = false
+ if case .tokens(let tokens) = selection { own = !range.presets.contains(tokens) }
+ let custom = MenuItem("Custom size…", selected: own, divider: !picks.isEmpty) {
+ if case .tokens(let tokens) = selection { typed = "\(tokens / 1000)" } else { typed = "" }
+ typing = true
+ }
+ return rows + [MenuItem("Set a size", divider: true, submenu: picks + [custom])]
}
private var label: String {
diff --git a/apps/ios/Kit/Sources/CodyncUI/Dialog.swift b/apps/ios/Kit/Sources/CodyncUI/Dialog.swift
index dfcc9b47..00b86d3a 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Dialog.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Dialog.swift
@@ -9,11 +9,14 @@ public struct DialogAction: Identifiable {
public let id = UUID()
public var title: String
public var destructive: Bool
+ /// Off while what the dialog asks for isn't valid yet (a field that doesn't read).
+ public var enabled: Bool
public var action: () -> Void
- public init(_ title: String, destructive: Bool = false, action: @escaping () -> Void) {
+ public init(_ title: String, destructive: Bool = false, enabled: Bool = true, action: @escaping () -> Void) {
self.title = title
self.destructive = destructive
+ self.enabled = enabled
self.action = action
}
}
@@ -22,10 +25,12 @@ public struct DialogAction: Identifiable {
public struct DialogField {
public var placeholder: String
public var text: Binding<String>
+ public var keyboard: UIKeyboardType
- public init(_ placeholder: String, text: Binding<String>) {
+ public init(_ placeholder: String, text: Binding<String>, keyboard: UIKeyboardType = .default) {
self.placeholder = placeholder
self.text = text
+ self.keyboard = keyboard
}
}
@@ -112,6 +117,7 @@ private struct DialogCard: View {
.multilineTextAlignment(.center)
if let field {
TextField(L10n.tr(field.placeholder), text: field.text)
+ .keyboardType(field.keyboard)
.textFieldStyle(.plain)
.font(.body)
.foregroundStyle(Palette.text)
@@ -131,6 +137,7 @@ private struct DialogCard: View {
Text(L10n.tr(action.title)).frame(maxWidth: .infinity)
}
.buttonStyle(DialogButtonStyle(destructive: action.destructive, prominent: true))
+ .disabled(!action.enabled)
}
if let cancel {
Button(action: close) { Text(L10n.tr(cancel)).frame(maxWidth: .infinity) }
@@ -145,6 +152,8 @@ private struct DialogCard: View {
.shadow(color: .black.opacity(0.25), radius: 24, y: 10)
.padding(24)
}
+ // One modal container: on the bare stack the trait lands on every element and only the last (Cancel) stays reachable.
+ .accessibilityElement(children: .contain)
.accessibilityAddTraits(.isModal)
}
@@ -155,7 +164,7 @@ private struct DialogCard: View {
}
private func run(_ action: DialogAction) {
- guard !closed else { return }
+ guard !closed, action.enabled else { return }
close()
action.action()
}
@@ -164,6 +173,7 @@ private struct DialogCard: View {
private struct DialogButtonStyle: ButtonStyle {
let destructive: Bool
let prominent: Bool
+ @Environment(\.isEnabled) private var isEnabled
func makeBody(configuration: Configuration) -> some View {
configuration.label
@@ -171,7 +181,7 @@ private struct DialogButtonStyle: ButtonStyle {
.foregroundStyle(destructive ? Color.white : (prominent ? Palette.onAccent : Palette.text))
.padding(.vertical, 12)
.background(destructive ? Palette.danger : (prominent ? Palette.accentFill : Palette.bubbleUser), in: Capsule())
- .opacity(configuration.isPressed ? 0.85 : 1)
+ .opacity(isEnabled ? (configuration.isPressed ? 0.85 : 1) : 0.4)
.scaleEffect(configuration.isPressed ? Motion.pressScale : 1)
.animation(Motion.press, value: configuration.isPressed)
.contentShape(Capsule())
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/CompactionTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/CompactionTests.swift
index f3a3044d..42180c0d 100644
--- a/apps/ios/Kit/Tests/CodyncKitTests/CompactionTests.swift
+++ b/apps/ios/Kit/Tests/CodyncKitTests/CompactionTests.swift
@@ -15,8 +15,8 @@ private func bot(_ extra: String) throws -> Bot {
#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])
+ let sized = try bot(#","compaction":"early","compactionTokens":{"min":50000,"max":260000,"step":10000,"presets":[100000,200000]}"#)
+ #expect(sized.compactionTokens == TokenRange(min: 50_000, max: 260_000, step: 10_000, presets: [100_000, 200_000]))
#expect(try bot(#","compaction":"early","compactionTokens":null"#).compactionTokens == nil, "window not known yet")
}
@@ -38,3 +38,14 @@ private func bot(_ extra: String) throws -> Bot {
#expect(base.rebased(from: base, onto: fresh).compaction == .off)
#expect(draft.rebased(from: base, onto: fresh).compaction == .nearLimit)
}
+
+@Test func aTypedSizeFitsTheWindow() {
+ let range = TokenRange(min: 50_000, max: 960_000, step: 10_000)
+ #expect([354_000, 355_000, 10_000, 5_000_000].map(range.fit) == [350_000, 360_000, 50_000, 960_000])
+ #expect(TokenRange.typed("350") == 350_000)
+ #expect(TokenRange.typed("350k") == 350_000)
+ #expect(TokenRange.typed(" 1.5K ") == 1_500)
+ for bad in ["abc", "", "0", "-5", "1e300", "nan"] {
+ #expect(TokenRange.typed(bad) == nil, "\(bad)")
+ }
+}
diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.md
index c0a36877..e9de03db 100644
--- a/apps/ios/WhatsNew.md
+++ b/apps/ios/WhatsNew.md
@@ -8,10 +8,10 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o
## 2.42.0
### zh-Hant
-- bot 設定新增「壓縮對話」:選擇 Codync 什麼時候把長對話壓縮成摘要。可以選提早(預設)、接近上限、不主動壓縮,或以 10K 為一級自己指定數量,最多到模型裝得下的上限。適用於 Claude Code 和 Codex 的 bot。
+- bot 詳情的「智慧體」區塊新增「壓縮對話」:選擇 Codync 什麼時候把長對話壓縮成摘要。可以選提早(預設)、接近上限、不主動壓縮,或指定數量:從 100K、200K… 裡挑,或自己輸入,最多到模型裝得下的上限。適用於 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.
+- New Summarize long chats setting in a bot's Agent section: choose when Codync summarizes a long chat. Pick Early (default), Near the limit, Only when full, or a size: 100K, 200K and so on, or one you type, up to what the model holds. For Claude Code and Codex bots.
## 2.41.0
### zh-Hant
diff --git a/apps/maestro/compaction.yaml b/apps/maestro/compaction.yaml
index e49bad73..57fe5353 100644
--- a/apps/maestro/compaction.yaml
+++ b/apps/maestro/compaction.yaml
@@ -1,6 +1,7 @@
-# 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,
+# A bot's Summarize long chats setting on the phones, in the Agent card of its details: once its agent has replied and
+# told its window, the menu has the three choices and Set a size, which lists sizes by 100K up to what the window holds
+# and Custom size… for one typed in; a size picked or typed 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 \
@@ -35,8 +36,11 @@ onFlowComplete:
- extendedWaitUntil:
visible: "ok"
timeout: 20000
+# Not on the Settings page: on the Details page, where the details open.
- tapOn: "${output.bot.name}, view details"
- tapOn: "Settings"
+- assertNotVisible: "Summarize long chats"
+- tapOn: "Details"
# 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"
@@ -45,15 +49,28 @@ onFlowComplete:
- assertVisible: "Near the limit"
- assertVisible: "Only when full"
- tapOn: "Set a size"
-- assertVisible: "50K"
-- tapOn: "120K"
-- assertVisible: "120K"
+- assertVisible: "900K"
+- tapOn: "100K"
+- assertVisible: "100K"
+- runScript:
+ file: compaction.js
+ env:
+ STORED: "100000"
+- tapOn: "100K"
+- tapOn: "Set a size"
+- tapOn: "Custom size…"
+- assertVisible: "Custom size"
+- eraseText
+# Rounded to the nearest 10K.
+- inputText: "354"
+- tapOn: "Save"
+- assertVisible: "350K"
- takeScreenshot: compaction-size
- runScript:
file: compaction.js
env:
- STORED: "120000"
-- tapOn: "120K"
+ STORED: "350000"
+- tapOn: "350K"
- tapOn: "Only when full"
- assertVisible: "Only when full"
- runScript:
diff --git a/docs/design/bot-memory.md b/docs/design/bot-memory.md
index 40e155c4..3fa5efab 100644
--- a/docs/design/bot-memory.md
+++ b/docs/design/bot-memory.md
@@ -439,9 +439,10 @@ config, `codync_mem::compaction::Threshold`) that moves the end-of-turn trigger:
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
+the loop guard apply to every setting but Only when full. The apps take the sizes from `compactionTokens`
+(`{min, max, step, presets}`: the bounds a typed size is rounded and held to, and the 100k multiples a menu
+lists), 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.
diff --git a/docs/features/context-and-memory.md b/docs/features/context-and-memory.md
index 2655170a..29b1de8d 100644
--- a/docs/features/context-and-memory.md
+++ b/docs/features/context-and-memory.md
@@ -169,10 +169,11 @@ Claude Code's own memory; the rules live in the `codync-mem` crate, and `chat/me
`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`
+ host), or a size from 50k up to the window less 40k (the apps list 100k steps and take any other size typed,
+ rounded to 10k). 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
+ `compactionTokens` (`{min, max, step, presets}`, `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.
diff --git a/host/crates/memory/src/compaction/threshold.rs b/host/crates/memory/src/compaction/threshold.rs
index 40d5fa7b..6e797598 100644
--- a/host/crates/memory/src/compaction/threshold.rs
+++ b/host/crates/memory/src/compaction/threshold.rs
@@ -11,6 +11,8 @@ const STEP: u64 = 10_000;
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;
+/// The sizes a menu lists are multiples of this; any other size is the user's to type.
+const PRESET_STEP: u64 = 100_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.
@@ -104,17 +106,31 @@ impl Threshold {
}
}
-/// The sizes a user may set in one window: `min` to `max` tokens by `step`.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
+/// The sizes a user may set in one window: `min` to `max` tokens by `step`, and the few a menu lists.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Sizes {
pub min: u64,
pub max: u64,
pub step: u64,
+ pub presets: Vec<u64>,
+}
+
+impl Sizes {
+ /// A size typed as `tokens`, as one this window takes: to the nearest step, within `min` and `max`.
+ pub fn fit(&self, tokens: u64) -> u64 {
+ let step = self.step.max(1);
+ (tokens.saturating_add(step / 2) / step * step).max(self.min).min(self.max)
+ }
}
/// 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 })
+ max_tokens(window).map(|max| Sizes {
+ min: MIN_TOKENS,
+ max,
+ step: STEP,
+ presets: (1..=max / PRESET_STEP).map(|n| n * PRESET_STEP).collect(),
+ })
}
/// The largest size a window allows, leaving the compaction turn its headroom.
@@ -144,8 +160,12 @@ mod tests {
#[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));
+ let million = sizes(1_000_000).expect("a 1M window offers sizes");
+ assert_eq!((million.min, million.max, million.step), (50_000, 960_000, 10_000));
+ assert_eq!(million.presets, (1..=9).map(|n| n * 100_000).collect::<Vec<_>>(), "100K to 900K");
+ assert_eq!(sizes(272_000).map(|s| (s.max, s.presets)), Some((230_000, vec![100_000, 200_000])));
+ assert_eq!(sizes(130_000).map(|s| s.presets), Some(vec![]), "90K at most: only a size of one's own");
+ assert_eq!([354_000, 355_000, 10_000, 5_000_000].map(|n| million.fit(n)), [350_000, 360_000, 50_000, 960_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:?}");
diff --git a/host/src/hub/sync.rs b/host/src/hub/sync.rs
index 7323eab0..bc58f715 100644
--- a/host/src/hub/sync.rs
+++ b/host/src/hub/sync.rs
@@ -89,7 +89,7 @@ mod tests {
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})
+ json!({"min": 50_000, "max": 960_000, "step": 10_000, "presets": (1..=9).map(|n| n * 100_000).collect::<Vec<u64>>()})
);
let gemini = hub.bot_value_for_test("g");
diff --git a/host/src/tui/app/bot.rs b/host/src/tui/app/bot.rs
index 02694fed..cd35fef8 100644
--- a/host/src/tui/app/bot.rs
+++ b/host/src/tui/app/bot.rs
@@ -62,8 +62,8 @@ pub struct Bot {
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>,
+ /// The sizes it may take; `None` until the agent has told its window.
+ pub compaction_sizes: Option<codync_mem::compaction::Sizes>,
/// 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.
@@ -101,17 +101,6 @@ 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,
@@ -220,7 +209,7 @@ impl Bot {
.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"]),
+ compaction_sizes: serde_json::from_value(v["compactionTokens"].clone()).ok().flatten(),
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 06ec72cc..4c8739a6 100644
--- a/host/src/tui/app/forms.rs
+++ b/host/src/tui/app/forms.rs
@@ -54,6 +54,7 @@ impl App {
reachable_by_assistants: b.reachable_by_assistants,
compaction: b.compaction,
compaction_sizes: b.compaction_sizes.clone(),
+ compaction_typed: String::new(),
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(),
@@ -141,6 +142,8 @@ impl App {
f.model = Editor::with(&m);
}
}
+ KeyCode::Char(c) if field == Field::Compaction && c.is_ascii_digit() => f.type_compaction(Some(c)),
+ KeyCode::Backspace if field == Field::Compaction => f.type_compaction(None),
KeyCode::Enter => self.save_form(&mut f),
KeyCode::Left | KeyCode::Right | KeyCode::Char(' ')
if matches!(
@@ -288,7 +291,10 @@ 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,
+ "compaction": self.compaction.map(|at| match (at, &self.compaction_sizes) {
+ (Threshold::Tokens(n), Some(sizes)) => Threshold::Tokens(sizes.fit(n)),
+ _ => at,
+ }),
"avatarColor": COLORS[self.color],
"avatarShape": SHAPES[self.shape],
"connectors": self.connectors.iter().filter(|t| t.on).map(|t| t.id.clone()).collect::<Vec<_>>(),
@@ -296,17 +302,39 @@ impl Form {
})
}
- /// When Codync summarizes the chat, in the order ← → steps through: the three choices, then each size.
+ /// When Codync summarizes the chat, in the order ← → steps through: the three choices, then the sizes a menu lists.
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()
+ let presets = self.compaction_sizes.iter().flat_map(|s| s.presets.iter().map(|&n| Threshold::Tokens(n)));
+ [Threshold::Early, Threshold::NearLimit, Threshold::Off].into_iter().chain(presets).collect()
+ }
+
+ /// A digit typed into the size (thousands of tokens), or Backspace (`None`); held to the window's sizes on save.
+ fn type_compaction(&mut self, digit: Option<char>) {
+ if self.compaction.is_none() || self.compaction_sizes.is_none() {
+ return;
+ }
+ match digit {
+ Some(c) if self.compaction_typed.len() < 4 => self.compaction_typed.push(c),
+ Some(_) => return,
+ None => {
+ self.compaction_typed.pop();
+ }
+ }
+ if let Ok(k) = self.compaction_typed.parse::<u64>() {
+ self.compaction = Some(Threshold::Tokens(k * 1000));
+ }
}
fn cycle_compaction(&mut self, d: isize) {
let Some(now) = self.compaction else { return };
- let choices = self.compaction_choices();
+ self.compaction_typed.clear();
+ let mut choices = self.compaction_choices();
+ // A size of one's own steps from its place among the presets.
+ if let Threshold::Tokens(n) = now
+ && !choices.contains(&now)
+ {
+ choices.insert(choices.partition_point(|c| !matches!(c, Threshold::Tokens(p) if *p > n)), now);
+ }
let i = choices.iter().position(|c| *c == now).unwrap_or(0);
self.compaction = Some(choices[cycle(i, d, choices.len())]);
}
@@ -381,22 +409,42 @@ 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}});
+ /// Feeds `keys` to the editor, which must stay open.
+ fn press(app: &mut App, mut f: Box<Form>, keys: impl IntoIterator<Item = KeyCode>) -> Box<Form> {
+ for key in keys {
+ let Some(Overlay::Form(next)) = app.form_key(f, KeyEvent::from(key)) else { panic!("the editor stays") };
+ f = next;
+ }
+ f
+ }
+
+ /// The editor of a Claude Code bot on `compaction`, at the compaction field, in a window of up to 260K.
+ fn compaction_editor(app: &mut App, compaction: &Value) -> Box<Form> {
+ let bot = json!({"id": "b", "name": "B", "backend": "claude", "compaction": compaction,
+ "compactionTokens": {"min": 50_000, "max": 260_000, "step": 10_000, "presets": [100_000, 200_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") };
+ f
+ }
+
+ #[tokio::test]
+ async fn the_compaction_threshold_steps_through_choices_then_sizes() {
+ let mut app = test_app();
+ let f = compaction_editor(&mut app, &json!("off"));
+ let f = press(&mut app, f, [KeyCode::Right]);
+ assert_eq!(f.changes(), json!({"compaction": 100_000}));
+ let f = press(&mut app, f, [KeyCode::Left]);
assert_eq!(f.changes(), json!({}));
- assert_eq!(f.compaction_choices().len(), 6, "early, near the limit, only when full, 50K, 60K, 70K");
+ assert_eq!(f.compaction_choices().len(), 5, "early, near the limit, only when full, 100K, 200K");
+
+ for (key, next) in [(KeyCode::Right, 200_000), (KeyCode::Left, 100_000)] {
+ let f = compaction_editor(&mut app, &json!(150_000));
+ let f = press(&mut app, f, [key]);
+ assert_eq!(f.changes(), json!({"compaction": next}), "a size of one's own steps from its place");
+ }
let other = json!({"id": "g", "name": "G", "backend": "gemini", "compaction": null});
app.bots.insert("g".into(), Bot::parse(&other).expect("a bot"));
@@ -404,10 +452,22 @@ mod tests {
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") };
+ let f = press(&mut app, f, [KeyCode::Right]);
assert_eq!(f.changes(), json!({}), "nothing to choose where Codync doesn't summarize");
}
+ #[tokio::test]
+ async fn a_typed_size_is_fitted_on_save() {
+ let mut app = test_app();
+ let f = compaction_editor(&mut app, &json!("off"));
+ let f = press(&mut app, f, "35490".chars().map(KeyCode::Char));
+ assert_eq!(f.compaction, Some(Threshold::Tokens(3_549_000)), "as typed, four digits at most");
+ let f = press(&mut app, f, [KeyCode::Backspace]);
+ assert_eq!(f.changes(), json!({"compaction": 260_000}), "held to the largest size the window takes");
+ let f = press(&mut app, f, [KeyCode::Backspace; 3].into_iter().chain("155".chars().map(KeyCode::Char)));
+ assert_eq!(f.changes(), json!({"compaction": 160_000}), "to the nearest 10K");
+ }
+
#[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 43a2cb6e..16b40e3c 100644
--- a/host/src/tui/app/tests.rs
+++ b/host/src/tui/app/tests.rs
@@ -182,3 +182,20 @@ async fn the_settings_form_scrolls_to_keep_the_focused_field_in_sight() {
assert!(!drawn(0).contains("Skills"), "more fields than the form has rows");
assert!(drawn(FIELDS.len() - 1).contains("Skills"), "scrolled to the focused one");
}
+
+#[tokio::test]
+async fn a_long_field_help_wraps_to_a_second_row() {
+ use ratatui::{Terminal, backend::TestBackend};
+ let mut app = test_app();
+ let bot = json!({"id": "b", "name": "B", "backend": "claude", "compaction": "early",
+ "compactionTokens": {"min": 50_000, "max": 960_000, "step": 10_000, "presets": [100_000]}});
+ app.bots.insert("b".into(), Bot::parse(&bot).expect("valid bot"));
+ app.selected = Some("b".into());
+ app.edit_bot();
+ let Some(Overlay::Form(f)) = app.overlays.last_mut() else { panic!("the editor opens") };
+ f.field = FIELDS.iter().position(|x| *x == Field::Compaction).expect("a compaction 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");
+ let drawn = terminal.backend().buffer().content().iter().map(ratatui::buffer::Cell::symbol).collect::<String>();
+ assert!(drawn.contains("50K–960K"), "the sizes one can type, after a description longer than a row");
+}
diff --git a/host/src/tui/app/ui.rs b/host/src/tui/app/ui.rs
index bbd0b267..cdccb5bf 100644
--- a/host/src/tui/app/ui.rs
+++ b/host/src/tui/app/ui.rs
@@ -200,9 +200,9 @@ pub const FIELDS: [Field; 20] = [
Field::Fast,
Field::Fallbacks,
Field::SelfFallbacks,
+ Field::Compaction,
Field::Folder,
Field::Approvals,
- Field::Compaction,
Field::Notify,
Field::Computer,
Field::Team,
@@ -246,7 +246,10 @@ pub struct Form {
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>,
+ /// `None` until the agent has told its window.
+ pub compaction_sizes: Option<codync_mem::compaction::Sizes>,
+ /// The digits of a size being typed, in thousands of tokens.
+ pub compaction_typed: String,
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 d721317d..84df89c9 100644
--- a/host/src/tui/view/forms.rs
+++ b/host/src/tui/view/forms.rs
@@ -3,11 +3,12 @@
use ratatui::buffer::Buffer;
use ratatui::layout::{Position, Rect};
use ratatui::style::{Modifier, Style};
+use ratatui::text::Span;
use super::super::app::{App, COLORS, Editor, FIELDS, Field, Form, GroupField, GroupForm, SHAPES, tilde};
use super::super::l10n::tr;
use super::super::manage::Page;
-use super::super::md::{truncate, width as w};
+use super::super::md::{truncate, width as w, wrap};
use super::super::sheets::page_tabs;
use super::buffer::{centered, frame_box, put, put_line, restyle, rput, u};
use super::chat::composer_lines;
@@ -35,6 +36,9 @@ fn created_by(app: &App, id: &str) -> Option<String> {
Some(format!("created by {creator} · {} {day}", MONTHS[month]))
}
+/// The rows under the fields: the help, up to two, and the buttons.
+const FOOTER: u16 = 3;
+
/// The rows a field's value takes.
fn field_rows(field: Field) -> u16 {
if field == Field::Instructions { 3 } else { 1 }
@@ -66,8 +70,11 @@ fn field_help(app: &App, f: &Form, agent_name: &str) -> Option<(String, Style)>
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()
+ let sizes = f.compaction_sizes.as_ref().map_or_else(
+ || tr("Sizes show after the bot's next reply").into_owned(),
+ |s| format!("{} {}K–{}K", tr("Or type a size in K:"), s.min / 1000, s.max / 1000),
+ );
+ [about.into_owned(), sizes].join(" ")
}
Field::Team => {
"Let this bot create bots and change any bot's setup, its own included. The bots it creates can too.".to_owned()
@@ -103,7 +110,7 @@ pub(super) fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {
let mut y = inner.y + 1;
let agent_name = app.agent_name(&f.backend);
// 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 room = inner.bottom().saturating_sub(FOOTER).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;
@@ -346,13 +353,17 @@ pub(super) fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {
}
}
y += rows + 1;
- if y >= inner.bottom().saturating_sub(2) {
+ if y >= inner.bottom().saturating_sub(FOOTER) {
break;
}
}
let by = inner.bottom() - 1;
if let Some((line, style)) = field_help(app, f, &agent_name) {
- put(buf, inner.x, by - 1, inner.width, &line, style.patch(t.panel));
+ let lines = wrap(&[Span::styled(line, style.patch(t.panel))], usize::from(inner.width), &[], &[]);
+ let shown = &lines[..lines.len().min(usize::from(FOOTER - 1))];
+ for (j, l) in shown.iter().enumerate() {
+ put_line(buf, inner.x, by.saturating_sub(u(shown.len() - j)), inner.width, l);
+ }
}
let save = if f.saving {
" … Saving "
diff --git a/host/tests/compaction_e2e.rs b/host/tests/compaction_e2e.rs
index 08f3408f..e6e38f52 100644
--- a/host/tests/compaction_e2e.rs
+++ b/host/tests/compaction_e2e.rs
@@ -62,7 +62,10 @@ async fn the_users_threshold_decides_when_the_host_compacts() {
}
};
assert_eq!(shown["compaction"], "early");
- assert_eq!(shown["compactionTokens"], json!({"min": 50_000, "max": 960_000, "step": 10_000}));
+ assert_eq!(
+ shown["compactionTokens"],
+ json!({"min": 50_000, "max": 960_000, "step": 10_000, "presets": (1..=9).map(|n| n * 100_000).collect::<Vec<u64>>()})
+ );
host.call("updateBot", json!({"id": bot, "compaction": 300_000})).await;
host.reply(&bot, "USAGE 210000 SIZE 1000000").await;
diff --git a/web/content/docs/bots.mdx b/web/content/docs/bots.mdx
index 1702eaa2..0e9020a6 100644
--- a/web/content/docs/bots.mdx
+++ b/web/content/docs/bots.mdx
@@ -83,16 +83,16 @@ 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.
+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 in the Agent section, under the agent and its fallbacks (on the Details page of a chat's details).
| 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. |
+| **Set a size** | At the size you pick: 100K, 200K and so on up to the largest the window allows, or **Custom size…** to type your own, in thousands of tokens (from 50K, rounded to 10K). |
-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.
+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 sits under the fallbacks: ←/→ goes through the same choices, then each listed size, and typing digits sets a size of your own in K.
## Activity