Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
feat(webui): configure idle compaction timeout (NAN-305) (#6383)
chengyongruf11ea5f9e03c
diff --git a/docs/configuration.md b/docs/configuration.mdindex 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.pyindex 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.jsonindex 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.pyindex 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 WebUISettingsServicesdef 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"] == backendassert 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 defaultsdiff --git a/webui/browser/fixture.tsx b/webui/browser/fixture.tsxindex 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() {/></main>;}if (parameters.get("case") === "skeleton-additions") installSkeletonPreviewApi();+if (parameters.get("case") === "idle-compaction") installIdleCompactionApi();await initializeI18n();createRoot(document.getElementById("root")!).render(<TooltipProvider>{parameters.get("case") === "answer-order"@@ -180,6 +182,8 @@ createRoot(document.getElementById("root")!).render(<TooltipProvider>? <MarkdownEmphasisFixture />: parameters.get("case") === "typography"? <ClientProvider client={railClient} token="fixture"><TypographyFixture /></ClientProvider>+ : parameters.get("case") === "idle-compaction"+ ? <IdleCompactionFixture />: parameters.get("case") === "history-hydration"? <HistoryHydrationFixture />: parameters.get("case") === "history-boundary"diff --git a/webui/browser/idle-compaction-fixture.tsx b/webui/browser/idle-compaction-fixture.tsxnew file mode 100644index 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 <T,>(action: string, payload?: Record<string, unknown>): Promise<T> => {+ 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<string, RuntimeConfigValue>;+ 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<string, unknown> = {+ "/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 <ClientProvider client={client} token="fixture">+ <div className="flex min-h-screen flex-col">+ <div className="flex gap-3 p-2 text-xs">+ <button onClick={() => { failNext = true; }}>Fail next save</button>+ <output aria-label="Persisted minutes">{String(snapshot.runtime_config?.[path])}</output>+ </div>+ <SettingsView theme="light" initialSection="runtime" initialSettings={initial}+ onSettingsChange={setSnapshot} onToggleTheme={() => {}} onBackToChat={() => {}}+ onModelNameChange={() => {}} onRestart={() => {}} />+ </div>+ </ClientProvider>;+}diff --git a/webui/browser/idle-compaction.spec.ts b/webui/browser/idle-compaction.spec.tsnew file mode 100644index 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.tsxindex 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.tsxindex 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.tsxindex 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 }) {<div className="flex h-5 items-center"><div className={cn(block, "h-3.5 w-32 max-w-full")} /></div><div className="settings-control">{control === "feature" ? <div className={cn(block, "mr-3 h-3 w-14")} /> : null}- {control === "duration" ? <div className="w-full"><div className={cn(block, "h-9 w-full rounded-full")} /><div className="mt-1.5 flex h-4 items-center"><div className={cn(block, "h-2.5 w-4/5 opacity-60")} /></div></div> : <div data-skeleton-switch={toggle ? "" : undefined} data-skeleton-reading-size={control === "reading" ? "" : undefined} className={cn(block,+ {control === "idle-timeout" ? <div className="flex items-center gap-2">+ <div className={cn(block, "h-9 w-28 rounded-full")} /><div className={cn(block, "h-3 w-10")} />+ </div> : control === "duration" ? <div className="w-full"><div className={cn(block, "h-9 w-full rounded-full")} /><div className="mt-1.5 flex h-4 items-center"><div className={cn(block, "h-2.5 w-4/5 opacity-60")} /></div></div> : <div data-skeleton-switch={toggle ? "" : undefined} data-skeleton-reading-size={control === "reading" ? "" : undefined} className={cn(block,toggle ? "h-5 w-9 shrink-0 rounded-full" : control === "input" ? "h-9 w-full rounded-full": control === "segments" || control === "reading" || control === "theme" ? "segmented-control w-44 rounded-full" : control === "edit" ? "ml-auto h-9 w-9 rounded-full" : "h-[1lh] w-24 text-ui",(control === "segments" || control === "reading") && "h-[34px]", control === "theme" && "h-8",@@ -40,8 +42,10 @@ function Group({ controls }: { controls: Control[] }) {function RuntimeGroups({ page }: { page: RuntimeConfigPage }) {return <>{RUNTIME_CONFIG_GROUPS.filter((group) => group.page === page).map((group) => group.id === "chat"? <Group key={group.id} controls={["switch", "segments"]} />- : <Group key={group.id} controls={RUNTIME_CONFIG_FIELDS.filter((field) => 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",+ : <Group key={group.id} controls={RUNTIME_CONFIG_FIELDS.filter((field) => field.group === group.id && (!field.when || field.when.value === true)).flatMap<Control>((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.tsxnew file mode 100644index 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 <>+ <SettingsRow title={tr("label")} description={tr("help")}>+ <ToggleButton id={toggleId} checked={enabled} disabled={disabled} label={tr("label")}+ onChange={(next) => {+ if (/^\d+$/.test(value) && Number.isSafeInteger(Number(value)) && Number(value) > 0) {+ lastMinutes.current = value;+ }+ setEditing(false);+ onCommit(next ? lastMinutes.current : "0");+ }} />+ </SettingsRow>+ {enabled ? <SettingsRow title={tr("wait")}>+ <div className="flex items-center gap-2">+ <Input id={id} type="text" inputMode="numeric" value={value} disabled={disabled}+ aria-label={tr("wait")} aria-describedby={`${id}-unit${errorId ? ` ${errorId}` : ""}`}+ aria-invalid={Boolean(errorId) || undefined}+ className="h-9 w-28 rounded-full text-[13px]" autoComplete="off"+ onChange={(event) => 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);+ }} />+ <span id={`${id}-unit`} className="text-[13px] text-muted-foreground">{tr("minutes")}</span>+ </div>+ </SettingsRow> : null}+ </>;+}diff --git a/webui/src/components/settings/system/RuntimeConfigSettings.tsx b/webui/src/components/settings/system/RuntimeConfigSettings.tsxindex 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<string, Draft> = {}) => {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<string, RuntimeConfigValue> = {};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<typeof useRuntimeConfigSettings>;@@ -171,17 +185,31 @@ export function RuntimeConfigSettings({const section = (<section key={group.id} aria-label={title}><SettingsSectionTitle>{title}</SettingsSectionTitle>- <form noValidate onSubmit={(event) => { event.preventDefault(); void state.save(group.id); }}>+ <form noValidate onSubmit={(event) => { 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);+ }+ }}><fieldset disabled={state.saving === group.id || isRestarting} className="min-w-0"><legend className="sr-only">{title}</legend><button type="submit" hidden /><SettingsGroup>{fields.filter(state.visible).map((field) => {const id = `runtime-${field.path}`;+ const current = state.value(field.path);+ if (field.kind === "idle-compaction") return (+ <IdleCompactionControl key={field.path} id={id} value={String(current)}+ savedMinutes={Number(settings.runtime_config?.[field.path])}+ disabled={state.saving === group.id || isRestarting}+ errorId={state.invalidField === field.path ? errorId : undefined}+ onChange={(next) => state.change(field, next)}+ onCommit={(next) => state.commit(field, next)} />+ );const key = field.path.replaceAll(".", "_");const text = tr(`fields.${key}.label`);const help = tr(`fields.${key}.help`);- const current = state.value(field.path);const disabled = (field.path === "agents.defaults.timezone" && state.value("agents.defaults.timezone_mode") === "auto")|| (field.path === "tools.webui_allow_remote_package_install" && remoteBrowserAccess);const common = {diff --git a/webui/src/components/settings/system/runtime-config-fields.ts b/webui/src/components/settings/system/runtime-config-fields.tsindex b2d45d9bd..6f95ed8d9 100644--- a/webui/src/components/settings/system/runtime-config-fields.ts+++ b/webui/src/components/settings/system/runtime-config-fields.ts@@ -1,7 +1,7 @@export interface RuntimeConfigField {group: string;path: string;- kind: "toggle" | "text" | "nullable" | "number" | "duration" | "boolean" | "select" | "list" | "preset";+ kind: "toggle" | "text" | "nullable" | "number" | "duration" | "boolean" | "select" | "list" | "preset" | "idle-compaction";options?: string[];when?: { path: string; value: string | boolean | string[] };manual?: boolean;@@ -39,6 +39,7 @@ export const RUNTIME_CONFIG_FIELDS: RuntimeConfigField[] = [{ group: "execution", path: "agents.defaults.tool_hint_max_length", kind: "number", min: 20, max: 500 },{ group: "execution", path: "tools.max_session_messages_per_minute", kind: "number", min: 1 },{ group: "sessions", path: "agents.defaults.unified_session", kind: "boolean" },+ { group: "sessions", path: "agents.defaults.session_ttl_minutes", kind: "idle-compaction", manual: true },{ group: "tools", path: "tools.exec.enable", kind: "boolean" },{ group: "tools", path: "tools.file.enable", kind: "boolean" },{ group: "web", path: "tools.web.enable", kind: "boolean" },diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.jsonindex 4b0c41689..f6d2342e0 100644--- a/webui/src/i18n/locales/en/common.json+++ b/webui/src/i18n/locales/en/common.json@@ -745,6 +745,13 @@"search": "Find an advanced setting","noResults": "No matching settings.","pending": "Unsaved changes",+ "idleCompaction": {+ "label": "Auto-compact idle sessions",+ "help": "Automatically compact context after the idle timeout to reduce token usage on subsequent requests.",+ "wait": "Idle timeout",+ "minutes": "minutes",+ "numberError": "Enter a non-negative whole number of minutes."+ },"numberError": "Enter a valid number within the allowed range.","activeModel": "Use active model","none": "None",diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.jsonindex e9f9e7926..807fb597e 100644--- a/webui/src/i18n/locales/es/common.json+++ b/webui/src/i18n/locales/es/common.json@@ -565,6 +565,13 @@"save": "Guardar cambios", "saving": "Guardando…", "discard": "Descartar cambios", "saved": "Guardado.","restart": "Reiniciar nanobot", "restartHelp": "Reinicia para aplicar los cambios. Los argumentos de línea de comandos y las variables de entorno pueden tener prioridad.","search": "Buscar un ajuste avanzado", "noResults": "No hay ajustes que coincidan.", "pending": "Cambios sin guardar",+ "idleCompaction": {+ "label": "Compactación automática por inactividad",+ "help": "Compacta el contexto automáticamente al alcanzar el límite de inactividad para reducir el uso de tokens en solicitudes posteriores.",+ "wait": "Límite de inactividad",+ "minutes": "minutos",+ "numberError": "Introduce un número entero de minutos mayor o igual que cero."+ },"numberError": "Introduce un número válido dentro del rango permitido.", "activeModel": "Usar el modelo activo", "none": "Ninguno","auto": "Automático", "manual": "Manual", "standard": "Estándar", "persistent": "Continuo","unavailable": "Actualiza la pasarela para editar estos ajustes.", "advancedOptions": "Opciones avanzadas"diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.jsonindex 04a0c30f9..bbbb7554a 100644--- a/webui/src/i18n/locales/fr/common.json+++ b/webui/src/i18n/locales/fr/common.json@@ -565,6 +565,13 @@"save": "Enregistrer les modifications", "saving": "Enregistrement…", "discard": "Annuler les modifications", "saved": "Enregistré.","restart": "Redémarrer nanobot", "restartHelp": "Redémarrez pour appliquer les modifications. Les arguments de ligne de commande et variables d’environnement peuvent avoir priorité.","search": "Rechercher un paramètre avancé", "noResults": "Aucun paramètre correspondant.", "pending": "Modifications non enregistrées",+ "idleCompaction": {+ "label": "Compression automatique après inactivité",+ "help": "Compresse automatiquement le contexte après le délai d’inactivité pour réduire l’utilisation de tokens dans les requêtes suivantes.",+ "wait": "Délai d’inactivité",+ "minutes": "minutes",+ "numberError": "Saisissez un nombre entier de minutes supérieur ou égal à zéro."+ },"numberError": "Saisissez un nombre valide dans la plage autorisée.", "activeModel": "Utiliser le modèle actif", "none": "Aucun","auto": "Automatique", "manual": "Manuel", "standard": "Standard", "persistent": "Continu","unavailable": "Mettez à jour la passerelle pour modifier ces paramètres.", "advancedOptions": "Options avancées"diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.jsonindex 0444f948d..4a0d18f2b 100644--- a/webui/src/i18n/locales/id/common.json+++ b/webui/src/i18n/locales/id/common.json@@ -565,6 +565,13 @@"save": "Simpan perubahan", "saving": "Menyimpan…", "discard": "Buang perubahan", "saved": "Tersimpan.","restart": "Mulai ulang nanobot", "restartHelp": "Mulai ulang untuk menerapkan perubahan. Argumen baris perintah dan variabel lingkungan mungkin lebih diutamakan.","search": "Cari pengaturan lanjutan", "noResults": "Tidak ada pengaturan yang cocok.", "pending": "Perubahan belum disimpan",+ "idleCompaction": {+ "label": "Padatkan sesi tidak aktif secara otomatis",+ "help": "Padatkan konteks secara otomatis saat batas waktu tidak aktif tercapai untuk mengurangi penggunaan token pada permintaan berikutnya.",+ "wait": "Batas waktu tidak aktif",+ "minutes": "menit",+ "numberError": "Masukkan jumlah menit berupa bilangan bulat nol atau lebih."+ },"numberError": "Masukkan angka yang valid dalam rentang yang diizinkan.", "activeModel": "Gunakan model aktif", "none": "Tidak ada","auto": "Otomatis", "manual": "Manual", "standard": "Standar", "persistent": "Terus-menerus","unavailable": "Perbarui gateway untuk mengedit pengaturan ini.", "advancedOptions": "Opsi lanjutan"diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.jsonindex bec031c4a..9415083db 100644--- a/webui/src/i18n/locales/ja/common.json+++ b/webui/src/i18n/locales/ja/common.json@@ -565,6 +565,13 @@"save": "変更を保存", "saving": "保存中…", "discard": "変更を破棄", "saved": "保存しました。","restart": "nanobot を再起動", "restartHelp": "再起動すると反映されます。コマンドライン引数や環境変数の設定が優先される場合があります。","search": "詳細設定を検索", "noResults": "一致する設定はありません。", "pending": "未保存の変更",+ "idleCompaction": {+ "label": "未使用時の自動圧縮",+ "help": "未使用時間が上限に達するとコンテキストを自動圧縮し、次回以降のトークン使用量を減らします。",+ "wait": "未使用時間の上限",+ "minutes": "分",+ "numberError": "分数を0以上の整数で入力してください。"+ },"numberError": "許可された範囲内の有効な数値を入力してください。", "activeModel": "現在のモデルを使用", "none": "なし","auto": "自動", "manual": "手動", "standard": "標準", "persistent": "継続","unavailable": "これらの設定を編集するにはゲートウェイを更新してください。", "advancedOptions": "詳細オプション"diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.jsonindex 0d11a6a3e..a6137c1b4 100644--- a/webui/src/i18n/locales/ko/common.json+++ b/webui/src/i18n/locales/ko/common.json@@ -565,6 +565,13 @@"save": "변경 사항 저장", "saving": "저장 중…", "discard": "변경 사항 취소", "saved": "저장했습니다.","restart": "nanobot 다시 시작", "restartHelp": "다시 시작하면 적용됩니다. 명령줄 인수와 환경 변수 설정이 우선 적용될 수 있습니다.","search": "고급 설정 검색", "noResults": "일치하는 설정이 없습니다.", "pending": "저장하지 않은 변경 사항",+ "idleCompaction": {+ "label": "유휴 시 자동 압축",+ "help": "유휴 시간 제한에 도달하면 컨텍스트를 자동으로 압축해 이후 요청의 토큰 사용량을 줄입니다.",+ "wait": "유휴 시간 제한",+ "minutes": "분",+ "numberError": "분 단위로 0 이상의 정수를 입력하세요."+ },"numberError": "허용 범위 내의 유효한 숫자를 입력하세요.", "activeModel": "현재 모델 사용", "none": "없음","auto": "자동", "manual": "수동", "standard": "표준", "persistent": "계속","unavailable": "이 설정을 편집하려면 게이트웨이를 업데이트하세요.", "advancedOptions": "고급 옵션"diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.jsonindex 11a734035..cf03b139f 100644--- a/webui/src/i18n/locales/pt-BR/common.json+++ b/webui/src/i18n/locales/pt-BR/common.json@@ -565,6 +565,13 @@"save": "Salvar alterações", "saving": "Salvando…", "discard": "Descartar alterações", "saved": "Salvo.","restart": "Reiniciar nanobot", "restartHelp": "Reinicie para aplicar as alterações. Os argumentos de linha de comando e as variáveis de ambiente podem ter prioridade.","search": "Buscar uma configuração avançada", "noResults": "Nenhuma configuração correspondente.", "pending": "Alterações não salvas",+ "idleCompaction": {+ "label": "Compactação automática por inatividade",+ "help": "Compacta o contexto automaticamente ao atingir o limite de inatividade para reduzir o uso de tokens nas próximas solicitações.",+ "wait": "Limite de inatividade",+ "minutes": "minutos",+ "numberError": "Digite um número inteiro de minutos maior ou igual a zero."+ },"numberError": "Digite um número válido dentro do intervalo permitido.", "activeModel": "Usar o modelo ativo", "none": "Nenhum","auto": "Automático", "manual": "Manual", "standard": "Padrão", "persistent": "Contínuo","unavailable": "Atualize o gateway para editar estas configurações.", "advancedOptions": "Opções avançadas"diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.jsonindex c1a7a3f5c..7dda930b5 100644--- a/webui/src/i18n/locales/vi/common.json+++ b/webui/src/i18n/locales/vi/common.json@@ -565,6 +565,13 @@"save": "Lưu thay đổi", "saving": "Đang lưu…", "discard": "Hủy thay đổi", "saved": "Đã lưu.","restart": "Khởi động lại nanobot", "restartHelp": "Khởi động lại để áp dụng thay đổi. Tham số dòng lệnh và biến môi trường có thể được ưu tiên.","search": "Tìm cài đặt nâng cao", "noResults": "Không có cài đặt phù hợp.", "pending": "Thay đổi chưa lưu",+ "idleCompaction": {+ "label": "Tự động nén khi không hoạt động",+ "help": "Tự động nén ngữ cảnh khi hết thời gian chờ để giảm lượng token dùng cho các yêu cầu tiếp theo.",+ "wait": "Giới hạn thời gian không hoạt động",+ "minutes": "phút",+ "numberError": "Nhập số phút là số nguyên không âm."+ },"numberError": "Nhập số hợp lệ trong phạm vi cho phép.", "activeModel": "Dùng mô hình hiện tại", "none": "Không có","auto": "Tự động", "manual": "Thủ công", "standard": "Tiêu chuẩn", "persistent": "Liên tục","unavailable": "Cập nhật gateway để chỉnh sửa các cài đặt này.", "advancedOptions": "Tùy chọn nâng cao"diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.jsonindex 3d3978af4..d912d0cac 100644--- a/webui/src/i18n/locales/zh-CN/common.json+++ b/webui/src/i18n/locales/zh-CN/common.json@@ -745,6 +745,13 @@"search": "搜索高级设置","noResults": "没有匹配的设置。","pending": "有未保存的修改",+ "idleCompaction": {+ "label": "空闲自动压缩",+ "help": "空闲超时后压缩上下文,减少后续用量。",+ "wait": "空闲时限",+ "minutes": "分钟",+ "numberError": "请输入非负整数分钟数。"+ },"numberError": "请输入允许范围内的有效数字。","activeModel": "使用当前模型","none": "无",diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.jsonindex 25ffb70e4..3bd58b831 100644--- a/webui/src/i18n/locales/zh-TW/common.json+++ b/webui/src/i18n/locales/zh-TW/common.json@@ -565,6 +565,13 @@"save": "儲存變更", "saving": "儲存中…", "discard": "捨棄變更", "saved": "已儲存。","restart": "重新啟動 nanobot", "restartHelp": "重新啟動後生效;命令列與環境變數的設定可能優先。","search": "搜尋進階設定", "noResults": "找不到相符設定。", "pending": "尚未儲存的變更",+ "idleCompaction": {+ "label": "閒置自動壓縮",+ "help": "閒置逾時後壓縮上下文,減少後續用量。",+ "wait": "閒置時限",+ "minutes": "分鐘",+ "numberError": "請輸入非負整數分鐘數。"+ },"numberError": "請輸入允許範圍內的有效數字。", "activeModel": "使用目前模型", "none": "無","auto": "自動", "manual": "手動", "standard": "標準", "persistent": "持續","unavailable": "更新閘道後可編輯這些設定。", "advancedOptions": "進階選項"diff --git a/webui/src/tests/settings-idle-compaction.test.tsx b/webui/src/tests/settings-idle-compaction.test.tsxnew file mode 100644index 000000000..e8901f827--- /dev/null+++ b/webui/src/tests/settings-idle-compaction.test.tsx@@ -0,0 +1,154 @@+import { act, cleanup, fireEvent, screen, waitFor, within } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import userEvent from "@testing-library/user-event";++import {+ installSettingsViewTestHooks, renderSettingsView, requestMutationMock, settingsPayload,+} from "@/tests/settings-test-utils";++const path = "agents.defaults.session_ttl_minutes";++function setup(minutes = 720) {+ let persisted = {+ ...settingsPayload(),+ runtime_config: { [path]: minutes, "agents.defaults.unified_session": false },+ };+ requestMutationMock.mockImplementation(async (_action, { values }) => {+ persisted = { ...persisted, requires_restart: true,+ runtime_config: { ...persisted.runtime_config, ...values } };+ return persisted;+ });+ renderSettingsView({ initialSection: "runtime", initialSettings: persisted, onRestart: vi.fn() });+ return () => persisted;+}++const input = () => screen.getByRole("textbox", { name: "Idle timeout" });+const toggle = () => screen.getByRole("switch", { name: "Auto-compact idle sessions" });++function edit(next: string) {+ fireEvent.focus(input());+ fireEvent.change(input(), { target: { value: next } });+}++function expectSaved(minutes: number) {+ expect(requestMutationMock).toHaveBeenLastCalledWith(+ "settings.runtime_config.update", { values: { [path]: minutes } }, 20_000,+ );+}++describe("Idle compaction settings", () => {+ installSettingsViewTestHooks();++ it.each([15, 720, 0])("reads %i minutes in System → Sessions", (minutes) => {+ setup(minutes);+ const sessions = within(screen.getByRole("region", { name: "Sessions" }));+ expect(sessions.getByRole("switch", { name: "Auto-compact idle sessions" })).toHaveAttribute(+ "aria-checked", String(minutes > 0),+ );+ if (minutes) expect(input()).toHaveValue(String(minutes));+ else expect(screen.queryByRole("textbox", { name: "Idle timeout" })).not.toBeInTheDocument();+ });++ it("commits minutes on blur, retains minute precision, and reads saved values after remount", async () => {+ const persisted = setup(15);+ vi.useFakeTimers();+ edit("721");+ await act(async () => { await vi.advanceTimersByTimeAsync(1_500); });+ expect(requestMutationMock).not.toHaveBeenCalled();+ vi.useRealTimers();+ fireEvent.blur(input());+ await waitFor(() => expectSaved(721));+ await waitFor(() => expect(input()).toBeEnabled());+ expect(screen.getAllByText("Saved. Restart to apply changes.").length).toBeGreaterThan(0);+ cleanup();+ renderSettingsView({ initialSection: "runtime", initialSettings: persisted() });+ expect(input()).toHaveValue("721");+ });++ it("saves when keyboard focus leaves the section after reaching Cancel", async () => {+ setup();+ const user = userEvent.setup();+ await user.click(input());+ await user.clear(input());+ await user.type(input(), "37");+ await user.tab();+ expect(screen.getByRole("button", { name: "Cancel" })).toHaveFocus();+ expect(requestMutationMock).not.toHaveBeenCalled();+ await user.click(screen.getByRole("heading", { name: "Sessions" }));+ await waitFor(() => expectSaved(37));+ });++ it("disables with zero and restores the previous duration when enabled again", async () => {+ setup();+ fireEvent.click(toggle());+ await waitFor(() => expectSaved(0));+ await waitFor(() => expect(toggle()).toBeEnabled());+ expect(toggle()).not.toBeChecked();+ expect(screen.queryByRole("textbox", { name: "Idle timeout" })).not.toBeInTheDocument();+ fireEvent.click(toggle());+ await waitFor(() => expectSaved(720));+ expect(input()).toHaveValue("720");+ });++ it("enables a saved disabled setting with the default duration", async () => {+ setup(0);+ fireEvent.click(toggle());+ await waitFor(() => expectSaved(15));+ expect(input()).toHaveValue("15");+ });++ it("accepts zero entered in the duration field on Enter", async () => {+ setup();+ edit("0");+ expect(input()).toHaveValue("0");+ fireEvent.keyDown(input(), { key: "Enter" });+ await waitFor(() => expectSaved(0));+ expect(toggle()).not.toBeChecked();+ expect(screen.queryByRole("textbox", { name: "Idle timeout" })).not.toBeInTheDocument();+ });++ it.each(["", "-1", "1.5", "1e3", "9007199254740992"])("retains invalid input %j without saving", async (next) => {+ setup();+ edit(next);+ fireEvent.blur(input());+ expect(await screen.findByText("Enter a non-negative whole number of minutes.")).toBeVisible();+ expect(input()).toHaveValue(next);+ expect(input()).toHaveAttribute("aria-invalid", "true");+ expect(requestMutationMock).not.toHaveBeenCalled();+ });++ it("keeps the draft after a failed save and allows retry", async () => {+ setup();+ requestMutationMock.mockRejectedValueOnce(new Error("Could not save settings"));+ edit("37");+ fireEvent.blur(input());+ expect(await screen.findByText("Could not save settings")).toBeVisible();+ expect(input()).toHaveValue("37");+ fireEvent.click(screen.getByRole("button", { name: "Save" }));+ await waitFor(() => expect(requestMutationMock).toHaveBeenCalledTimes(2));+ expectSaved(37);+ await waitFor(() => expect(screen.queryByText("Could not save settings")).not.toBeInTheDocument());+ });++ it.each(["37", "0"])("cancels a focused %s minute draft without committing it on blur", async (next) => {+ setup();+ const user = userEvent.setup();+ await user.click(input());+ await user.clear(input());+ await user.type(input(), next);+ await user.click(screen.getByRole("button", { name: "Cancel" }));+ expect(input()).toHaveValue("720");+ expect(requestMutationMock).not.toHaveBeenCalled();+ });++ it("can cancel a failed toggle without losing the stored enabled state", async () => {+ setup();+ requestMutationMock.mockRejectedValueOnce(new Error("Could not save settings"));+ fireEvent.click(toggle());+ expect(await screen.findByText("Could not save settings")).toBeVisible();+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));+ expect(toggle()).toBeChecked();+ expect(input()).toHaveValue("720");+ expect(requestMutationMock).toHaveBeenCalledTimes(1);+ });+});diff --git a/webui/src/tests/settings-runtime-config.test.tsx b/webui/src/tests/settings-runtime-config.test.tsxindex 5dbcd9572..333b9828b 100644--- a/webui/src/tests/settings-runtime-config.test.tsx+++ b/webui/src/tests/settings-runtime-config.test.tsx@@ -17,6 +17,7 @@ function runtimeSettings() {"agents.defaults.timezone_mode": "auto","agents.defaults.timezone": "UTC","agents.defaults.dream.enabled": true,+ "agents.defaults.session_ttl_minutes": 15,"gateway.heartbeat.enabled": true,"tools.exec.timeout": 60,"tools.exec.allowed_env_keys": ["TERM"],