Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat(cli): add /config and /rename command for cli

ldstyle8d2d5b285854b
diff --git a/jiuwenclaw/agentserver/agent_manager.py b/jiuwenclaw/agentserver/agent_manager.py
index 036efa94f3..26319348a7 100644
--- a/jiuwenclaw/agentserver/agent_manager.py
+++ b/jiuwenclaw/agentserver/agent_manager.py
@@ -188,6 +188,13 @@ class AgentManager:
os.environ[key] = str(env_value)
for channel_id, agents in self.agents.items():
+ if not isinstance(agents, dict):
+ logger.warning(
+ "[AgentManager] unexpected agents entry for channel %s: %r",
+ channel_id,
+ type(agents),
+ )
+ continue
for _, agent in agents.items():
await agent.reload_agent_config(
config_base=config,
diff --git a/jiuwenclaw/agentserver/agent_ws_server.py b/jiuwenclaw/agentserver/agent_ws_server.py
index c653f14f95..507689ef80 100644
--- a/jiuwenclaw/agentserver/agent_ws_server.py
+++ b/jiuwenclaw/agentserver/agent_ws_server.py
@@ -304,6 +304,9 @@ class AgentWebSocketServer:
if request.req_method == ReqMethod.SESSION_LIST:
await self._handle_session_list(ws, request, send_lock)
return
+ if request.req_method == ReqMethod.SESSION_RENAME:
+ await self._handle_session_rename(ws, request, send_lock)
+ return
if request.req_method in get_permissions_config_req_methods():
await self._handle_permissions_config(ws, request, send_lock)
return
@@ -581,6 +584,37 @@ class AgentWebSocketServer:
async with send_lock:
await ws.send(json.dumps(wire, ensure_ascii=False))
+ async def _handle_session_rename(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
+ """处理 session.rename:与 CLI Gateway 本地回退共用 apply_session_rename。"""
+ from jiuwenclaw.agentserver.session_rename import apply_session_rename
+
+ sid = request.session_id or ""
+ ch = (request.channel_id or "").strip() or "tui"
+ ok, payload, err, code = apply_session_rename(
+ request.params,
+ sid,
+ init_channel_id=ch,
+ )
+ if ok:
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=True,
+ payload=payload or {},
+ metadata=request.metadata,
+ )
+ else:
+ resp = AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=False,
+ payload={"error": err or "session.rename failed", "code": code or ""},
+ metadata=request.metadata,
+ )
+ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)
+ async with send_lock:
+ await ws.send(json.dumps(wire, ensure_ascii=False))
+
async def _handle_permissions_config(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:
"""处理 permissions.* E2A 请求(与 Web ``register_method`` 同名 method)。"""
from jiuwenclaw.agentserver.permissions.config_rpc import dispatch_permissions_config_request
diff --git a/jiuwenclaw/agentserver/session_metadata.py b/jiuwenclaw/agentserver/session_metadata.py
index b216b075a6..837226745f 100644
--- a/jiuwenclaw/agentserver/session_metadata.py
+++ b/jiuwenclaw/agentserver/session_metadata.py
@@ -40,12 +40,17 @@ def _metadata_file(session_id: str) -> Path:
def _read_metadata(session_id: str) -> dict[str, Any]:
- """读取会话元数据(优先从内存缓存读取,避免异步写入未落盘时读到陈旧数据)"""
+ """读取会话元数据(优先从内存缓存读取,避免异步写入未落盘时读到陈旧数据)
+
+ 读路径不应产生副作用:即便 session 目录不存在,也不触发 mkdir,
+ 否则会导致仅查询(session.rename 无 title 参数时)隐式创建空 session 目录,
+ 污染 session.list 结果。
+ """
with _CACHE_LOCK:
cached = _METADATA_CACHE.get(session_id)
if cached is not None:
return cached.copy()
- fpath = _metadata_file(session_id)
+ fpath = get_agent_sessions_dir() / session_id / "metadata.json"
if not fpath.exists():
return {}
try:
@@ -141,11 +146,19 @@ def update_session_metadata(
channel_id: str | None = None,
user_id: str | None = None,
title: str | None = None,
+ clear_title: bool = False,
increment_message_count: bool = False,
user_content: str | None = None,
channel_metadata: dict[str, Any] | None = None,
) -> None:
- """更新会话元数据(异步写入,不阻塞调用方)"""
+ """更新会话元数据(异步写入,不阻塞调用方)
+
+ title 语义(保持历史防御契约):
+ - title=None → 不修改(默认)
+ - title="x" → 设置为 "x"
+ - title="" → 忽略(防御意外空值覆盖已有标题)
+ - 若需显式清除标题,请设置 clear_title=True
+ """
metadata = _read_metadata(session_id)
if not metadata:
@@ -172,8 +185,10 @@ def update_session_metadata(
metadata["channel_id"] = channel_id
if user_id is not None:
metadata["user_id"] = user_id
- # 仅当传入非空 title 时才更新(防止空字符串覆盖已有标题)
- if title:
+ # 显式清除优先级高于 title 入参
+ if clear_title:
+ metadata["title"] = ""
+ elif title:
metadata["title"] = title
if increment_message_count:
metadata["message_count"] = metadata.get("message_count", 0) + 1
diff --git a/jiuwenclaw/agentserver/session_rename.py b/jiuwenclaw/agentserver/session_rename.py
new file mode 100644
index 0000000000..139332e34b
--- /dev/null
+++ b/jiuwenclaw/agentserver/session_rename.py
@@ -0,0 +1,69 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""session.rename 共享实现:AgentWebSocketServer 与 cli_channel 本地回退共用。
+
+单次 rename 允许的最大标题长度,与 cli 侧保持一致,防御异常/恶意输入污染 metadata.json。
+"""
+from __future__ import annotations
+
+from typing import Any
+
+_RENAME_TITLE_MAX_LEN = 200
+
+
+def apply_session_rename(
+ params: Any,
+ connection_session_id: str,
+ *,
+ init_channel_id: str = "tui",
+) -> tuple[bool, dict[str, Any] | None, str | None, str | None]:
+ """实现 session.rename 三种语义:查询(None) / 清除(空串 strip 后) / 设置。
+
+ Returns:
+ (True, payload, None, None) 成功;
+ (False, None, error_message, error_code) 失败(error_code 如 ``BAD_REQUEST``)。
+ """
+ from jiuwenclaw.agentserver.session_metadata import (
+ get_session_metadata,
+ init_session_metadata,
+ update_session_metadata,
+ )
+
+ if not isinstance(params, dict):
+ params = {}
+
+ target = str(params.get("session_id") or connection_session_id).strip()
+ if not target:
+ return False, None, "session_id is required", "BAD_REQUEST"
+
+ metadata = get_session_metadata(target)
+ raw_title = params.get("title")
+
+ if raw_title is None:
+ current_title = metadata.get("title", "") if metadata else ""
+ payload = {
+ "session_id": target,
+ "title": current_title,
+ "previous_title": current_title,
+ }
+ return True, payload, None, None
+
+ if not metadata:
+ init_session_metadata(session_id=target, channel_id=init_channel_id)
+ metadata = get_session_metadata(target)
+ previous_title = metadata.get("title", "")
+
+ new_title = str(raw_title).strip()[:_RENAME_TITLE_MAX_LEN]
+
+ if new_title:
+ update_session_metadata(session_id=target, title=new_title)
+ else:
+ update_session_metadata(session_id=target, clear_title=True)
+
+ updated = get_session_metadata(target)
+ payload = {
+ "session_id": target,
+ "title": updated.get("title", ""),
+ "previous_title": previous_title,
+ }
+ return True, payload, None, None
diff --git a/jiuwenclaw/app_gateway.py b/jiuwenclaw/app_gateway.py
index 46cd1b8e58..02e4bff301 100644
--- a/jiuwenclaw/app_gateway.py
+++ b/jiuwenclaw/app_gateway.py
@@ -856,7 +856,15 @@ async def _run(
"env": dict(env_updates or {}),
},
)
- await client.send_request(reload_env)
+ reload_resp = await client.send_request(reload_env)
+ if not getattr(reload_resp, "ok", False):
+ err_payload = getattr(reload_resp, "payload", None) or {}
+ err_msg = (
+ err_payload.get("error")
+ if isinstance(err_payload, dict)
+ else err_payload
+ )
+ raise RuntimeError(f"agent.reload_config rejected: {err_msg}")
if updated_env_keys and (browser_runtime_keys & set(updated_env_keys)):
restart_env = e2a_from_agent_fields(
diff --git a/jiuwenclaw/app_web_handlers.py b/jiuwenclaw/app_web_handlers.py
index cb1120853c..a72e0b8b32 100644
--- a/jiuwenclaw/app_web_handlers.py
+++ b/jiuwenclaw/app_web_handlers.py
@@ -443,24 +443,26 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
await _clear_agent_config_cache(_resolve(agent_client))
logger.info("[config.set] 已更新 config.yaml: %s", yaml_updated)
- if env_updates or yaml_updated:
- if on_config_saved:
- config_payload = get_config()
- callback_result = on_config_saved(
- set(env_updates.keys()) | set(yaml_updated),
- env_updates=dict(env_updates),
- config_payload=config_payload,
- )
- if inspect.isawaitable(callback_result):
- callback_result = await callback_result
- applied_without_restart = bool(callback_result)
-
updated_param_keys = [k for k, e in _CONFIG_SET_ENV_MAP.items() if e in env_updates] + yaml_updated
await channel.send_response(
ws, req_id, ok=True,
payload={"updated": updated_param_keys, "applied_without_restart": applied_without_restart},
)
+ if env_updates or yaml_updated:
+ if on_config_saved:
+ try:
+ config_payload = get_config()
+ callback_result = on_config_saved(
+ set(env_updates.keys()) | set(yaml_updated),
+ env_updates=dict(env_updates),
+ config_payload=config_payload,
+ )
+ if inspect.isawaitable(callback_result):
+ await callback_result
+ except Exception as e: # noqa: BLE001
+ logger.warning("[config.set] on_config_saved failed: %s", e)
+
async def _config_validate_model(ws, req_id, params, session_id, max_tokens_bounds=None):
"""Send a minimal chat completion (user message \"Hi\") using draft default-model fields.
diff --git a/jiuwenclaw/channel/cli_channel.py b/jiuwenclaw/channel/cli_channel.py
index e729322e7f..10378a99ac 100644
--- a/jiuwenclaw/channel/cli_channel.py
+++ b/jiuwenclaw/channel/cli_channel.py
@@ -6,6 +6,7 @@ import inspect
import logging
import os
import shutil
+import time
from dataclasses import dataclass
from typing import Any
@@ -19,10 +20,12 @@ from jiuwenclaw.config import (
get_config,
get_config_raw,
update_context_engine_enabled_in_config,
+ update_memory_forbidden_enabled_in_config,
update_permissions_enabled_in_config,
get_model_names,
get_model_config,
add_or_update_model_in_config,
+ update_preferred_language_in_config,
)
from jiuwenclaw.jiuwen_core_patch import apply_openai_model_client_patch
from jiuwenclaw.gateway.route_binding import GatewayRouteBinding
@@ -160,7 +163,99 @@ _CLI_CONFIG_SET_ENV_MAP = {
"evolution_auto_scan": "EVOLUTION_AUTO_SCAN",
}
-_CLI_CONFIG_YAML_KEYS = frozenset({"context_engine_enabled", "permissions_enabled"})
+_CLI_CONFIG_YAML_SETTERS: dict[str, Any] = {
+ "context_engine_enabled": update_context_engine_enabled_in_config,
+ "permissions_enabled": update_permissions_enabled_in_config,
+ "memory_forbidden_enabled": update_memory_forbidden_enabled_in_config,
+ "preferred_language": update_preferred_language_in_config,
+}
+
+_CLI_CONFIG_YAML_KEYS = frozenset(_CLI_CONFIG_YAML_SETTERS.keys())
+
+
+_PREFERRED_LANGUAGE_OPTIONS = ("zh", "en")
+
+
+def _build_config_schema() -> list[dict]:
+ """构建配置项 Schema,供前端渲染交互界面。与 config.yaml 结构对齐。"""
+ available_providers = [p.value for p in ProviderType]
+ # 显式使用 ProviderType.OpenAI 作为默认供应商,避免依赖枚举声明顺序
+ default_provider = (
+ ProviderType.OpenAI.value
+ if hasattr(ProviderType, "OpenAI")
+ else (available_providers[0] if available_providers else "")
+ )
+ empty = ""
+ return [
+ # Model
+ {"key": "model", "label": "默认模型", "group": "Model", "type": "string",
+ "source": "env", "default": empty},
+ {"key": "model_provider", "label": "模型供应商", "group": "Model", "type": "select",
+ "options": available_providers, "source": "env", "default": default_provider},
+ {"key": "api_base", "label": "API 地址", "group": "Model", "type": "string",
+ "source": "env", "default": empty},
+ {"key": "api_key", "label": "API Key", "group": "Model", "type": "password",
+ "sensitive": True, "source": "env", "default": empty},
+ # Vision
+ {"key": "vision_model", "label": "视觉模型", "group": "Vision", "type": "string",
+ "source": "env", "default": empty},
+ {"key": "vision_provider", "label": "视觉供应商", "group": "Vision", "type": "select",
+ "options": available_providers, "source": "env", "default": default_provider},
+ {"key": "vision_api_base", "label": "视觉API地址", "group": "Vision", "type": "string",
+ "source": "env", "default": empty},
+ {"key": "vision_api_key", "label": "视觉API Key", "group": "Vision", "type": "password",
+ "sensitive": True, "source": "env", "default": empty},
+ # Video
+ {"key": "video_model", "label": "视频模型", "group": "Video", "type": "string",
+ "source": "env", "default": empty},
+ {"key": "video_provider", "label": "视频供应商", "group": "Video", "type": "select",
+ "options": available_providers, "source": "env", "default": default_provider},
+ {"key": "video_api_base", "label": "视频API地址", "group": "Video", "type": "string",
+ "source": "env", "default": empty},
+ {"key": "video_api_key", "label": "视频API Key", "group": "Video", "type": "password",
+ "sensitive": True, "source": "env", "default": empty},
+ # Audio
+ {"key": "audio_model", "label": "音频模型", "group": "Audio", "type": "string",
+ "source": "env", "default": empty},
+ {"key": "audio_provider", "label": "音频供应商", "group": "Audio", "type": "select",
+ "options": available_providers, "source": "env", "default": default_provider},
+ {"key": "audio_api_base", "label": "音频API地址", "group": "Audio", "type": "string",
+ "source": "env", "default": empty},
+ {"key": "audio_api_key", "label": "音频API Key", "group": "Audio", "type": "password",
+ "sensitive": True, "source": "env", "default": empty},
+ # Embedding
+ {"key": "embed_api_key", "label": "嵌入API Key", "group": "Embedding", "type": "password",
+ "sensitive": True, "source": "env", "default": empty},
+ {"key": "embed_api_base", "label": "嵌入API地址", "group": "Embedding", "type": "string",
+ "source": "env", "default": empty},
+ {"key": "embed_model", "label": "嵌入模型", "group": "Embedding", "type": "string",
+ "source": "env", "default": empty},
+ # Search & External
+ {"key": "jina_api_key", "label": "Jina API Key", "group": "Search & External", "type": "password",
+ "sensitive": True, "source": "env", "default": empty},
+ {"key": "serper_api_key", "label": "Serper API Key", "group": "Search & External", "type": "password",
+ "sensitive": True, "source": "env", "default": empty},
+ {"key": "perplexity_api_key", "label": "Perplexity API Key", "group": "Search & External", "type": "password",
+ "sensitive": True, "source": "env", "default": empty},
+ {"key": "github_token", "label": "GitHub Token", "group": "Search & External", "type": "password",
+ "sensitive": True, "source": "env", "default": empty},
+ # Email
+ {"key": "email_address", "label": "邮箱地址", "group": "Email", "type": "string",
+ "source": "env", "default": empty},
+ {"key": "email_token", "label": "邮箱Token", "group": "Email", "type": "password",
+ "sensitive": True, "source": "env", "default": empty},
+ # Features
+ {"key": "context_engine_enabled", "label": "上下文压缩", "group": "Features",
+ "type": "toggle", "source": "yaml", "default": "false"},
+ {"key": "permissions_enabled", "label": "权限管控", "group": "Features",
+ "type": "toggle", "source": "yaml", "default": "false"},
+ {"key": "memory_forbidden_enabled", "label": "敏感信息过滤", "group": "Features",
+ "type": "toggle", "source": "yaml", "default": "false"},
+ {"key": "preferred_language", "label": "显示语言", "group": "Features", "type": "select",
+ "options": ["zh", "en"], "source": "yaml", "default": "zh"},
+ {"key": "evolution_auto_scan", "label": "自动扫描技能", "group": "Features",
+ "type": "toggle", "source": "env", "default": "false"},
+ ]
def _normalize_provider_value(value: str) -> str:
@@ -280,9 +375,17 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
payload["permissions_enabled"] = (
"true" if perm_cfg.get("enabled", False) else "false"
)
+ mem_cfg = (raw.get("memory") or {}).get("forbidden_memory_definition") or {}
+ payload["memory_forbidden_enabled"] = (
+ "true" if mem_cfg.get("enabled", False) else "false"
+ )
+ payload["preferred_language"] = raw.get("preferred_language") or "zh"
except Exception:
payload.setdefault("context_engine_enabled", "false")
payload.setdefault("permissions_enabled", "false")
+ payload.setdefault("memory_forbidden_enabled", "false")
+ payload.setdefault("preferred_language", "zh")
+ payload["schema"] = _build_config_schema()
await channel.send_response(ws, req_id, ok=True, payload=payload)
async def _config_set(ws, req_id, params, session_id):
@@ -324,15 +427,30 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
return
env_updates[env_key] = "" if val is None else str(val).strip()
- for param_key in _CLI_CONFIG_YAML_KEYS:
+ for param_key, setter in _CLI_CONFIG_YAML_SETTERS.items():
if param_key not in params:
continue
- parsed = str(params[param_key]).strip().lower() in ("true", "1", "yes")
+ raw_value = str(params[param_key]).strip()
+ if param_key == "preferred_language":
+ normalized_lang = raw_value.lower()
+ if normalized_lang not in _PREFERRED_LANGUAGE_OPTIONS:
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error=(
+ f"preferred_language must be one of "
+ f"{list(_PREFERRED_LANGUAGE_OPTIONS)}"
+ ),
+ code="BAD_REQUEST",
+ )
+ return
try:
- if param_key == "context_engine_enabled":
- update_context_engine_enabled_in_config(parsed)
- elif param_key == "permissions_enabled":
- update_permissions_enabled_in_config(parsed)
+ if param_key == "preferred_language":
+ setter(raw_value)
+ else:
+ parsed = raw_value.lower() in ("true", "1", "yes")
+ setter(parsed)
yaml_updated.append(param_key)
except Exception as e:
logger.warning(
@@ -341,29 +459,25 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
for env_key, value in env_updates.items():
os.environ[env_key] = value
- applied_without_restart = True
+ # env 变量直接写 os.environ 立即生效;YAML 改动需要 agent 重启/热重载才生效
+ applied_without_restart = not yaml_updated
if env_updates:
_persist_env_updates(env_updates)
if yaml_updated:
- real_client = agent_client.get("value") if isinstance(agent_client, dict) else agent_client
+ real_client = (
+ agent_client.get("value")
+ if isinstance(agent_client, dict)
+ else agent_client
+ )
await _clear_agent_config_cache(real_client)
- if env_updates or yaml_updated:
- if on_config_saved:
- config_payload = get_config()
- callback_result = on_config_saved(
- set(env_updates.keys()) | set(yaml_updated),
- env_updates=dict(env_updates),
- config_payload=config_payload,
- )
- if inspect.isawaitable(callback_result):
- callback_result = await callback_result
- applied_without_restart = bool(callback_result)
-
updated_param_keys = [
k for k, e in _CLI_CONFIG_SET_ENV_MAP.items() if e in env_updates
] + yaml_updated
+
+ # 先回包再执行 on_config_saved(含 Agent 热重载),
+ # 避免 WebSocket 长时间无响应、CLI 误以为无反馈。
await channel.send_response(
ws,
req_id,
@@ -374,6 +488,20 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
},
)
+ if env_updates or yaml_updated:
+ if on_config_saved:
+ try:
+ config_payload = get_config()
+ callback_result = on_config_saved(
+ set(env_updates.keys()) | set(yaml_updated),
+ env_updates=dict(env_updates),
+ config_payload=config_payload,
+ )
+ if inspect.isawaitable(callback_result):
+ await callback_result
+ except Exception as e: # noqa: BLE001
+ logger.warning("[cli config.set] on_config_saved failed: %s", e)
+
async def _config_validate_model(ws, req_id, params, session_id):
if not isinstance(params, dict):
await channel.send_response(
@@ -483,7 +611,6 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
)
async def _session_list(ws, req_id, params, session_id):
- import time
from jiuwenclaw.e2a.gateway_normalize import e2a_from_agent_fields
from jiuwenclaw.schema.message import ReqMethod
@@ -496,9 +623,15 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
limit = int(raw_limit.strip())
limit = max(1, min(limit, 200))
- real_client = agent_client.get("value") if isinstance(agent_client, dict) else agent_client
+ real_client = (
+ agent_client.get("value")
+ if isinstance(agent_client, dict)
+ else agent_client
+ )
if real_client is None:
- await channel.send_response(ws, req_id, ok=True, payload={"sessions": []})
+ await channel.send_response(
+ ws, req_id, ok=True, payload={"sessions": []}
+ )
return
env = e2a_from_agent_fields(
request_id=req_id,
@@ -513,12 +646,19 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
if not resp.ok:
await channel.send_response(ws, req_id, ok=False, error="session.list failed")
return
- all_sessions = resp.payload.get("sessions", []) if isinstance(resp.payload, dict) else []
- cli_sessions = [s for s in all_sessions if s.get("channel_id", "") == "tui"][:limit]
+ all_sessions = (
+ resp.payload.get("sessions", [])
+ if isinstance(resp.payload, dict)
+ else []
+ )
+ cli_sessions = [
+ s for s in all_sessions if s.get("channel_id", "") == "tui"
+ ][:limit]
await channel.send_response(ws, req_id, ok=True, payload={"sessions": cli_sessions})
async def _session_create(ws, req_id, params, session_id):
from jiuwenclaw.utils import get_agent_sessions_dir
+ from jiuwenclaw.agentserver.session_metadata import init_session_metadata
if not isinstance(params, dict):
await channel.send_response(
@@ -544,6 +684,12 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
)
return
session_dir.mkdir()
+ # 初始化元数据(与 web channel 对齐)
+ init_session_metadata(
+ session_id=target,
+ channel_id="tui",
+ title=str(params.get("title") or "").strip(),
+ )
await channel.send_response(ws, req_id, ok=True, payload={"session_id": target})
async def _session_delete(ws, req_id, params, session_id):
@@ -578,6 +724,64 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
shutil.rmtree(session_dir)
await channel.send_response(ws, req_id, ok=True, payload={"session_id": target})
+ async def _session_rename(ws, req_id, params, session_id):
+ """优先经 E2A 转发至 AgentWebSocketServer._handle_session_rename;无 agent 或转发失败时本地回退。"""
+ from jiuwenclaw.agentserver.session_rename import apply_session_rename
+ from jiuwenclaw.e2a.gateway_normalize import e2a_from_agent_fields
+ from jiuwenclaw.schema.message import ReqMethod
+
+ real_client = (
+ agent_client.get("value")
+ if isinstance(agent_client, dict)
+ else agent_client
+ )
+ if real_client is not None:
+ try:
+ env = e2a_from_agent_fields(
+ request_id=req_id,
+ channel_id="tui",
+ session_id=session_id,
+ req_method=ReqMethod.SESSION_RENAME,
+ params=params if isinstance(params, dict) else {},
+ is_stream=False,
+ timestamp=time.time(),
+ )
+ resp = await real_client.send_request(env)
+ if resp.ok:
+ pl = resp.payload if isinstance(resp.payload, dict) else {}
+ await channel.send_response(ws, req_id, ok=True, payload=pl)
+ return
+ pl = resp.payload if isinstance(resp.payload, dict) else {}
+ err = pl.get("error", "session.rename failed")
+ code = pl.get("code") or None
+ if isinstance(code, str) and not code.strip():
+ code = None
+ await channel.send_response(
+ ws, req_id, ok=False, error=str(err), code=code
+ )
+ return
+ except Exception as e:
+ logger.warning(
+ "[cli session.rename] forward to agent failed, fallback local: %s",
+ e,
+ )
+
+ ok, payload, err, code = apply_session_rename(
+ params,
+ session_id,
+ init_channel_id="tui",
+ )
+ if ok:
+ await channel.send_response(ws, req_id, ok=True, payload=payload or {})
+ else:
+ await channel.send_response(
+ ws,
+ req_id,
+ ok=False,
+ error=err or "session.rename failed",
+ code=code,
+ )
+
async def _chat_send(ws, req_id, params, session_id):
await channel.send_response(
ws, req_id, ok=True, payload={"accepted": True, "session_id": session_id}
@@ -612,7 +816,6 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
await channel.send_response(ws, req_id, ok=True, payload=payload)
async def _command_model(ws, req_id, params, session_id):
- import time
from jiuwenclaw.e2a.gateway_normalize import e2a_from_agent_fields
from jiuwenclaw.schema.message import ReqMethod
@@ -671,7 +874,8 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
},
)
logger.info(
- "[cli command.model] 新增模型: name=%s, client_cfg=%s, model_config_obj=%s",
+ "[cli command.model] 新增模型: name=%s, "
+ "client_cfg=%s, model_config_obj=%s",
target,
client_cfg,
model_cfg_obj,
@@ -733,7 +937,10 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
ws,
req_id,
ok=False,
- error=f"Model '{target}' not found. Available: {', '.join(get_model_names())}",
+ error=(
+ f"Model '{target}' not found. "
+ f"Available: {', '.join(get_model_names())}"
+ ),
)
return
@@ -869,7 +1076,10 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
config_templates["timeout"] = resolved_cfg["timeout"]
add_or_update_model_in_config(
"default",
- {"model_client_config": config_templates, "model_config_obj": raw_model_config_obj},
+ {
+ "model_client_config": config_templates,
+ "model_config_obj": raw_model_config_obj,
+ },
)
logger.info("[cli command.model] 已重置 models.default 为环境变量引用")
except Exception as e:
@@ -917,6 +1127,7 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:
channel.register_local_handler(path, "session.list", _session_list)
channel.register_local_handler(path, "session.create", _session_create)
channel.register_local_handler(path, "session.delete", _session_delete)
+ channel.register_local_handler(path, "session.rename", _session_rename)
channel.register_local_handler(path, "chat.send", _chat_send)
channel.register_local_handler(path, "chat.resume", _chat_resume)
channel.register_local_handler(path, "chat.interrupt", _chat_interrupt)
diff --git a/jiuwenclaw/cli/src/app-state.ts b/jiuwenclaw/cli/src/app-state.ts
index 265c9ff604..2d6601d2f6 100644
--- a/jiuwenclaw/cli/src/app-state.ts
+++ b/jiuwenclaw/cli/src/app-state.ts
@@ -66,6 +66,7 @@ export interface AppSnapshot {
evolutionStatus: "idle" | "running";
contextCompression: ContextCompressionStats | null;
modelInfo: { provider: string; model: string; version: string };
+ sessionTitle: string;
}
export class CliPiAppState {
@@ -73,6 +74,7 @@ export class CliPiAppState {
private entries: HistoryItem[] = [];
private connectionStatus: ConnectionStatus = "idle";
private sessionId: string;
+ private sessionTitle: string = "";
private mode: "agent.plan" | "agent.fast" | "code.plan" | "code.normal" | "team" =
"agent.plan";
private themeName: ThemeName = getCurrentThemeName();
@@ -176,6 +178,12 @@ export class CliPiAppState {
safeRestoreHistory: (sessionId) => {
this.safeRestoreHistory(sessionId);
},
+ setSessionTitle: (title) => {
+ this.setSessionTitle(title);
+ },
+ safeFetchSessionTitle: (sessionId) => {
+ this.safeFetchSessionTitle(sessionId);
+ },
};
constructor(
@@ -283,6 +291,7 @@ export class CliPiAppState {
evolutionStatus: this.evolutionStatus,
contextCompression: this.contextCompression ? { ...this.contextCompression } : null,
modelInfo: this.modelInfo,
+ sessionTitle: this.sessionTitle,
};
}
@@ -319,6 +328,9 @@ export class CliPiAppState {
.length,
collapseToolGroups: this.collapseToolGroups,
expandToolGroups: this.expandToolGroups,
+ sessionTitle: snapshot.sessionTitle,
+ setSessionTitle: this.setSessionTitle,
+ enterConfigEditor: undefined, // AppScreen injects the real handler when executing slash commands.
};
}
@@ -351,6 +363,25 @@ readonly request = async <T = Record<string, unknown>>(
this.emitChange();
};
+ readonly setSessionTitle = (title: string): void => {
+ this.sessionTitle = title;
+ this.emitChange();
+ };
+
+ readonly safeFetchSessionTitle = (sessionId: string): void => {
+ void (async () => {
+ try {
+ const meta = await this.request<{ session_id: string; title: string }>(
+ "session.rename",
+ { session_id: sessionId },
+ );
+ this.setSessionTitle(meta.title || "");
+ } catch {
+ // 标题获取失败不影响核心功能
+ }
+ })();
+ };
+
readonly addItem = (item: HistoryItem): void => {
this.entries = [...this.entries, item];
this.lastError = item.kind === "error" ? item.content : this.lastError;
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/clear.ts b/jiuwenclaw/cli/src/core/commands/builtins/clear.ts
index ef938276ac..f37b174e24 100644
--- a/jiuwenclaw/cli/src/core/commands/builtins/clear.ts
+++ b/jiuwenclaw/cli/src/core/commands/builtins/clear.ts
@@ -26,6 +26,7 @@ export function createClearCommand(): SlashCommand {
}
ctx.updateSession(nextId);
+ ctx.setSessionTitle("");
ctx.clearEntries();
ctx.addItem(addInfo(nextId, `Started a fresh conversation in ${nextId}`, "i"));
await ctx.restoreHistory(nextId);
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/config.ts b/jiuwenclaw/cli/src/core/commands/builtins/config.ts
index 5e8ef6b06e..a816f97b82 100644
--- a/jiuwenclaw/cli/src/core/commands/builtins/config.ts
+++ b/jiuwenclaw/cli/src/core/commands/builtins/config.ts
@@ -1,5 +1,21 @@
import { addError, addInfo, extractObject, formatValue } from "../helpers.js";
-import { CommandKind, type SlashCommand } from "../types.js";
+import { CommandKind, type CommandContext, type SlashCommand } from "../types.js";
+
+const COMPLETION_SCHEMA_TTL_MS = 30_000;
+let cachedSchemaKeys: string[] | null = null;
+let cachedSchemaAt = 0;
+
+export interface ConfigItemSchema {
+ key: string;
+ label: string;
+ group: string;
+ type: "string" | "select" | "toggle" | "password";
+ options?: string[];
+ default?: string;
+ sensitive?: boolean;
+ description?: string;
+ source: "env" | "yaml";
+}
function flattenConfigEntries(
value: unknown,
@@ -35,16 +51,355 @@ function flattenConfigEntries(
return flattened.length > 0 ? flattened : prefix ? [{ label: prefix, value: "{}" }] : [];
}
+function maskSensitive(value: string): string {
+ if (!value || value.length <= 8) return "***";
+ return `${value.slice(0, 4)}****${value.slice(-4)}`;
+}
+
+function groupConfigSchemaByGroup(
+ schemas: ConfigItemSchema[],
+): Record<string, ConfigItemSchema[]> {
+ const groups: Record<string, ConfigItemSchema[]> = {};
+ for (const schema of schemas) {
+ const group = schema.group || "Other";
+ if (!groups[group]) groups[group] = [];
+ groups[group].push(schema);
+ }
+ return groups;
+}
+
+async function applyConfigSet(
+ ctx: CommandContext,
+ key: string,
+ value: string,
+ schema: ConfigItemSchema,
+): Promise<void> {
+ try {
+ const result = await ctx.request<{
+ updated: string[];
+ applied_without_restart: boolean;
+ }>("config.set", { [key]: value });
+ ctx.addItem(
+ addInfo(
+ ctx.sessionId,
+ result.applied_without_restart
+ ? `Config ${key} updated (applied)`
+ : `Config ${key} updated (restart required)`,
+ "c",
+ {
+ view: "kv",
+ title: "Config Updated",
+ items: [
+ { label: "key", value: key },
+ { label: "value", value: schema.sensitive ? "***" : value },
+ { label: "applied", value: String(result.applied_without_restart) },
+ ],
+ },
+ ),
+ );
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `config.set failed: ${message}`));
+ }
+}
+
+function buildConfigDisplayItems(
+ payload: Record<string, unknown> & { schema?: ConfigItemSchema[] },
+ key: string,
+): {
+ items: Array<{ label: string; value: string }>;
+ emptyMessage: string | null;
+} {
+ const displayPayload: Record<string, unknown> = {};
+ for (const [k, v] of Object.entries(payload)) {
+ if (k !== "schema" && k !== "app_version") {
+ displayPayload[k] = v;
+ }
+ }
+ // 若用户指定了 key 但后端未返回该字段,应明确提示未找到,而不是 fallback 回全部配置
+ if (key) {
+ if (displayPayload[key] === undefined) {
+ return { items: [], emptyMessage: `No config value found for ${key}` };
+ }
+ const single = { [key]: displayPayload[key] };
+ const objectPayload = extractObject(single);
+ const items = objectPayload
+ ? flattenConfigEntries(objectPayload)
+ : [{ label: key, value: formatValue(single[key]) }];
+ return { items, emptyMessage: null };
+ }
+ const objectPayload = extractObject(displayPayload);
+ const items = objectPayload
+ ? flattenConfigEntries(objectPayload)
+ : [{ label: "value", value: formatValue(displayPayload) }];
+ if (items.length === 0) {
+ return { items: [], emptyMessage: "No config values returned" };
+ }
+ return { items, emptyMessage: null };
+}
+
+function emitConfigGetDisplay(
+ ctx: CommandContext,
+ key: string,
+ payload: Record<string, unknown> & { schema?: ConfigItemSchema[] },
+): void {
+ const { items, emptyMessage } = buildConfigDisplayItems(payload, key);
+ if (emptyMessage) {
+ ctx.addItem(addInfo(ctx.sessionId, emptyMessage, "c"));
+ return;
+ }
+ ctx.addItem(
+ addInfo(ctx.sessionId, key ? `Config: ${key}` : "Config values", "c", {
+ view: "kv",
+ title: key ? `Config · ${key}` : "Config",
+ items,
+ }),
+ );
+}
+
+async function showConfigOverview(ctx: CommandContext): Promise<void> {
+ const payload = await ctx.request<Record<string, unknown> & { schema?: ConfigItemSchema[] }>(
+ "config.get",
+ {},
+ );
+ const schemaList = payload.schema ?? [];
+ const groups = groupConfigSchemaByGroup(schemaList);
+ const items: Array<{ label: string; value?: string; description?: string }> = [];
+
+ for (const [groupName, schemas] of Object.entries(groups)) {
+ items.push({ label: `── ${groupName} ──`, description: "" });
+ for (const schema of schemas) {
+ const currentValue = String(payload[schema.key] ?? "");
+ const displayValue =
+ schema.type === "toggle"
+ ? currentValue === "true" ? "Enabled" : "Disabled"
+ : schema.sensitive ? maskSensitive(currentValue) : currentValue;
+ items.push({
+ label: schema.key,
+ value: displayValue,
+ description: schema.description ?? schema.label,
+ });
+ }
+ }
+
+ ctx.addItem(
+ addInfo(ctx.sessionId, "Configuration", "c", {
+ view: "kv",
+ title: "Config",
+ items: [
+ ...items,
+ { label: "", description: "" },
+ { label: "Usage", value: "/config set <key> <value> or /config edit" },
+ ],
+ }),
+ );
+}
+
export function createConfigCommand(): SlashCommand {
return {
name: "config",
altNames: ["settings", "setting"],
- description: "View backend config",
- usage: "/config [key]",
- example: "/config model_name",
+ description: "View and manage backend configuration",
+ usage: "/config [get|set|list|edit|reset] [key] [value]",
+ example: "/config set model deepseek-chat",
kind: CommandKind.BUILT_IN,
takesArgs: true,
+ completion: async (ctx, _partial) => {
+ const subCommands = ["get", "set", "list", "edit", "reset"];
+ const now = Date.now();
+ if (cachedSchemaKeys && now - cachedSchemaAt < COMPLETION_SCHEMA_TTL_MS) {
+ return [...subCommands, ...cachedSchemaKeys];
+ }
+ try {
+ const payload = await ctx.request<{ schema?: ConfigItemSchema[] }>("config.get", {});
+ const configKeys = (payload.schema ?? []).map((item) => item.key);
+ cachedSchemaKeys = configKeys;
+ cachedSchemaAt = now;
+ return [...subCommands, ...configKeys];
+ } catch {
+ return [...subCommands];
+ }
+ },
+ subCommands: [
+ {
+ name: "get",
+ description: "View config value",
+ usage: "/config get [key]",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: async (ctx, args) => {
+ const key = args.trim();
+ let payload: unknown;
+ try {
+ payload = await ctx.request("config.get", key ? { key } : {});
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `failed to load config: ${message}`));
+ return;
+ }
+ emitConfigGetDisplay(ctx, key, payload as Record<string, unknown> & { schema?: ConfigItemSchema[] });
+ },
+ },
+ {
+ name: "set",
+ description: "Set config value",
+ usage: "/config set <key> <value>",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: async (ctx, args) => {
+ const [key, ...valueParts] = args.trim().split(/\s+/);
+ const value = valueParts.join(" ");
+ if (!key) {
+ ctx.addItem(addError(ctx.sessionId, "usage: /config set <key> <value>"));
+ return;
+ }
+ let configPayload: Record<string, unknown> & { schema?: ConfigItemSchema[] };
+ try {
+ configPayload = await ctx.request<Record<string, unknown> & { schema?: ConfigItemSchema[] }>(
+ "config.get",
+ {},
+ );
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `failed to load config for validation: ${message}`));
+ return;
+ }
+ const schema = (configPayload.schema ?? []).find((s) => s.key === key);
+ if (!schema) {
+ ctx.addItem(addError(ctx.sessionId, `Unknown config key: ${key}`));
+ return;
+ }
+ if (schema.type === "select" && schema.options) {
+ if (!value) {
+ if (ctx.enterConfigEditor) {
+ ctx.enterConfigEditor(key, configPayload);
+ } else {
+ ctx.addItem(
+ addError(ctx.sessionId, `Interactive selection not available. Options: ${schema.options.join(", ")}`),
+ );
+ }
+ return;
+ }
+ if (!schema.options.includes(value)) {
+ ctx.addItem(
+ addError(
+ ctx.sessionId,
+ `Invalid value "${value}" for ${key}. Options: ${schema.options.join(", ")}`,
+ ),
+ );
+ return;
+ }
+ }
+ if (schema.type === "toggle") {
+ const currentVal = String(configPayload[key] ?? "false");
+ const effectiveValue = value || (currentVal === "true" ? "false" : "true");
+ await applyConfigSet(ctx, key, effectiveValue, schema);
+ return;
+ }
+ if (!value) {
+ ctx.addItem(addError(ctx.sessionId, "usage: /config set <key> <value>"));
+ return;
+ }
+ await applyConfigSet(ctx, key, value, schema);
+ },
+ },
+ {
+ name: "list",
+ description: "List all configurable items",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: false,
+ action: async (ctx) => {
+ let payload: Record<string, unknown> & { schema?: ConfigItemSchema[] };
+ try {
+ payload = await ctx.request<Record<string, unknown> & { schema?: ConfigItemSchema[] }>(
+ "config.get",
+ {},
+ );
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `failed to load config: ${message}`));
+ return;
+ }
+ const schemaList = payload.schema ?? [];
+ const groups = groupConfigSchemaByGroup(schemaList);
+ const items: Array<{ label: string; value?: string; description?: string }> = [];
+ for (const [groupName, schemas] of Object.entries(groups)) {
+ items.push({ label: `── ${groupName} ──`, description: "" });
+ for (const schema of schemas) {
+ const currentValue = String(payload[schema.key] ?? "");
+ items.push({
+ label: schema.key,
+ value: schema.sensitive ? maskSensitive(currentValue) : currentValue,
+ description: schema.description ?? schema.label,
+ });
+ }
+ }
+ ctx.addItem(addInfo(ctx.sessionId, "All config items", "c", { view: "kv", title: "Config Items", items }));
+ },
+ },
+ {
+ name: "edit",
+ description: "Interactive configuration editor",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: false,
+ action: async (ctx) => {
+ let payload: Record<string, unknown> & { schema?: ConfigItemSchema[] };
+ try {
+ payload = await ctx.request<Record<string, unknown> & { schema?: ConfigItemSchema[] }>(
+ "config.get",
+ {},
+ );
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `failed to load config: ${message}`));
+ return;
+ }
+ if (ctx.enterConfigEditor) {
+ ctx.enterConfigEditor(undefined, payload);
+ } else {
+ ctx.addItem(addError(ctx.sessionId, "Interactive editor not available in this mode"));
+ }
+ },
+ },
+ {
+ name: "reset",
+ description: "Reset config to default value",
+ usage: "/config reset <key>",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ action: async (ctx, args) => {
+ const key = args.trim();
+ if (!key) {
+ ctx.addItem(addError(ctx.sessionId, "usage: /config reset <key>"));
+ return;
+ }
+ let configPayload: Record<string, unknown> & { schema?: ConfigItemSchema[] };
+ try {
+ configPayload = await ctx.request<Record<string, unknown> & { schema?: ConfigItemSchema[] }>(
+ "config.get",
+ {},
+ );
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `failed to load config: ${message}`));
+ return;
+ }
+ const schema = (configPayload.schema ?? []).find((s) => s.key === key);
+ if (!schema) {
+ ctx.addItem(addError(ctx.sessionId, `Unknown config key: ${key}`));
+ return;
+ }
+ const defaultValue =
+ schema.default !== undefined && schema.default !== null ? String(schema.default) : "";
+ await applyConfigSet(ctx, key, defaultValue, schema);
+ },
+ },
+ ],
action: async (ctx, args) => {
+ if (!args.trim()) {
+ await showConfigOverview(ctx);
+ return;
+ }
const key = args.trim();
let payload: unknown;
try {
@@ -54,30 +409,7 @@ export function createConfigCommand(): SlashCommand {
ctx.addItem(addError(ctx.sessionId, `failed to load config: ${message}`));
return;
}
-
- const objectPayload = extractObject(payload);
- const items = objectPayload
- ? flattenConfigEntries(objectPayload)
- : [{ label: key || "value", value: formatValue(payload) }];
-
- if (items.length === 0) {
- ctx.addItem(
- addInfo(
- ctx.sessionId,
- key ? `No config value found for ${key}` : "No config values returned",
- "c",
- ),
- );
- return;
- }
-
- ctx.addItem(
- addInfo(ctx.sessionId, key ? `Config: ${key}` : "Config values", "c", {
- view: "kv",
- title: key ? `Config · ${key}` : "Config",
- items,
- }),
- );
+ emitConfigGetDisplay(ctx, key, payload as Record<string, unknown> & { schema?: ConfigItemSchema[] });
},
};
-}
+}
\ No newline at end of file
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/rename.ts b/jiuwenclaw/cli/src/core/commands/builtins/rename.ts
new file mode 100644
index 0000000000..45d130a37c
--- /dev/null
+++ b/jiuwenclaw/cli/src/core/commands/builtins/rename.ts
@@ -0,0 +1,90 @@
+import { addError, addInfo } from "../helpers.js";
+import { CommandKind, type SlashCommand } from "../types.js";
+
+interface RenamePayload {
+ session_id: string;
+ title: string;
+ previous_title?: string;
+}
+
+export function createRenameCommand(): SlashCommand {
+ return {
+ name: "rename",
+ description: "Rename the current session title",
+ usage: "/rename [new title | clear]",
+ example: "/rename My Debug Session",
+ kind: CommandKind.BUILT_IN,
+ takesArgs: true,
+ completion: (_ctx, partial) => {
+ const suggestions: string[] = [];
+ if ("clear".startsWith(partial.toLowerCase())) {
+ suggestions.push("clear");
+ }
+ return suggestions;
+ },
+ action: async (ctx, args) => {
+ const value = args.trim();
+ const isClear = value.toLowerCase() === "clear";
+ try {
+ if (value === "") {
+ const payload = await ctx.request<{ session_id: string; title: string }>(
+ "session.rename",
+ {},
+ );
+ const currentTitle = payload.title || "(untitled)";
+ ctx.addItem(
+ addInfo(ctx.sessionId, `Current session title: ${currentTitle}`, "r", {
+ view: "kv",
+ title: "Rename",
+ items: [
+ { label: "session", value: ctx.sessionId },
+ { label: "title", value: currentTitle },
+ ],
+ }),
+ );
+ ctx.setSessionTitle(payload.title || "");
+ return;
+ }
+
+ if (isClear) {
+ const payload = await ctx.request<RenamePayload>(
+ "session.rename",
+ { title: "" },
+ );
+ ctx.addItem(
+ addInfo(ctx.sessionId, "Session title cleared", "r", {
+ view: "kv",
+ title: "Rename",
+ items: [
+ { label: "session", value: payload.session_id },
+ { label: "title", value: payload.title || "(untitled)" },
+ ],
+ }),
+ );
+ ctx.setSessionTitle(payload.title || "");
+ return;
+ }
+
+ const payload = await ctx.request<RenamePayload>(
+ "session.rename",
+ { title: value },
+ );
+ ctx.addItem(
+ addInfo(ctx.sessionId, `Session renamed to "${payload.title}"`, "r", {
+ view: "kv",
+ title: "Rename",
+ items: [
+ { label: "session", value: payload.session_id },
+ { label: "previous", value: payload.previous_title || "(untitled)" },
+ { label: "new", value: payload.title },
+ ],
+ }),
+ );
+ ctx.setSessionTitle(payload.title);
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ ctx.addItem(addError(ctx.sessionId, `rename failed: ${message}`));
+ }
+ },
+ };
+}
\ No newline at end of file
diff --git a/jiuwenclaw/cli/src/core/commands/builtins/resume.ts b/jiuwenclaw/cli/src/core/commands/builtins/resume.ts
index 1b277be79d..0a83bef4aa 100644
--- a/jiuwenclaw/cli/src/core/commands/builtins/resume.ts
+++ b/jiuwenclaw/cli/src/core/commands/builtins/resume.ts
@@ -75,6 +75,19 @@ export function createResumeCommand(): SlashCommand {
ctx.clearEntries();
ctx.addItem(addInfo(nextSessionId, `Resumed session ${nextSessionId}`, "r"));
void ctx.restoreHistory(nextSessionId);
+ // 异步拉取被恢复会话的标题;在拿到结果前保留上一会话的 title 显示,
+ // 避免 "清空 -> 回填" 造成状态栏闪烁。成功后覆盖,失败不影响核心功能。
+ void (async () => {
+ try {
+ const meta = await ctx.request<{ session_id: string; title: string }>(
+ "session.rename",
+ { session_id: nextSessionId },
+ );
+ ctx.setSessionTitle(meta.title || "");
+ } catch {
+ ctx.setSessionTitle("");
+ }
+ })();
return;
}
ctx.addItem(
diff --git a/jiuwenclaw/cli/src/core/commands/registry.ts b/jiuwenclaw/cli/src/core/commands/registry.ts
index 8d0b92e7cc..f27fa3e8d5 100644
--- a/jiuwenclaw/cli/src/core/commands/registry.ts
+++ b/jiuwenclaw/cli/src/core/commands/registry.ts
@@ -15,6 +15,7 @@ import { createModelCommand } from "./builtins/model.js";
import { createModeCommand } from "./builtins/mode.js";
import { createPlanCommand } from "./builtins/plan.js";
import { createResumeCommand } from "./builtins/resume.js";
+import { createRenameCommand } from "./builtins/rename.js";
import { createSessionCommand } from "./builtins/session.js";
import { createSkillsCommand } from "./builtins/skills.js";
import { createThemeCommand } from "./builtins/theme.js";
@@ -35,6 +36,7 @@ export function createBuiltinCommands(): SlashCommand[] {
createModeCommand(),
createPlanCommand(),
createResumeCommand(),
+ createRenameCommand(),
createSessionCommand(),
createSkillsCommand(),
createThemeCommand(),
diff --git a/jiuwenclaw/cli/src/core/commands/types.ts b/jiuwenclaw/cli/src/core/commands/types.ts
index 33ee3a7d86..4342b71b8d 100644
--- a/jiuwenclaw/cli/src/core/commands/types.ts
+++ b/jiuwenclaw/cli/src/core/commands/types.ts
@@ -2,6 +2,7 @@ import type { HistoryItem } from "../types.js";
import type { AccentColorName, ThemeName } from "../../ui/theme.js";
import type { PendingQuestionItem, UserAnswer } from "../event-handlers.js";
import type { FileAttachment } from "../protocol.js";
+import type { ConfigItemSchema } from "./builtins/config.js";
export type ConnectionStatus = "idle" | "connecting" | "connected" | "reconnecting" | "auth_failed";
@@ -51,6 +52,12 @@ export interface CommandContext {
collapsedToolGroupCount: number;
collapseToolGroups: (scope: "last" | "all") => void;
expandToolGroups: (scope: "last" | "all") => void;
+ sessionTitle: string;
+ setSessionTitle: (title: string) => void;
+ enterConfigEditor?: (
+ focusKey?: string,
+ configPayload?: Record<string, unknown> & { schema?: ConfigItemSchema[] },
+ ) => void;
}
export interface SlashCommand {
diff --git a/jiuwenclaw/cli/src/core/event-handlers.ts b/jiuwenclaw/cli/src/core/event-handlers.ts
index 19ec58cad2..fb3dcb0578 100644
--- a/jiuwenclaw/cli/src/core/event-handlers.ts
+++ b/jiuwenclaw/cli/src/core/event-handlers.ts
@@ -61,6 +61,8 @@ export interface AppEventDelegate {
appendTeamMessageEvent(event: TeamMessageEvent): void;
setEvolutionStatus(status: "idle" | "running"): void;
setContextCompression(stats: ContextCompressionStats | null): void;
+ setSessionTitle(title: string): void;
+ safeFetchSessionTitle(sessionId: string): void;
addToolCallPayload(
payload: Record<string, unknown>,
sessionId: string,
@@ -140,6 +142,7 @@ function handleConnectionAck(delegate: AppEventDelegate, frame: EventFrame): boo
const sessionId = delegate.getSessionId();
if (sessionId && delegate.getConnectionStatus() === "connected") {
delegate.safeRestoreHistory(sessionId);
+ delegate.safeFetchSessionTitle(sessionId);
}
return true;
}
@@ -675,6 +678,9 @@ export function handleIncomingFrame(delegate: AppEventDelegate, frame: EventFram
) {
delegate.setMode(mode as "agent.plan" | "agent.fast" | "code.plan" | "code.normal" | "team");
}
+ if (typeof payload.title === "string") {
+ delegate.setSessionTitle(payload.title);
+ }
return true;
}
diff --git a/jiuwenclaw/cli/src/ui/app-screen.ts b/jiuwenclaw/cli/src/ui/app-screen.ts
index ae27eaa5e1..cf9e5bd09e 100644
--- a/jiuwenclaw/cli/src/ui/app-screen.ts
+++ b/jiuwenclaw/cli/src/ui/app-screen.ts
@@ -25,6 +25,7 @@ import { addError, addInfo } from "../core/commands/helpers.js";
import type { FileAttachment } from "../core/protocol.js";
import type { ModelListPayload } from "../core/commands/builtins/model.js";
import type { SessionListPayload, SessionMeta } from "../core/commands/builtins/resume.js";
+import type { ConfigItemSchema } from "../core/commands/builtins/config.js";
import { handleAppScreenKeyInput } from "./keymap.js";
import { buildAppScreenLines } from "./screen-layout.js";
import {
@@ -61,6 +62,25 @@ type ModelListState = {
current: string;
};
+type ConfigEditorPhase = "select_group" | "select_item" | "select_value" | "input_value";
+
+type ConfigEditorState = {
+ phase: ConfigEditorPhase;
+ schemaList: ConfigItemSchema[];
+ currentValues: Record<string, string>;
+ selectedGroup: string | null;
+ selectedKey: string | null;
+ list: SelectList;
+};
+
+const IMAGE_MIME_TYPES: Record<string, string> = {
+ ".png": "image/png",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".gif": "image/gif",
+ ".webp": "image/webp",
+};
+
function resolveFdBinary(): string | null {
for (const candidate of ["fd", "fdfind"]) {
const result = spawnSync(candidate, ["--version"], {
@@ -311,6 +331,7 @@ export class AppScreen implements Component, Focusable {
private questionList: SelectList | null = null;
private resumeSessionList: ResumeSessionListState | null = null;
private modelList: ModelListState | null = null;
+ private configEditorState: ConfigEditorState | null = null;
private showTodos = true;
private showTeamPanel = false;
private selectedTeamMemberId: string | null = null;
@@ -469,6 +490,33 @@ export class AppScreen implements Component, Focusable {
return;
}
+ if (!snapshot.pendingQuestion && this.configEditorState !== null) {
+ if (this.configEditorState.phase === "input_value") {
+ // Handle Esc to cancel input and go back to group selection
+ if (matchesKey(data, "escape")) {
+ if (this.configEditorState.selectedGroup) {
+ const groupSchemas = this.configEditorState.schemaList.filter(
+ (s) => s.group === this.configEditorState!.selectedGroup,
+ );
+ this.showConfigGroupItems(
+ this.configEditorState.selectedGroup,
+ groupSchemas,
+ this.configEditorState.currentValues,
+ );
+ } else {
+ this.configEditorState = null;
+ this.tui.requestRender();
+ }
+ return;
+ }
+ this.editor.handleInput(data);
+ } else {
+ this.configEditorState.list.handleInput(data);
+ }
+ this.tui.requestRender();
+ return;
+ }
+
if (!snapshot.pendingQuestion && this.modelList !== null) {
this.modelList.list.handleInput(data);
this.tui.requestRender();
@@ -531,6 +579,7 @@ export class AppScreen implements Component, Focusable {
const editorLines = this.applySlashCommandHint(this.editor.render(width), width);
const composerPreviewLines: string[] = [];
const questionLines = [
+ ...this.buildConfigEditorLines(width),
...this.buildResumeSessionListLines(width),
...this.buildModelListLines(width),
...this.buildPendingQuestionLines(snapshot, width),
@@ -564,6 +613,21 @@ export class AppScreen implements Component, Focusable {
const { content, attachments } = this.buildOutgoingMessage(text);
+ // Config editor input_value phase: submit the typed value
+ if (this.configEditorState?.phase === "input_value" && this.configEditorState.selectedKey) {
+ const key = this.configEditorState.selectedKey;
+ const schema = this.configEditorState.schemaList.find((s) => s.key === key);
+ if (schema) {
+ void this.applyConfigEditorSet(key, text, schema, this.configEditorState.currentValues);
+ }
+ this.editor.setText("");
+ this.composerAttachments = [];
+ return;
+ }
+
+ const content = this.composeOutgoingMessage(text);
+ if (!content) return;
+
const snapshot = this.state.getSnapshot();
if (snapshot.pendingQuestion) {
if (this.questionList === null) {
@@ -593,6 +657,9 @@ export class AppScreen implements Component, Focusable {
await this.commands.execute(text, {
...this.state.getCommandContext(),
exitApp: this.exit,
+ enterConfigEditor: (focusKey, configPayload) => {
+ this.openConfigEditor(focusKey, configPayload);
+ },
});
} finally {
this.clearPendingSubmittedInput();
@@ -868,6 +935,312 @@ export class AppScreen implements Component, Focusable {
return {
content: text.replace(/[ \t]{2,}/g, " ").replace(/[ \t]+\n/g, "\n").trim(),
attachments: this.collectComposerAttachments(text),
+ private buildConfigEditorLines(width: number): string[] {
+ if (!this.configEditorState) {
+ return [];
+ }
+ const state = this.configEditorState;
+ const title =
+ state.phase === "select_group"
+ ? "Configuration Editor"
+ : state.phase === "select_item"
+ ? state.selectedGroup ?? "Config"
+ : state.phase === "select_value"
+ ? `Select value for "${state.selectedKey}"`
+ : `Enter new value for "${state.selectedKey}"`;
+ const hint =
+ state.phase === "input_value"
+ ? "Enter value · Esc back"
+ : "↑/↓ choose · Enter confirm · Esc cancel";
+
+ const lines: string[] = [
+ padToWidth(palette.status.warning(title), width),
+ ];
+
+ if (
+ (state.phase === "select_value" || state.phase === "input_value") &&
+ state.selectedKey
+ ) {
+ const schema = state.schemaList.find((s) => s.key === state.selectedKey);
+ const rawVal = state.currentValues[state.selectedKey] ?? "";
+ const currentVal = schema?.sensitive
+ ? rawVal.length > 8 ? `${rawVal.slice(0, 4)}****${rawVal.slice(-4)}` : rawVal ? "***" : "(empty)"
+ : rawVal || "(empty)";
+ lines.push(padToWidth(palette.text.dim(`current: ${currentVal}`), width));
+ }
+
+ if (state.phase === "input_value") {
+ lines.push(...this.editor.render(width));
+ } else {
+ lines.push(...state.list.render(width));
+ }
+
+ lines.push(padToWidth(palette.text.dim(hint), width));
+ return lines;
+ }
+
+ private openConfigEditor(
+ focusKey?: string,
+ configPayload?: Record<string, unknown> & { schema?: ConfigItemSchema[] },
+ ): void {
+ const schemaList = configPayload?.schema ?? [];
+ if (schemaList.length === 0) {
+ this.state.addItem(addError(this.state.getSnapshot().sessionId, "No config schema available"));
+ return;
+ }
+ const currentValues: Record<string, string> = {};
+ for (const schema of schemaList) {
+ currentValues[schema.key] = String(configPayload?.[schema.key] ?? "");
+ }
+
+ if (focusKey) {
+ const schema = schemaList.find((s) => s.key === focusKey);
+ if (schema && schema.type === "select" && schema.options) {
+ // 用临时的 select_group 状态承载 schemaList/currentValues,再 showConfigValueSelect 会替换成 select_value
+ this.configEditorState = {
+ phase: "select_group",
+ schemaList,
+ currentValues,
+ selectedGroup: null,
+ selectedKey: null,
+ list: new SelectList([], 1, selectListTheme),
+ };
+ this.showConfigValueSelect(schema, currentValues);
+ return;
+ }
+ }
+
+ this.showConfigGroupSelector(schemaList, currentValues);
+ }
+
+ private showConfigGroupSelector(
+ schemaList: ConfigItemSchema[],
+ currentValues: Record<string, string>,
+ ): void {
+ const groups: Record<string, ConfigItemSchema[]> = {};
+ for (const schema of schemaList) {
+ const group = schema.group || "Other";
+ if (!groups[group]) groups[group] = [];
+ groups[group].push(schema);
+ }
+
+ const groupItems: SelectItem[] = Object.keys(groups).map((groupName) => ({
+ value: groupName,
+ label: groupName,
+ description: `${groups[groupName].length} items`,
+ }));
+ const list = new SelectList(
+ groupItems,
+ Math.min(Math.max(groupItems.length, 1), 8),
+ selectListTheme,
+ { minPrimaryColumnWidth: 24, maxPrimaryColumnWidth: 42 },
+ );
+ list.onSelect = (item) => {
+ this.showConfigGroupItems(item.value, groups[item.value], currentValues);
+ };
+ list.onCancel = () => {
+ this.configEditorState = null;
+ this.tui.requestRender();
+ };
+ this.configEditorState = {
+ phase: "select_group",
+ schemaList,
+ currentValues,
+ selectedGroup: null,
+ selectedKey: null,
+ list,
+ };
+ this.tui.requestRender();
+ }
+
+ private showConfigGroupItems(
+ groupName: string,
+ schemas: ConfigItemSchema[],
+ currentValues: Record<string, string>,
+ ): void {
+ const items: SelectItem[] = schemas.map((schema) => {
+ const val = currentValues[schema.key] ?? "";
+ const displayVal =
+ schema.type === "toggle"
+ ? val === "true" ? "Enabled" : "Disabled"
+ : schema.sensitive
+ ? val.length > 8 ? `${val.slice(0, 4)}****${val.slice(-4)}` : "***"
+ : val;
+ return {
+ value: schema.key,
+ label: `${schema.label}: ${displayVal}`,
+ description: schema.description,
+ };
+ });
+ items.push({ value: "__back__", label: "Back", description: "" });
+ const list = new SelectList(items, Math.min(Math.max(items.length, 1), 8), selectListTheme, {
+ minPrimaryColumnWidth: 24,
+ maxPrimaryColumnWidth: 42,
+ });
+ list.onSelect = (item) => {
+ if (item.value === "__back__") {
+ this.showConfigGroupSelector(this.configEditorState!.schemaList, currentValues);
+ return;
+ }
+ const schema = schemas.find((s) => s.key === item.value);
+ if (!schema) return;
+ this.handleConfigItemSelection(schema, currentValues);
+ };
+ list.onCancel = () => {
+ this.showConfigGroupSelector(this.configEditorState!.schemaList, currentValues);
+ };
+ this.configEditorState = {
+ phase: "select_item",
+ schemaList: this.configEditorState!.schemaList,
+ currentValues,
+ selectedGroup: groupName,
+ selectedKey: null,
+ list,
+ };
+ this.tui.requestRender();
+ }
+
+ private handleConfigItemSelection(
+ schema: ConfigItemSchema,
+ currentValues: Record<string, string>,
+ ): void {
+ if (schema.type === "toggle") {
+ const currentVal = currentValues[schema.key] ?? "false";
+ const newValue = currentVal === "true" ? "false" : "true";
+ void this.applyConfigEditorSet(schema.key, newValue, schema, currentValues);
+ return;
+ }
+ if (schema.type === "select" && schema.options) {
+ this.showConfigValueSelect(schema, currentValues);
+ return;
+ }
+ // string / password → input mode
+ this.editor.setText("");
+ this.configEditorState = {
+ phase: "input_value",
+ schemaList: this.configEditorState!.schemaList,
+ currentValues,
+ selectedGroup: this.configEditorState!.selectedGroup,
+ selectedKey: schema.key,
+ list: this.configEditorState!.list,
+ };
+ this.tui.requestRender();
+ }
+
+ private showConfigValueSelect(
+ schema: ConfigItemSchema,
+ currentValues: Record<string, string>,
+ ): void {
+ const currentValue = currentValues[schema.key] ?? "";
+ const items: SelectItem[] = (schema.options ?? []).map((option) => ({
+ value: option,
+ label: option,
+ description: option === currentValue ? "(current)" : undefined,
+ }));
+ const list = new SelectList(items, Math.min(Math.max(items.length, 1), 8), selectListTheme, {
+ minPrimaryColumnWidth: 24,
+ maxPrimaryColumnWidth: 42,
+ });
+ list.onSelect = (item) => {
+ void this.applyConfigEditorSet(schema.key, item.value, schema, currentValues);
+ };
+ list.onCancel = () => {
+ if (this.configEditorState?.selectedGroup) {
+ const groupSchemas = this.configEditorState.schemaList.filter(
+ (s) => s.group === this.configEditorState!.selectedGroup,
+ );
+ this.showConfigGroupItems(this.configEditorState.selectedGroup, groupSchemas, currentValues);
+ } else {
+ this.configEditorState = null;
+ this.tui.requestRender();
+ }
+ };
+ this.configEditorState = {
+ phase: "select_value",
+ schemaList: this.configEditorState!.schemaList,
+ currentValues,
+ selectedGroup: this.configEditorState?.selectedGroup ?? null,
+ selectedKey: schema.key,
+ list,
+ };
+ this.tui.requestRender();
+ }
+
+ private async applyConfigEditorSet(
+ key: string,
+ value: string,
+ schema: ConfigItemSchema,
+ currentValues: Record<string, string>,
+ ): Promise<void> {
+ try {
+ const result = await this.state.request<{
+ updated: string[];
+ applied_without_restart: boolean;
+ }>("config.set", { [key]: value });
+ currentValues[key] = value;
+ const msg = result.applied_without_restart
+ ? `✓ ${key}: ${schema.sensitive ? "***" : value} (applied)`
+ : `✓ ${key}: ${schema.sensitive ? "***" : value} (restart required)`;
+ this.state.addItem(addInfo(this.state.getSnapshot().sessionId, msg, "c"));
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ this.state.addItem(addError(this.state.getSnapshot().sessionId, `config.set failed: ${message}`));
+ }
+ if (this.configEditorState?.selectedGroup) {
+ const groupSchemas = this.configEditorState.schemaList.filter(
+ (s) => s.group === this.configEditorState!.selectedGroup,
+ );
+ this.showConfigGroupItems(this.configEditorState.selectedGroup, groupSchemas, currentValues);
+ } else {
+ this.configEditorState = null;
+ this.tui.requestRender();
+ }
+ }
+
+ private syncComposerAttachmentsFromEditor(): void {
+ if (this.syncingComposerInput) {
+ return;
+ }
+
+ const originalText = this.editor.getText();
+ const { normalizedText, attachments } = syncComposerImageTokens(
+ originalText,
+ this.composerAttachments,
+ (path) => this.isComposerImageFile(path),
+ );
+
+ this.composerAttachments = attachments;
+
+ if (normalizedText !== originalText) {
+ this.syncingComposerInput = true;
+ this.editor.setText(normalizedText);
+ this.syncingComposerInput = false;
+ }
+ }
+
+ private deleteComposerAttachmentTokenBackwards(): boolean {
+ const cursor = this.editor.getCursor();
+ const lines = this.editor.getLines();
+ const currentLine = lines[cursor.line] ?? "";
+ const tokenRange = findAttachmentTokenAtCursor(currentLine, cursor.col);
+ if (!tokenRange) {
+ return false;
+ }
+
+ const nextLine =
+ `${currentLine.slice(0, tokenRange.start)}${currentLine.slice(tokenRange.end)}`.replace(
+ / {2,}/g,
+ " ",
+ );
+ const nextLines = [...lines];
+ nextLines[cursor.line] = nextLine;
+ const nextText = nextLines.join("\n");
+ const nextCol = Math.min(tokenRange.start, nextLine.length);
+
+ this.syncingComposerInput = true;
+ this.editor.setText(nextText);
+ const editorState = this.editor as unknown as {
+ state?: { cursorLine: number; cursorCol: number };
};
}
@@ -1003,6 +1376,24 @@ export class AppScreen implements Component, Focusable {
description: command.description,
getArgumentCompletions: command.completion
? async (argumentPrefix: string): Promise<AutocompleteItem[] | null> => {
+ const trimmed = argumentPrefix.trim();
+ // pi-tui 把「第一个空格之后」整段当作 `/config` 的参数前缀去补全。
+ // 对 `/config set model deepseek`,前缀是 `set model deepseek`,补全项却是平铺的
+ // get/set/list/各 config key;若补全菜单仍打开,Enter 会先 applyCompletion 再提交,
+ // 会把整段参数替换成当前选中项(常为列表首项 `get`),看起来像「变成 /config get」且 set 未执行。
+ // 子命令名已匹配且后面还有 token 时关闭参数补全,让 Enter 直接提交当前输入。
+ if (command.subCommands?.length && trimmed.length > 0) {
+ const tokens = trimmed.split(/\s+/).filter(Boolean);
+ if (tokens.length >= 2) {
+ const head = tokens[0] ?? "";
+ const matchedSub = command.subCommands.some(
+ (sub) => sub.name === head || sub.altNames?.includes(head),
+ );
+ if (matchedSub) {
+ return null;
+ }
+ }
+ }
const items = await command.completion!(this.state.getCommandContext(), argumentPrefix);
return items.map((value) => ({
value,
diff --git a/jiuwenclaw/cli/src/ui/components/messages/render-compact-entry.ts b/jiuwenclaw/cli/src/ui/components/messages/render-compact-entry.ts
index 1f671daa41..5790aeca2b 100644
--- a/jiuwenclaw/cli/src/ui/components/messages/render-compact-entry.ts
+++ b/jiuwenclaw/cli/src/ui/components/messages/render-compact-entry.ts
@@ -10,6 +10,14 @@ import { CollapsedToolGroupMessageComponent, ToolGroupMessageComponent } from ".
import type { MessageRenderOptions, RenderedHistoryEntry } from "./types.js";
import { shouldExpandCompactToolGroup, shouldGapAfterEntry } from "./presentation-rules.js";
+function shouldRenderInfoExpanded(entry: Extract<HistoryItem, { kind: "info" }>): boolean {
+ if (entry.mediaItems?.length) return true;
+ const meta = entry.meta;
+ if (!meta) return false;
+ if (meta.view) return true;
+ return Boolean(meta.items && meta.items.length > 0);
+}
+
export function renderCompactEntry(
entry: HistoryItem,
width: number,
diff --git a/jiuwenclaw/cli/src/ui/screen-layout.ts b/jiuwenclaw/cli/src/ui/screen-layout.ts
index f73b34c0b4..f63ef2a294 100644
--- a/jiuwenclaw/cli/src/ui/screen-layout.ts
+++ b/jiuwenclaw/cli/src/ui/screen-layout.ts
@@ -96,6 +96,12 @@ function buildStatusLines(
const left: string[] = [];
const connectionLabel = connectionStatusLabel(snapshot.connectionStatus);
if (connectionLabel) left.push(connectionLabel);
+ if (snapshot.sessionTitle) {
+ const displayTitle = snapshot.sessionTitle.length > 30
+ ? snapshot.sessionTitle.slice(0, 30) + "..."
+ : snapshot.sessionTitle;
+ left.push(displayTitle);
+ }
if (snapshot.mode !== "agent.plan") left.push(`mode:${snapshot.mode}`);
if (snapshot.transcriptFoldMode !== "none") left.push(`fold:${snapshot.transcriptFoldMode}`);
const teamWorking =
diff --git a/jiuwenclaw/cli/src/ui/transcript-entry-selection.ts b/jiuwenclaw/cli/src/ui/transcript-entry-selection.ts
index 2fc089ad59..df11357f70 100644
--- a/jiuwenclaw/cli/src/ui/transcript-entry-selection.ts
+++ b/jiuwenclaw/cli/src/ui/transcript-entry-selection.ts
@@ -36,17 +36,20 @@ export function selectTranscriptEntries(snapshot: AppSnapshot): SelectedTranscri
: buildTranscriptEntries(snapshot.entries, snapshot.toolExecutions);
if (snapshot.transcriptFoldMode === "all") {
+ // 「all」折叠工具链噪声时仍需保留 info:含 /config、/help、/fold 等本地指令反馈,否则界面会像无任何输出。
entries = entries.filter(
(entry) =>
entry.kind === "user" ||
entry.kind === "assistant" ||
entry.kind === "thinking" ||
- entry.kind === "error",
+ entry.kind === "error" ||
+ entry.kind === "info",
);
} else if (snapshot.transcriptFoldMode === "thinking") {
entries = entries.filter((entry) => entry.kind !== "thinking");
} else if (snapshot.transcriptFoldMode === "tools") {
- entries = entries.filter((entry) => entry.kind !== "system" && entry.kind !== "info");
+ // 仅折叠 system;info 含 /config、/help 等反馈,隐藏会导致用户误以为命令无响应。
+ entries = entries.filter((entry) => entry.kind !== "system");
}
entries = entries
diff --git a/jiuwenclaw/config.py b/jiuwenclaw/config.py
index 21fa993bd6..6b9b5e629a 100644
--- a/jiuwenclaw/config.py
+++ b/jiuwenclaw/config.py
@@ -161,9 +161,12 @@ def update_channel_subsection_in_config(
def update_preferred_language_in_config(lang: str) -> None:
- """只更新顶层 preferred_language 并写回。"""
+ """只更新顶层 preferred_language 并写回。非法值回退为 zh,与 set_preferred_language_in_config_file 一致。"""
+ normalized = str(lang or "zh").strip().lower()
+ if normalized not in ("zh", "en"):
+ normalized = "zh"
data = _load_yaml_round_trip(_CONFIG_YAML_PATH)
- data["preferred_language"] = lang
+ data["preferred_language"] = normalized
_dump_yaml_round_trip(_CONFIG_YAML_PATH, data)
diff --git a/jiuwenclaw/schema/message.py b/jiuwenclaw/schema/message.py
index bedae90727..7370d9cc18 100644
--- a/jiuwenclaw/schema/message.py
+++ b/jiuwenclaw/schema/message.py
@@ -31,6 +31,7 @@ class ReqMethod(Enum):
SESSION_LIST = "session.list"
SESSION_CREATE = "session.create"
SESSION_DELETE = "session.delete"
+ SESSION_RENAME = "session.rename"
PATH_GET = "path.get"
PATH_SET = "path.set"