diff --git a/docs/configuration.md b/docs/configuration.md index f3a133194..da3396140 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -2498,9 +2498,11 @@ The deprecated `agents.defaults.failOnToolError` field is silently ignored when ## Auto Compact -The WebUI has no control for the idle-compaction threshold or scan interval. Configure these fields directly in `config.json`; use `/compact` for an immediate compaction. +Configure **Auto-compact idle sessions** and **Idle timeout** in **Settings → System → Sessions**, then restart the gateway to apply changes. The scan interval is configured directly in `config.json`; use `/compact` for an immediate compaction. -When a session is idle for longer than a configured threshold, nanobot summarizes its conversation context. When you return, the model receives that summary and new messages instead of replaying the messages covered by the summary. The original conversation remains in your saved chat history, but even its most recent messages are no longer included verbatim in the model's context after idle compaction. +When a session is idle for longer than the configured timeout, nanobot summarizes its conversation context to reduce input token usage on later requests. Summarization is lossy and may omit details. When you return, the model receives that summary and new messages instead of replaying the messages covered by the summary. The original conversation remains in your saved chat history, but even its most recent messages are no longer included verbatim in the model's context after idle compaction. + +If your provider retains its prompt cache longer, you can increase the idle timeout to delay compaction. Set the timeout to `0` to disable idle compaction if preserving the full context matters more than reducing subsequent input usage. ```json { diff --git a/nanobot/webui/settings_runtime.py b/nanobot/webui/settings_runtime.py index 05a1540b3..398eb695a 100644 --- a/nanobot/webui/settings_runtime.py +++ b/nanobot/webui/settings_runtime.py @@ -20,6 +20,7 @@ RUNTIME_CONFIG_PATHS = ( "agents.defaults.timezone", "agents.defaults.timezone_mode", "agents.defaults.unified_session", + "agents.defaults.session_ttl_minutes", "agents.defaults.max_tool_iterations", "agents.defaults.max_concurrent_subagents", "agents.defaults.max_tool_result_chars", diff --git a/tests/webui/fixtures/runtime-config-keys.json b/tests/webui/fixtures/runtime-config-keys.json index 750fb55fd..498eb4b6e 100644 --- a/tests/webui/fixtures/runtime-config-keys.json +++ b/tests/webui/fixtures/runtime-config-keys.json @@ -2,6 +2,7 @@ "agents.defaults.timezone", "agents.defaults.timezone_mode", "agents.defaults.unified_session", + "agents.defaults.session_ttl_minutes", "agents.defaults.max_tool_iterations", "agents.defaults.max_concurrent_subagents", "agents.defaults.max_tool_result_chars", diff --git a/tests/webui/test_settings_runtime.py b/tests/webui/test_settings_runtime.py index fe3a6c9af..2dee494a2 100644 --- a/tests/webui/test_settings_runtime.py +++ b/tests/webui/test_settings_runtime.py @@ -13,6 +13,7 @@ from nanobot.webui.settings_runtime import ( runtime_config_payload, update_runtime_config, ) +from nanobot.webui.settings_services import WebUISettingsServices def test_web_proxy_roundtrip_while_disabled_preserves_model_proxy(tmp_path): @@ -66,6 +67,13 @@ def test_runtime_patch_persists_and_preserves_other_domains(tmp_path): {"tools.exec": {"enable": False}}, {"agents.defaults.max_concurrent_subagents": 0}, {"agents.defaults.max_tool_iterations": True}, + {"agents.defaults.session_ttl_minutes": -1}, + {"agents.defaults.session_ttl_minutes": 1.5}, + {"agents.defaults.session_ttl_minutes": 15.0}, + {"agents.defaults.session_ttl_minutes": "15"}, + {"agents.defaults.session_ttl_minutes": True}, + {"agents.defaults.session_ttl_minutes": False}, + {"agents.defaults.session_ttl_minutes": None}, {"tools.exec.timeout": -1}, {"tools.exec.timeout": 86401}, {"tools.exec.timeout": "60"}, @@ -194,3 +202,49 @@ def test_sandbox_backend_persists_with_path_permissions(tmp_path, backend): assert saved.sandbox_rw_binds == ["shared/write"] assert payload["runtime_config"]["tools.exec.sandbox"] == backend assert payload["requires_restart"] + + +def test_idle_compaction_settings_roundtrip_and_restart_contract(tmp_path): + path = tmp_path / "config.json" + config = Config() + config.providers.openai.api_key = "${PRIVATE_API_KEY}" + save_config(config, path) + services = WebUISettingsServices.create(path) + key = "agents.defaults.session_ttl_minutes" + assert runtime_config_payload(config)[key] == 15 + + for minutes in (0, 720, 721, 37, 15): + payload = services.mutate(update_runtime_config_settings, {key: minutes}) + assert payload["runtime_config"][key] == minutes + assert payload["requires_restart"] is True + saved = load_config(path) + assert saved.agents.defaults.session_ttl_minutes == minutes + assert saved.agents.defaults.idle_compact_check_interval_seconds == 60 + assert saved.providers.openai.api_key == "${PRIVATE_API_KEY}" + defaults = json.loads(path.read_text(encoding="utf-8"))["agents"]["defaults"] + assert defaults["idleCompactAfterMinutes"] == minutes + assert "sessionTtlMinutes" not in defaults + assert "session_ttl_minutes" not in defaults + + unchanged = services.mutate(update_runtime_config_settings, {key: minutes}) + assert unchanged["runtime_config"][key] == minutes + assert unchanged["requires_restart"] is False + + +def test_idle_compaction_legacy_config_can_be_read_and_updated(tmp_path): + path = tmp_path / "config.json" + path.write_text(json.dumps({"agents": {"defaults": { + "sessionTtlMinutes": 720, "idleCompactCheckIntervalSeconds": 91, + }}}), encoding="utf-8") + key = "agents.defaults.session_ttl_minutes" + assert runtime_config_payload(load_config(path))[key] == 720 + + payload = update_runtime_config_settings({key: 0}, config_path=path) + assert payload["runtime_config"][key] == 0 + assert payload["requires_restart"] is True + saved = load_config(path) + assert saved.agents.defaults.session_ttl_minutes == 0 + assert saved.agents.defaults.idle_compact_check_interval_seconds == 91 + defaults = json.loads(path.read_text(encoding="utf-8"))["agents"]["defaults"] + assert defaults["idleCompactAfterMinutes"] == 0 + assert "sessionTtlMinutes" not in defaults diff --git a/webui/browser/fixture.tsx b/webui/browser/fixture.tsx index 4f0f51de7..6384955ae 100644 --- a/webui/browser/fixture.tsx +++ b/webui/browser/fixture.tsx @@ -30,6 +30,7 @@ import { ThreadLoadingFixture } from "./thread-loading-fixture"; import { AnswerOrderFixture } from "./answer-order-fixture"; import { SidebarActivityFixture } from "./sidebar-activity-fixture"; import { HistoryHydrationFixture } from "./history-hydration-fixture"; +import { IdleCompactionFixture, installIdleCompactionApi } from "./idle-compaction-fixture"; const history: UIMessage[] = [ { id: "question", role: "user", content: "Earlier question", createdAt: 1_700_000_000_000 }, @@ -168,6 +169,7 @@ function AppsFixture() { />; } if (parameters.get("case") === "skeleton-additions") installSkeletonPreviewApi(); +if (parameters.get("case") === "idle-compaction") installIdleCompactionApi(); await initializeI18n(); createRoot(document.getElementById("root")!).render( {parameters.get("case") === "answer-order" @@ -180,6 +182,8 @@ createRoot(document.getElementById("root")!).render( ? : parameters.get("case") === "typography" ? + : parameters.get("case") === "idle-compaction" + ? : parameters.get("case") === "history-hydration" ? : parameters.get("case") === "history-boundary" diff --git a/webui/browser/idle-compaction-fixture.tsx b/webui/browser/idle-compaction-fixture.tsx new file mode 100644 index 000000000..fec66b1bc --- /dev/null +++ b/webui/browser/idle-compaction-fixture.tsx @@ -0,0 +1,65 @@ +import { useState } from "react"; + +import { SettingsView } from "@/components/settings/SettingsView"; +import { RUNTIME_CONFIG_FIELDS } from "@/components/settings/system/runtime-config-fields"; +import { settings } from "@/dev/gallery/settings"; +import { NanobotClient } from "@/lib/nanobot-client"; +import type { RuntimeConfigValue, SettingsPayload } from "@/lib/types"; +import { ClientProvider } from "@/providers/ClientProvider"; + +const path = "agents.defaults.session_ttl_minutes"; +const storageKey = "fixture.idle-compaction-minutes"; +const client = new NanobotClient({ url: "ws://127.0.0.1:1", reconnect: false }); +let failNext = false; +const initial: SettingsPayload = { + ...settings, + runtime_config: Object.fromEntries(RUNTIME_CONFIG_FIELDS.map((field) => [field.path, + field.kind === "boolean" ? false : field.kind === "toggle" ? field.options?.[0] ?? "" + : field.kind === "list" ? [] : field.kind === "number" ? 20 : field.kind === "duration" ? 60 : "", + ])), +}; +initial.runtime_config![path] = Number(localStorage.getItem(storageKey) ?? 720); +let persisted = initial; + +client.requestMutation = async (action: string, payload?: Record): Promise => { + if (action !== "settings.runtime_config.update") throw new Error(`Unexpected mutation: ${action}`); + if (failNext) { + failNext = false; + throw new Error("Fixture save failed"); + } + const values = payload?.values as Record; + if (path in values) localStorage.setItem(storageKey, String(values[path])); + persisted = { ...persisted, runtime_config: { ...persisted.runtime_config, ...values }, requires_restart: true, + restart_required_sections: ["runtime"] }; + return persisted as T; +}; + +export function installIdleCompactionApi() { + const fetch = window.fetch.bind(window); + window.fetch = async (input, init) => { + const url = new URL(input instanceof Request ? input.url : String(input), location.href); + if (url.origin !== location.origin || !url.pathname.startsWith("/api/")) return fetch(input, init); + const bodies: Record = { + "/api/settings": persisted, + "/api/settings/nanobot-features": { features: [], enabled_count: 0, requires_restart: false }, + "/api/settings/api-service": { installed: false, running: false, managed: false, host: "127.0.0.1", + port: 8900, timeout: 120, endpoint: "http://127.0.0.1:8900/v1", command: "nanobot serve" }, + }; + return Response.json(bodies[url.pathname] ?? {}); + }; +} + +export function IdleCompactionFixture() { + const [snapshot, setSnapshot] = useState(initial); + return +
+
+ + {String(snapshot.runtime_config?.[path])} +
+ {}} onBackToChat={() => {}} + onModelNameChange={() => {}} onRestart={() => {}} /> +
+
; +} diff --git a/webui/browser/idle-compaction.spec.ts b/webui/browser/idle-compaction.spec.ts new file mode 100644 index 000000000..bb2bc357e --- /dev/null +++ b/webui/browser/idle-compaction.spec.ts @@ -0,0 +1,59 @@ +import { expect, test } from "@playwright/test"; + +for (const locale of ["en", "zh-CN"]) { + for (const width of [390, 1280]) { + test(`idle compaction settings in ${locale} at ${width}px`, async ({ page }) => { + await page.setViewportSize({ width, height: 900 }); + await page.addInitScript((language) => localStorage.setItem("nanobot.locale", language), locale); + await page.goto("/browser/fixture.html?case=idle-compaction"); + const chinese = locale === "zh-CN"; + const input = page.getByRole("textbox", { name: chinese ? "空闲时限" : "Idle timeout" }); + const toggle = page.getByRole("switch", { name: chinese ? "空闲自动压缩" : "Auto-compact idle sessions" }); + const persisted = page.getByRole("status", { name: "Persisted minutes" }); + await expect(input).toHaveValue("720"); + for (const draft of ["37", "0"]) { + await input.fill(draft); + await page.getByRole("button", { name: chinese ? "取消" : "Cancel", exact: true }).click(); + await expect(input).toHaveValue("720"); + await expect(persisted).toHaveText("720"); + } + await input.fill("721"); + await expect(persisted).toHaveText("720"); + await page.getByText(chinese ? "分钟" : "minutes", { exact: true }).click(); + await expect(persisted).toHaveText("721"); + await expect(toggle).toBeEnabled(); + await toggle.click(); + await expect(persisted).toHaveText("0"); + await expect(input).toHaveCount(0); + await page.reload(); + await expect(toggle).not.toBeChecked(); + await toggle.click(); + await expect(input).toHaveValue("15"); + await expect(toggle).toBeEnabled(); + + await input.fill("-1"); + await input.press("Enter"); + await expect(input).toHaveAttribute("aria-invalid", "true"); + await expect(input).toHaveValue("-1"); + await expect(persisted).toHaveText("15"); + await input.fill("37"); + // Arm the failure without moving focus and committing the draft first. + await page.getByRole("button", { name: "Fail next save" }).evaluate((button: HTMLButtonElement) => button.click()); + await input.press("Enter"); + await expect(page.getByText("Fixture save failed")).toBeVisible(); + await expect(input).toHaveValue("37"); + await input.press("Enter"); + await expect(persisted).toHaveText("37"); + await expect(page.getByText("Fixture save failed")).toHaveCount(0); + await page.reload(); + await expect(input).toHaveValue("37"); + await input.scrollIntoViewIfNeeded(); + const bounds = await input.boundingBox(); + expect(bounds).not.toBeNull(); + expect(bounds!.x).toBeGreaterThanOrEqual(0); + expect(bounds!.x + bounds!.width).toBeLessThanOrEqual(width); + expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(width); + await page.screenshot({ path: test.info().outputPath(`idle-compaction-${locale}-${width}.png`), fullPage: true }); + }); + } +} diff --git a/webui/browser/skeleton-additions-fixture.tsx b/webui/browser/skeleton-additions-fixture.tsx index a437dd5c9..68f0bef6c 100644 --- a/webui/browser/skeleton-additions-fixture.tsx +++ b/webui/browser/skeleton-additions-fixture.tsx @@ -41,7 +41,7 @@ const previewSettings: SettingsPayload = { max_tokens: 8192, context_window_tokens: 200_000, temperature: 0.1, reasoning_effort: null }], model_call_order: ["default"], runtime_config: Object.fromEntries(RUNTIME_CONFIG_FIELDS.map((field) => [field.path, - field.kind === "boolean" ? true : field.kind === "toggle" ? field.options?.[1] ?? "" : field.kind === "list" ? [] : field.kind === "number" ? 20 : field.kind === "duration" ? 3600 : "", + field.kind === "boolean" ? true : field.kind === "toggle" ? field.options?.[1] ?? "" : field.kind === "list" ? [] : field.kind === "number" ? 20 : field.kind === "duration" ? 3600 : field.kind === "idle-compaction" ? 15 : "", ])), }; let detailState = "loaded"; diff --git a/webui/src/components/settings/shared/SettingsControls.tsx b/webui/src/components/settings/shared/SettingsControls.tsx index 2a76b5df3..15e92aa3a 100644 --- a/webui/src/components/settings/shared/SettingsControls.tsx +++ b/webui/src/components/settings/shared/SettingsControls.tsx @@ -324,6 +324,7 @@ export function RestartSettingsFooter({ size="sm" variant="ghost" onClick={onReset} + data-settings-reset="" disabled={!dirty || saving} className="rounded-full" > diff --git a/webui/src/components/settings/shared/SettingsSectionSkeleton.tsx b/webui/src/components/settings/shared/SettingsSectionSkeleton.tsx index 5ca9d8f34..5ba1ef04d 100644 --- a/webui/src/components/settings/shared/SettingsSectionSkeleton.tsx +++ b/webui/src/components/settings/shared/SettingsSectionSkeleton.tsx @@ -8,7 +8,7 @@ import { SkeletonStatus } from "@/components/settings/shared/SkeletonStatus"; import { RUNTIME_CONFIG_FIELDS, RUNTIME_CONFIG_GROUPS, type RuntimeConfigPage } from "@/components/settings/system/runtime-config-fields"; import { cn } from "@/lib/utils"; -type Control = "switch" | "input" | "duration" | "segments" | "reading" | "theme" | "edit" | "text" | "feature"; +type Control = "switch" | "input" | "duration" | "idle-timeout" | "segments" | "reading" | "theme" | "edit" | "text" | "feature"; const block = "rounded bg-muted-foreground/20"; function Title({ heading = false }: { heading?: boolean }) { @@ -23,7 +23,9 @@ function Row({ control }: { control: Control }) {
{control === "feature" ?
: null} - {control === "duration" ?
:
+
+
: control === "duration" ?
:
{RUNTIME_CONFIG_GROUPS.filter((group) => group.page === page).map((group) => group.id === "chat" ? - : field.group === group.id && (!field.when || field.when.value === true)).map((field) => - field.kind === "boolean" || field.kind === "toggle" ? "switch" : field.kind === "list" ? "edit" : field.kind === "duration" ? "duration" : "input", + : field.group === group.id && (!field.when || field.when.value === true)).flatMap((field) => + field.kind === "idle-compaction" ? ["switch", "idle-timeout"] : [ + field.kind === "boolean" || field.kind === "toggle" ? "switch" : field.kind === "list" ? "edit" : field.kind === "duration" ? "duration" : "input", + ], )} />)}; } diff --git a/webui/src/components/settings/system/IdleCompactionControl.tsx b/webui/src/components/settings/system/IdleCompactionControl.tsx new file mode 100644 index 000000000..8e19b5450 --- /dev/null +++ b/webui/src/components/settings/system/IdleCompactionControl.tsx @@ -0,0 +1,63 @@ +import { useEffect, useRef, useState } from "react"; +import { useTranslation } from "react-i18next"; + +import { SettingsRow } from "@/components/settings/shared/SettingsControls"; +import { Input } from "@/components/ui/input"; +import { ToggleButton } from "@/components/ui/toggle-button"; + +export function IdleCompactionControl({ + id, value, savedMinutes, disabled, errorId, onChange, onCommit, +}: { + id: string; + value: string; + savedMinutes: number; + disabled: boolean; + errorId?: string; + onChange: (next: string) => void; + onCommit: (next: string) => void; +}) { + const { t } = useTranslation(); + const tr = (key: string) => t(`settings.runtimeConfig.idleCompaction.${key}`); + const [editing, setEditing] = useState(false); + const enabled = editing || value !== "0"; + const lastMinutes = useRef(savedMinutes > 0 ? String(savedMinutes) : "15"); + useEffect(() => { + if (savedMinutes > 0) lastMinutes.current = String(savedMinutes); + }, [savedMinutes]); + const toggleId = `${id}-enabled`; + return <> + + { + if (/^\d+$/.test(value) && Number.isSafeInteger(Number(value)) && Number(value) > 0) { + lastMinutes.current = value; + } + setEditing(false); + onCommit(next ? lastMinutes.current : "0"); + }} /> + + {enabled ? +
+ onChange(event.target.value)} + onFocus={() => setEditing(true)} + onKeyDown={(event) => { + if (event.key === "Enter") { + event.preventDefault(); + setEditing(false); + onCommit(value); + } + }} + onBlur={(event) => { + if (event.relatedTarget?.id === toggleId + || (event.relatedTarget instanceof Element && event.relatedTarget.closest("[data-settings-reset]"))) return; + setEditing(false); + }} /> + {tr("minutes")} +
+
: null} + ; +} diff --git a/webui/src/components/settings/system/RuntimeConfigSettings.tsx b/webui/src/components/settings/system/RuntimeConfigSettings.tsx index 6af847e50..718298ef5 100644 --- a/webui/src/components/settings/system/RuntimeConfigSettings.tsx +++ b/webui/src/components/settings/system/RuntimeConfigSettings.tsx @@ -7,6 +7,7 @@ import { ProviderPicker } from "@/components/settings/shared/ModelControls"; import { TimezonePicker } from "@/components/settings/shared/TimezonePicker"; import { SettingsTextEditor } from "@/components/settings/shared/SettingsTextEditor"; import { ShellRuntimeControl } from "@/components/settings/system/ShellRuntimeControl"; +import { IdleCompactionControl } from "@/components/settings/system/IdleCompactionControl"; import { Input } from "@/components/ui/input"; import { RUNTIME_CONFIG_FIELDS, RUNTIME_CONFIG_GROUPS, type RuntimeConfigField, type RuntimeConfigPage } from "@/components/settings/system/runtime-config-fields"; import { updateRuntimeConfigSettings } from "@/lib/api"; @@ -65,18 +66,26 @@ export function useRuntimeConfigSettings( setErrors((prev) => ({ ...prev, [field.group]: message })); setInvalidField(field.path); }; - const save = async (group: string) => { + const save = async (group: string, edits: Record = {}) => { if (!settings?.runtime_config) return; if (saving) { if (!queuedSaves.current.includes(group)) queuedSaves.current.push(group); return; } - const changed = RUNTIME_CONFIG_FIELDS.filter((field) => field.group === group && visible(field) && dirty(field)); + const editedValue = (field: RuntimeConfigField) => edits[field.path] ?? value(field.path); + const changed = RUNTIME_CONFIG_FIELDS.filter((field) => field.group === group && visible(field) + && editedValue(field) !== displayValue(settings.runtime_config?.[field.path])); if (!changed.length) return; const values: Record = {}; for (const field of changed) { - const raw = value(field.path); - if (field.kind === "number" || field.kind === "duration") { + const raw = editedValue(field); + if (field.kind === "idle-compaction") { + if (!/^\d+$/.test(String(raw)) || !Number.isSafeInteger(Number(raw))) { + reject(field, t("settings.runtimeConfig.idleCompaction.numberError")); + return; + } + values[field.path] = Number(raw); + } else if (field.kind === "number" || field.kind === "duration") { const maximum = field.kind === "duration" ? settings.advanced.exec_max_runtime_limit : field.max; const parsed = Number(raw); if (String(raw).trim() === "" || !Number.isFinite(parsed) @@ -131,7 +140,12 @@ export function useRuntimeConfigSettings( applyPayload(payload, { preserveAgentForm: true, preserveCapabilityForms: true }); setSaved((prev) => ({ ...prev, [field.group]: true })); }; - return { value, visible, dirty, discard, change, reject, save, saveList, saving, errors, invalidField, saved }; + const commit = (field: RuntimeConfigField, next: Draft) => { + if (next === value(field.path) && !dirty(field)) return; + change(field, next); + void save(field.group, { [field.path]: next }); + }; + return { value, visible, dirty, discard, change, commit, reject, save, saveList, saving, errors, invalidField, saved }; } export type RuntimeConfigController = ReturnType; @@ -171,17 +185,31 @@ export function RuntimeConfigSettings({ const section = (
{title} -
{ event.preventDefault(); void state.save(group.id); }}> + { event.preventDefault(); void state.save(group.id); }} + onBlur={(event) => { + if (event.relatedTarget && event.currentTarget.contains(event.relatedTarget)) return; + if (fields.some((field) => field.kind === "idle-compaction" && state.dirty(field))) { + void state.save(group.id); + } + }}>
{title}