feat(webui): configure idle compaction timeout (NAN-305) (#6383)
* feat(webui): configure idle compaction timeout (NAN-305) * fix(webui): clarify idle compaction timeout and tradeoff * refactor(webui): remove unused idle compaction minimum * fix(webui): match idle compaction loading skeleton
This commit is contained in:
1 parent
c6babb20e8
commit
f11ea5f9e0
25 files changed
+523
-15
No files matched your search
@@ -324,6 +324,7 @@ export function RestartSettingsFooter({
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={onReset}
|
||||
data-settings-reset=""
|
||||
disabled={!dirty || saving}
|
||||
className="rounded-full"
|
||||
>
|
||||
|
||||
@@ -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",
|
||||
],
|
||||
)} />)}</>;
|
||||
}
|
||||
|
||||
|
||||
@@ -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}
|
||||
</>;
|
||||
}
|
||||
@@ -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 = {
|
||||
|
||||
@@ -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" },
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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": "詳細オプション"
|
||||
|
||||
@@ -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": "고급 옵션"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -745,6 +745,13 @@
|
||||
"search": "搜索高级设置",
|
||||
"noResults": "没有匹配的设置。",
|
||||
"pending": "有未保存的修改",
|
||||
"idleCompaction": {
|
||||
"label": "空闲自动压缩",
|
||||
"help": "空闲超时后压缩上下文,减少后续用量。",
|
||||
"wait": "空闲时限",
|
||||
"minutes": "分钟",
|
||||
"numberError": "请输入非负整数分钟数。"
|
||||
},
|
||||
"numberError": "请输入允许范围内的有效数字。",
|
||||
"activeModel": "使用当前模型",
|
||||
"none": "无",
|
||||
|
||||
@@ -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": "進階選項"
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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"],
|
||||
|
||||
Reference in new issue
Block a user