Merge remote-tracking branch 'origin/main' into codex/review-pr-3894
# Conflicts: # tests/utils/test_webui_transcript.py
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
"""Backend helpers for the bundled WebUI surface."""
|
||||
|
||||
@@ -0,0 +1,609 @@
|
||||
"""Settings REST helpers for the WebUI HTTP surface.
|
||||
|
||||
The WebSocket channel owns transport/authentication. This module owns the
|
||||
settings payload shape and the allowlisted config mutations exposed to WebUI.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from nanobot.config.loader import get_config_path, load_config, save_config
|
||||
from nanobot.providers.image_generation import (
|
||||
get_image_gen_provider,
|
||||
image_gen_provider_names,
|
||||
)
|
||||
from nanobot.providers.registry import PROVIDERS, find_by_name
|
||||
|
||||
QueryParams = dict[str, list[str]]
|
||||
|
||||
_WEB_SEARCH_PROVIDER_OPTIONS: tuple[dict[str, str], ...] = (
|
||||
{"name": "duckduckgo", "label": "DuckDuckGo", "credential": "none"},
|
||||
{"name": "brave", "label": "Brave Search", "credential": "api_key"},
|
||||
{"name": "tavily", "label": "Tavily", "credential": "api_key"},
|
||||
{"name": "searxng", "label": "SearXNG", "credential": "base_url"},
|
||||
{"name": "jina", "label": "Jina", "credential": "api_key"},
|
||||
{"name": "kagi", "label": "Kagi", "credential": "api_key"},
|
||||
{"name": "olostep", "label": "Olostep", "credential": "api_key"},
|
||||
)
|
||||
_WEB_SEARCH_PROVIDER_BY_NAME = {
|
||||
provider["name"]: provider for provider in _WEB_SEARCH_PROVIDER_OPTIONS
|
||||
}
|
||||
|
||||
_IMAGE_GENERATION_ASPECT_RATIOS = {
|
||||
"1:1",
|
||||
"3:4",
|
||||
"9:16",
|
||||
"4:3",
|
||||
"16:9",
|
||||
"3:2",
|
||||
"2:3",
|
||||
"21:9",
|
||||
}
|
||||
|
||||
|
||||
class WebUISettingsError(ValueError):
|
||||
"""User-facing settings validation failure."""
|
||||
|
||||
def __init__(self, message: str, *, status: int = 400) -> None:
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
self.status = status
|
||||
|
||||
|
||||
def _query_first(query: QueryParams, key: str) -> str | None:
|
||||
values = query.get(key)
|
||||
return values[0] if values else None
|
||||
|
||||
|
||||
def _query_first_alias(query: QueryParams, snake: str, camel: str) -> str | None:
|
||||
value = _query_first(query, snake)
|
||||
return _query_first(query, camel) if value is None else value
|
||||
|
||||
|
||||
def _mask_secret_hint(secret: str | None) -> str | None:
|
||||
if not secret:
|
||||
return None
|
||||
if len(secret) <= 8:
|
||||
return "••••"
|
||||
return f"{secret[:4]}••••{secret[-4:]}"
|
||||
|
||||
|
||||
def _provider_requires_api_key(spec: Any) -> bool:
|
||||
if spec.backend == "azure_openai":
|
||||
return True
|
||||
if spec.is_local or spec.is_direct:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _provider_configured_for_settings(spec: Any, provider_config: Any) -> bool:
|
||||
if _provider_requires_api_key(spec):
|
||||
return bool(provider_config.api_key)
|
||||
return bool(
|
||||
provider_config.api_key
|
||||
or provider_config.api_base
|
||||
or getattr(provider_config, "region", None)
|
||||
or getattr(provider_config, "profile", None)
|
||||
)
|
||||
|
||||
|
||||
def _parse_bool(value: str, field: str) -> bool:
|
||||
normalized = value.strip().lower()
|
||||
if normalized not in {"1", "0", "true", "false", "yes", "no"}:
|
||||
raise WebUISettingsError(f"{field} must be boolean")
|
||||
return normalized in {"1", "true", "yes"}
|
||||
|
||||
|
||||
def _image_generation_provider_rows(config: Any) -> list[dict[str, Any]]:
|
||||
rows: list[dict[str, Any]] = []
|
||||
for name in image_gen_provider_names():
|
||||
spec = find_by_name(name)
|
||||
provider_config = getattr(config.providers, name, None)
|
||||
configured = (
|
||||
_provider_configured_for_settings(spec, provider_config)
|
||||
if spec is not None and provider_config is not None
|
||||
else bool(getattr(provider_config, "api_key", None))
|
||||
)
|
||||
rows.append(
|
||||
{
|
||||
"name": name,
|
||||
"label": spec.label if spec is not None else name,
|
||||
"configured": configured,
|
||||
"api_key_hint": _mask_secret_hint(
|
||||
getattr(provider_config, "api_key", None)
|
||||
),
|
||||
"api_base": getattr(provider_config, "api_base", None),
|
||||
"default_api_base": (
|
||||
spec.default_api_base if spec and spec.default_api_base else None
|
||||
),
|
||||
}
|
||||
)
|
||||
return rows
|
||||
|
||||
|
||||
def settings_payload(*, requires_restart: bool = False) -> dict[str, Any]:
|
||||
config = load_config()
|
||||
defaults = config.agents.defaults
|
||||
active_preset_name = defaults.model_preset or "default"
|
||||
try:
|
||||
effective_preset = config.resolve_preset()
|
||||
except Exception:
|
||||
effective_preset = config.resolve_default_preset()
|
||||
active_preset_name = "default"
|
||||
|
||||
provider_name = (
|
||||
config.get_provider_name(effective_preset.model, preset=effective_preset)
|
||||
or effective_preset.provider
|
||||
)
|
||||
provider = config.get_provider(effective_preset.model, preset=effective_preset)
|
||||
selected_provider = provider_name
|
||||
if effective_preset.provider != "auto":
|
||||
spec = find_by_name(effective_preset.provider)
|
||||
selected_provider = spec.name if spec else provider_name
|
||||
|
||||
providers = []
|
||||
for spec in PROVIDERS:
|
||||
provider_config = getattr(config.providers, spec.name, None)
|
||||
if provider_config is None or spec.is_oauth:
|
||||
continue
|
||||
providers.append(
|
||||
{
|
||||
"name": spec.name,
|
||||
"label": spec.label,
|
||||
"configured": _provider_configured_for_settings(spec, provider_config),
|
||||
"api_key_required": _provider_requires_api_key(spec),
|
||||
"api_key_hint": _mask_secret_hint(provider_config.api_key),
|
||||
"api_base": provider_config.api_base,
|
||||
"default_api_base": spec.default_api_base or None,
|
||||
}
|
||||
)
|
||||
|
||||
search_config = config.tools.web.search
|
||||
image_config = config.tools.image_generation
|
||||
search_provider = (
|
||||
search_config.provider
|
||||
if search_config.provider in _WEB_SEARCH_PROVIDER_BY_NAME
|
||||
else "duckduckgo"
|
||||
)
|
||||
image_providers = _image_generation_provider_rows(config)
|
||||
selected_image_provider = next(
|
||||
(
|
||||
provider
|
||||
for provider in image_providers
|
||||
if provider["name"] == image_config.provider
|
||||
),
|
||||
None,
|
||||
)
|
||||
model_presets = [
|
||||
{
|
||||
"name": "default",
|
||||
"label": "Default",
|
||||
"active": active_preset_name == "default",
|
||||
"is_default": True,
|
||||
"model": defaults.model,
|
||||
"provider": defaults.provider,
|
||||
"max_tokens": defaults.max_tokens,
|
||||
"context_window_tokens": defaults.context_window_tokens,
|
||||
"temperature": defaults.temperature,
|
||||
"reasoning_effort": defaults.reasoning_effort,
|
||||
}
|
||||
]
|
||||
for name, preset in config.model_presets.items():
|
||||
model_presets.append(
|
||||
{
|
||||
"name": name,
|
||||
"label": name,
|
||||
"active": active_preset_name == name,
|
||||
"is_default": False,
|
||||
"model": preset.model,
|
||||
"provider": preset.provider,
|
||||
"max_tokens": preset.max_tokens,
|
||||
"context_window_tokens": preset.context_window_tokens,
|
||||
"temperature": preset.temperature,
|
||||
"reasoning_effort": preset.reasoning_effort,
|
||||
}
|
||||
)
|
||||
|
||||
exec_config = config.tools.exec
|
||||
return {
|
||||
"agent": {
|
||||
"model": effective_preset.model,
|
||||
"provider": selected_provider,
|
||||
"resolved_provider": provider_name,
|
||||
"has_api_key": bool(provider and provider.api_key),
|
||||
"model_preset": active_preset_name,
|
||||
"max_tokens": effective_preset.max_tokens,
|
||||
"context_window_tokens": effective_preset.context_window_tokens,
|
||||
"temperature": effective_preset.temperature,
|
||||
"reasoning_effort": effective_preset.reasoning_effort,
|
||||
"timezone": defaults.timezone,
|
||||
"bot_name": defaults.bot_name,
|
||||
"bot_icon": defaults.bot_icon,
|
||||
"tool_hint_max_length": defaults.tool_hint_max_length,
|
||||
},
|
||||
"model_presets": model_presets,
|
||||
"providers": providers,
|
||||
"web_search": {
|
||||
"provider": search_provider,
|
||||
"api_key_hint": _mask_secret_hint(search_config.api_key),
|
||||
"base_url": search_config.base_url or None,
|
||||
"max_results": search_config.max_results,
|
||||
"timeout": search_config.timeout,
|
||||
"providers": list(_WEB_SEARCH_PROVIDER_OPTIONS),
|
||||
},
|
||||
"web": {
|
||||
"enable": config.tools.web.enable,
|
||||
"proxy": config.tools.web.proxy,
|
||||
"user_agent": config.tools.web.user_agent,
|
||||
"search": {
|
||||
"max_results": search_config.max_results,
|
||||
"timeout": search_config.timeout,
|
||||
},
|
||||
"fetch": {
|
||||
"use_jina_reader": config.tools.web.fetch.use_jina_reader,
|
||||
},
|
||||
},
|
||||
"image_generation": {
|
||||
"enabled": image_config.enabled,
|
||||
"provider": image_config.provider,
|
||||
"provider_configured": bool(
|
||||
selected_image_provider and selected_image_provider["configured"]
|
||||
),
|
||||
"model": image_config.model,
|
||||
"default_aspect_ratio": image_config.default_aspect_ratio,
|
||||
"default_image_size": image_config.default_image_size,
|
||||
"max_images_per_turn": image_config.max_images_per_turn,
|
||||
"save_dir": image_config.save_dir,
|
||||
"providers": image_providers,
|
||||
},
|
||||
"runtime": {
|
||||
"config_path": str(get_config_path().expanduser()),
|
||||
"workspace_path": str(config.workspace_path),
|
||||
"gateway_host": config.gateway.host,
|
||||
"gateway_port": config.gateway.port,
|
||||
"heartbeat": {
|
||||
"enabled": config.gateway.heartbeat.enabled,
|
||||
"interval_s": config.gateway.heartbeat.interval_s,
|
||||
"keep_recent_messages": config.gateway.heartbeat.keep_recent_messages,
|
||||
},
|
||||
"dream": {
|
||||
"schedule": defaults.dream.describe_schedule(),
|
||||
"max_batch_size": defaults.dream.max_batch_size,
|
||||
"max_iterations": defaults.dream.max_iterations,
|
||||
"annotate_line_ages": defaults.dream.annotate_line_ages,
|
||||
},
|
||||
"unified_session": defaults.unified_session,
|
||||
},
|
||||
"advanced": {
|
||||
"restrict_to_workspace": config.tools.restrict_to_workspace,
|
||||
"ssrf_whitelist_count": len(config.tools.ssrf_whitelist),
|
||||
"mcp_server_count": len(config.tools.mcp_servers),
|
||||
"exec_enabled": exec_config.enable,
|
||||
"exec_sandbox": exec_config.sandbox or None,
|
||||
"exec_path_append_set": bool(exec_config.path_append),
|
||||
},
|
||||
"requires_restart": requires_restart,
|
||||
}
|
||||
|
||||
|
||||
def update_agent_settings(query: QueryParams) -> dict[str, Any]:
|
||||
config = load_config()
|
||||
defaults = config.agents.defaults
|
||||
changed = False
|
||||
restart_required = False
|
||||
|
||||
if "model_preset" in query or "modelPreset" in query:
|
||||
preset = (_query_first_alias(query, "model_preset", "modelPreset") or "").strip()
|
||||
preset_value = None if not preset or preset == "default" else preset
|
||||
if preset_value is not None and preset_value not in config.model_presets:
|
||||
raise WebUISettingsError("unknown model preset")
|
||||
if defaults.model_preset != preset_value:
|
||||
defaults.model_preset = preset_value
|
||||
changed = True
|
||||
|
||||
model = _query_first(query, "model")
|
||||
if model is not None:
|
||||
model = model.strip()
|
||||
if not model:
|
||||
raise WebUISettingsError("model is required")
|
||||
if defaults.model != model:
|
||||
defaults.model = model
|
||||
changed = True
|
||||
|
||||
provider = _query_first(query, "provider")
|
||||
if provider is not None:
|
||||
provider = provider.strip()
|
||||
if not provider:
|
||||
raise WebUISettingsError("provider is required")
|
||||
spec = find_by_name(provider)
|
||||
if spec is None:
|
||||
raise WebUISettingsError("unknown provider")
|
||||
provider_config = getattr(config.providers, provider, None)
|
||||
if (
|
||||
provider_config is None
|
||||
or not _provider_configured_for_settings(spec, provider_config)
|
||||
):
|
||||
raise WebUISettingsError("provider is not configured")
|
||||
if defaults.provider != provider:
|
||||
defaults.provider = provider
|
||||
changed = True
|
||||
|
||||
timezone = _query_first(query, "timezone")
|
||||
if timezone is not None:
|
||||
timezone = timezone.strip()
|
||||
if not timezone:
|
||||
raise WebUISettingsError("timezone is required")
|
||||
try:
|
||||
ZoneInfo(timezone)
|
||||
except Exception:
|
||||
raise WebUISettingsError("invalid timezone") from None
|
||||
if defaults.timezone != timezone:
|
||||
defaults.timezone = timezone
|
||||
changed = True
|
||||
restart_required = True
|
||||
|
||||
bot_name = _query_first_alias(query, "bot_name", "botName")
|
||||
if bot_name is not None:
|
||||
bot_name = bot_name.strip()
|
||||
if not bot_name:
|
||||
raise WebUISettingsError("bot_name is required")
|
||||
if defaults.bot_name != bot_name:
|
||||
defaults.bot_name = bot_name
|
||||
changed = True
|
||||
restart_required = True
|
||||
|
||||
bot_icon = _query_first_alias(query, "bot_icon", "botIcon")
|
||||
if bot_icon is not None:
|
||||
bot_icon = bot_icon.strip()
|
||||
if defaults.bot_icon != bot_icon:
|
||||
defaults.bot_icon = bot_icon
|
||||
changed = True
|
||||
restart_required = True
|
||||
|
||||
tool_hint_max_length = _query_first_alias(
|
||||
query,
|
||||
"tool_hint_max_length",
|
||||
"toolHintMaxLength",
|
||||
)
|
||||
if tool_hint_max_length is not None:
|
||||
try:
|
||||
parsed = int(tool_hint_max_length)
|
||||
except ValueError:
|
||||
raise WebUISettingsError("tool_hint_max_length must be an integer") from None
|
||||
if parsed < 20 or parsed > 500:
|
||||
raise WebUISettingsError("tool_hint_max_length must be between 20 and 500")
|
||||
if defaults.tool_hint_max_length != parsed:
|
||||
defaults.tool_hint_max_length = parsed
|
||||
changed = True
|
||||
restart_required = True
|
||||
|
||||
if changed:
|
||||
save_config(config)
|
||||
return settings_payload(requires_restart=restart_required)
|
||||
|
||||
|
||||
def update_provider_settings(query: QueryParams) -> dict[str, Any]:
|
||||
provider_name = (_query_first(query, "provider") or "").strip()
|
||||
if not provider_name:
|
||||
raise WebUISettingsError("provider is required")
|
||||
spec = find_by_name(provider_name)
|
||||
if spec is None or spec.is_oauth:
|
||||
raise WebUISettingsError("unknown provider")
|
||||
|
||||
config = load_config()
|
||||
provider_config = getattr(config.providers, spec.name, None)
|
||||
if provider_config is None:
|
||||
raise WebUISettingsError("unknown provider")
|
||||
|
||||
changed = False
|
||||
if "api_key" in query or "apiKey" in query:
|
||||
api_key = _query_first_alias(query, "api_key", "apiKey")
|
||||
api_key = (api_key or "").strip() or None
|
||||
if provider_config.api_key != api_key:
|
||||
provider_config.api_key = api_key
|
||||
changed = True
|
||||
|
||||
if "api_base" in query or "apiBase" in query:
|
||||
api_base = _query_first_alias(query, "api_base", "apiBase")
|
||||
api_base = (api_base or "").strip() or None
|
||||
if provider_config.api_base != api_base:
|
||||
provider_config.api_base = api_base
|
||||
changed = True
|
||||
|
||||
if changed:
|
||||
save_config(config)
|
||||
image_config = config.tools.image_generation
|
||||
restart_required = (
|
||||
changed
|
||||
and image_config.enabled
|
||||
and image_config.provider == spec.name
|
||||
and get_image_gen_provider(spec.name) is not None
|
||||
)
|
||||
return settings_payload(requires_restart=restart_required)
|
||||
|
||||
|
||||
def update_web_search_settings(query: QueryParams) -> dict[str, Any]:
|
||||
provider_name = (_query_first(query, "provider") or "").strip().lower()
|
||||
provider_option = _WEB_SEARCH_PROVIDER_BY_NAME.get(provider_name)
|
||||
if provider_option is None:
|
||||
raise WebUISettingsError("unknown web search provider")
|
||||
|
||||
config = load_config()
|
||||
search_config = config.tools.web.search
|
||||
web_config = config.tools.web
|
||||
previous_provider = search_config.provider
|
||||
changed = False
|
||||
restart_required = False
|
||||
|
||||
def set_search_value(attr: str, value: object) -> None:
|
||||
nonlocal changed
|
||||
if getattr(search_config, attr) != value:
|
||||
setattr(search_config, attr, value)
|
||||
changed = True
|
||||
|
||||
def set_fetch_value(attr: str, value: object) -> None:
|
||||
nonlocal changed
|
||||
if getattr(web_config.fetch, attr) != value:
|
||||
setattr(web_config.fetch, attr, value)
|
||||
changed = True
|
||||
|
||||
if search_config.provider != provider_name:
|
||||
search_config.provider = provider_name
|
||||
changed = True
|
||||
|
||||
credential = provider_option["credential"]
|
||||
if credential == "none":
|
||||
set_search_value("api_key", "")
|
||||
set_search_value("base_url", "")
|
||||
elif credential == "base_url":
|
||||
base_url = _query_first_alias(query, "base_url", "baseUrl")
|
||||
base_url = base_url.strip() if base_url is not None else None
|
||||
if not base_url and previous_provider == provider_name and search_config.base_url:
|
||||
base_url = search_config.base_url
|
||||
if not base_url:
|
||||
raise WebUISettingsError("base_url is required")
|
||||
set_search_value("base_url", base_url)
|
||||
set_search_value("api_key", "")
|
||||
else:
|
||||
api_key = _query_first_alias(query, "api_key", "apiKey")
|
||||
api_key = api_key.strip() if api_key is not None else None
|
||||
if not api_key and previous_provider == provider_name and search_config.api_key:
|
||||
api_key = search_config.api_key
|
||||
if not api_key:
|
||||
raise WebUISettingsError("api_key is required")
|
||||
set_search_value("api_key", api_key)
|
||||
set_search_value("base_url", "")
|
||||
|
||||
max_results = _query_first_alias(query, "max_results", "maxResults")
|
||||
if max_results is not None:
|
||||
try:
|
||||
parsed = int(max_results)
|
||||
except ValueError:
|
||||
raise WebUISettingsError("max_results must be an integer") from None
|
||||
if parsed < 1 or parsed > 10:
|
||||
raise WebUISettingsError("max_results must be between 1 and 10")
|
||||
set_search_value("max_results", parsed)
|
||||
|
||||
timeout = _query_first(query, "timeout")
|
||||
if timeout is not None:
|
||||
try:
|
||||
parsed_timeout = int(timeout)
|
||||
except ValueError:
|
||||
raise WebUISettingsError("timeout must be an integer") from None
|
||||
if parsed_timeout < 1 or parsed_timeout > 120:
|
||||
raise WebUISettingsError("timeout must be between 1 and 120")
|
||||
set_search_value("timeout", parsed_timeout)
|
||||
|
||||
use_jina_reader = _query_first_alias(query, "use_jina_reader", "useJinaReader")
|
||||
if use_jina_reader is not None:
|
||||
normalized = use_jina_reader.strip().lower()
|
||||
if normalized not in {"1", "0", "true", "false", "yes", "no"}:
|
||||
raise WebUISettingsError("use_jina_reader must be boolean")
|
||||
previous_jina_reader = web_config.fetch.use_jina_reader
|
||||
set_fetch_value("use_jina_reader", normalized in {"1", "true", "yes"})
|
||||
if web_config.fetch.use_jina_reader != previous_jina_reader:
|
||||
restart_required = True
|
||||
|
||||
if changed:
|
||||
save_config(config)
|
||||
return settings_payload(requires_restart=restart_required)
|
||||
|
||||
|
||||
def update_image_generation_settings(query: QueryParams) -> dict[str, Any]:
|
||||
config = load_config()
|
||||
image_config = config.tools.image_generation
|
||||
changed = False
|
||||
|
||||
provider_name = _query_first(query, "provider")
|
||||
if provider_name is not None:
|
||||
provider_name = provider_name.strip().lower()
|
||||
if not provider_name:
|
||||
raise WebUISettingsError("image generation provider is required")
|
||||
if get_image_gen_provider(provider_name) is None:
|
||||
raise WebUISettingsError("unknown image generation provider")
|
||||
if image_config.provider != provider_name:
|
||||
image_config.provider = provider_name
|
||||
changed = True
|
||||
|
||||
enabled = _query_first(query, "enabled")
|
||||
if enabled is not None:
|
||||
parsed_enabled = _parse_bool(enabled, "enabled")
|
||||
if image_config.enabled != parsed_enabled:
|
||||
image_config.enabled = parsed_enabled
|
||||
changed = True
|
||||
|
||||
model = _query_first(query, "model")
|
||||
if model is not None:
|
||||
model = model.strip()
|
||||
if not model:
|
||||
raise WebUISettingsError("image generation model is required")
|
||||
if len(model) > 200:
|
||||
raise WebUISettingsError("image generation model is too long")
|
||||
if image_config.model != model:
|
||||
image_config.model = model
|
||||
changed = True
|
||||
|
||||
default_aspect_ratio = _query_first_alias(
|
||||
query,
|
||||
"default_aspect_ratio",
|
||||
"defaultAspectRatio",
|
||||
)
|
||||
if default_aspect_ratio is not None:
|
||||
default_aspect_ratio = default_aspect_ratio.strip()
|
||||
if default_aspect_ratio not in _IMAGE_GENERATION_ASPECT_RATIOS:
|
||||
raise WebUISettingsError("unsupported image generation aspect ratio")
|
||||
if image_config.default_aspect_ratio != default_aspect_ratio:
|
||||
image_config.default_aspect_ratio = default_aspect_ratio
|
||||
changed = True
|
||||
|
||||
default_image_size = _query_first_alias(
|
||||
query,
|
||||
"default_image_size",
|
||||
"defaultImageSize",
|
||||
)
|
||||
if default_image_size is not None:
|
||||
default_image_size = default_image_size.strip()
|
||||
if not default_image_size:
|
||||
raise WebUISettingsError("default image size is required")
|
||||
if len(default_image_size) > 32 or not all(
|
||||
char.isascii() and (char.isalnum() or char in {"x", "X", ":", "-", "_"})
|
||||
for char in default_image_size
|
||||
):
|
||||
raise WebUISettingsError("unsupported image generation size")
|
||||
if image_config.default_image_size != default_image_size:
|
||||
image_config.default_image_size = default_image_size
|
||||
changed = True
|
||||
|
||||
max_images_per_turn = _query_first_alias(
|
||||
query,
|
||||
"max_images_per_turn",
|
||||
"maxImagesPerTurn",
|
||||
)
|
||||
if max_images_per_turn is not None:
|
||||
try:
|
||||
parsed_max = int(max_images_per_turn)
|
||||
except ValueError:
|
||||
raise WebUISettingsError("max_images_per_turn must be an integer") from None
|
||||
if parsed_max < 1 or parsed_max > 8:
|
||||
raise WebUISettingsError("max_images_per_turn must be between 1 and 8")
|
||||
if image_config.max_images_per_turn != parsed_max:
|
||||
image_config.max_images_per_turn = parsed_max
|
||||
changed = True
|
||||
|
||||
if image_config.enabled:
|
||||
selected_provider = next(
|
||||
(
|
||||
provider
|
||||
for provider in _image_generation_provider_rows(config)
|
||||
if provider["name"] == image_config.provider
|
||||
),
|
||||
None,
|
||||
)
|
||||
if not selected_provider or not selected_provider["configured"]:
|
||||
raise WebUISettingsError("image generation provider is not configured")
|
||||
|
||||
if changed:
|
||||
save_config(config)
|
||||
return settings_payload(requires_restart=changed)
|
||||
@@ -0,0 +1,193 @@
|
||||
"""Persisted WebUI sidebar workspace state.
|
||||
|
||||
This state is UI-only metadata, scoped to the active nanobot instance data
|
||||
directory (the directory containing the current config.json). It deliberately
|
||||
does not modify agent sessions.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.config.paths import get_webui_dir
|
||||
|
||||
WEBUI_SIDEBAR_STATE_SCHEMA_VERSION = 1
|
||||
_MAX_STATE_FILE_BYTES = 256 * 1024
|
||||
_MAX_LIST_ITEMS = 2_000
|
||||
_MAX_MAP_ITEMS = 2_000
|
||||
_MAX_KEY_LEN = 512
|
||||
_MAX_TITLE_LEN = 160
|
||||
_MAX_TAG_LEN = 40
|
||||
_ALLOWED_DENSITIES = {"comfortable", "compact"}
|
||||
_ALLOWED_SORTS = {"updated_desc", "created_desc", "title_asc"}
|
||||
|
||||
|
||||
def webui_sidebar_state_path() -> Path:
|
||||
return get_webui_dir() / "sidebar-state.json"
|
||||
|
||||
|
||||
def default_webui_sidebar_state() -> dict[str, Any]:
|
||||
return {
|
||||
"schema_version": WEBUI_SIDEBAR_STATE_SCHEMA_VERSION,
|
||||
"pinned_keys": [],
|
||||
"archived_keys": [],
|
||||
"title_overrides": {},
|
||||
"tags_by_key": {},
|
||||
"collapsed_groups": {},
|
||||
"view": {
|
||||
"density": "comfortable",
|
||||
"show_previews": False,
|
||||
"show_timestamps": False,
|
||||
"show_archived": False,
|
||||
"sort": "updated_desc",
|
||||
},
|
||||
"updated_at": None,
|
||||
}
|
||||
|
||||
|
||||
def _clean_string(value: Any, *, max_len: int = _MAX_KEY_LEN) -> str | None:
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
cleaned = value.strip()
|
||||
if not cleaned:
|
||||
return None
|
||||
return cleaned[:max_len]
|
||||
|
||||
|
||||
def _clean_string_list(value: Any, *, max_len: int = _MAX_KEY_LEN) -> list[str]:
|
||||
if not isinstance(value, list):
|
||||
return []
|
||||
out: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for item in value[:_MAX_LIST_ITEMS]:
|
||||
cleaned = _clean_string(item, max_len=max_len)
|
||||
if cleaned is None or cleaned in seen:
|
||||
continue
|
||||
seen.add(cleaned)
|
||||
out.append(cleaned)
|
||||
return out
|
||||
|
||||
|
||||
def _clean_bool_map(value: Any) -> dict[str, bool]:
|
||||
if not isinstance(value, dict):
|
||||
return {}
|
||||
out: dict[str, bool] = {}
|
||||
for key, raw in list(value.items())[:_MAX_MAP_ITEMS]:
|
||||
cleaned_key = _clean_string(key)
|
||||
if cleaned_key is None:
|
||||
continue
|
||||
out[cleaned_key] = bool(raw)
|
||||
return out
|
||||
|
||||
|
||||
def _clean_title_overrides(value: Any) -> dict[str, str]:
|
||||
if not isinstance(value, dict):
|
||||
return {}
|
||||
out: dict[str, str] = {}
|
||||
for key, raw_title in list(value.items())[:_MAX_MAP_ITEMS]:
|
||||
cleaned_key = _clean_string(key)
|
||||
cleaned_title = _clean_string(raw_title, max_len=_MAX_TITLE_LEN)
|
||||
if cleaned_key is None or cleaned_title is None:
|
||||
continue
|
||||
out[cleaned_key] = cleaned_title
|
||||
return out
|
||||
|
||||
|
||||
def _clean_tags_by_key(value: Any) -> dict[str, list[str]]:
|
||||
if not isinstance(value, dict):
|
||||
return {}
|
||||
out: dict[str, list[str]] = {}
|
||||
for key, raw_tags in list(value.items())[:_MAX_MAP_ITEMS]:
|
||||
cleaned_key = _clean_string(key)
|
||||
if cleaned_key is None:
|
||||
continue
|
||||
tags = _clean_string_list(raw_tags, max_len=_MAX_TAG_LEN)[:12]
|
||||
if tags:
|
||||
out[cleaned_key] = tags
|
||||
return out
|
||||
|
||||
|
||||
def _clean_view(value: Any) -> dict[str, Any]:
|
||||
default = default_webui_sidebar_state()["view"]
|
||||
if not isinstance(value, dict):
|
||||
return dict(default)
|
||||
density = value.get("density")
|
||||
sort = value.get("sort")
|
||||
return {
|
||||
"density": density if density in _ALLOWED_DENSITIES else default["density"],
|
||||
"show_previews": bool(value.get("show_previews", default["show_previews"])),
|
||||
"show_timestamps": bool(value.get("show_timestamps", default["show_timestamps"])),
|
||||
"show_archived": bool(value.get("show_archived", default["show_archived"])),
|
||||
"sort": sort if sort in _ALLOWED_SORTS else default["sort"],
|
||||
}
|
||||
|
||||
|
||||
def normalize_webui_sidebar_state(raw: Any) -> dict[str, Any]:
|
||||
"""Return a schema-v1 sidebar state from any older/partial input."""
|
||||
if not isinstance(raw, dict):
|
||||
raw = {}
|
||||
state = default_webui_sidebar_state()
|
||||
state["pinned_keys"] = _clean_string_list(raw.get("pinned_keys"))
|
||||
state["archived_keys"] = _clean_string_list(raw.get("archived_keys"))
|
||||
state["title_overrides"] = _clean_title_overrides(raw.get("title_overrides"))
|
||||
state["tags_by_key"] = _clean_tags_by_key(raw.get("tags_by_key"))
|
||||
state["collapsed_groups"] = _clean_bool_map(raw.get("collapsed_groups"))
|
||||
state["view"] = _clean_view(raw.get("view"))
|
||||
updated_at = raw.get("updated_at")
|
||||
state["updated_at"] = updated_at if isinstance(updated_at, str) else None
|
||||
return state
|
||||
|
||||
|
||||
def read_webui_sidebar_state() -> dict[str, Any]:
|
||||
path = webui_sidebar_state_path()
|
||||
if not path.is_file():
|
||||
return default_webui_sidebar_state()
|
||||
try:
|
||||
if path.stat().st_size > _MAX_STATE_FILE_BYTES:
|
||||
logger.warning("webui sidebar state too large, ignoring: {}", path)
|
||||
return default_webui_sidebar_state()
|
||||
with open(path, encoding="utf-8") as f:
|
||||
raw = json.load(f)
|
||||
except (OSError, json.JSONDecodeError) as e:
|
||||
logger.warning("read webui sidebar state failed {}: {}", path, e)
|
||||
return default_webui_sidebar_state()
|
||||
return normalize_webui_sidebar_state(raw)
|
||||
|
||||
|
||||
def write_webui_sidebar_state(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
state = normalize_webui_sidebar_state(raw)
|
||||
state["updated_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||||
encoded = json.dumps(
|
||||
state,
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
sort_keys=True,
|
||||
).encode("utf-8")
|
||||
if len(encoded) > _MAX_STATE_FILE_BYTES:
|
||||
raise ValueError("sidebar state is too large")
|
||||
|
||||
path = webui_sidebar_state_path()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_suffix(".json.tmp")
|
||||
with open(tmp, "wb") as f:
|
||||
f.write(encoded)
|
||||
f.write(b"\n")
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
os.replace(tmp, path)
|
||||
try:
|
||||
dir_fd = os.open(path.parent, os.O_RDONLY)
|
||||
except OSError:
|
||||
return state
|
||||
try:
|
||||
os.fsync(dir_fd)
|
||||
finally:
|
||||
os.close(dir_fd)
|
||||
return state
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Legacy WebUI JSON snapshot path helpers (JSON file); transcripts use transcript."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.config.paths import get_webui_dir
|
||||
from nanobot.session.manager import SessionManager
|
||||
from nanobot.webui.transcript import delete_webui_transcript
|
||||
|
||||
|
||||
def webui_thread_file_path(session_key: str) -> Path:
|
||||
stem = SessionManager.safe_key(session_key)
|
||||
return get_webui_dir() / f"{stem}.json"
|
||||
|
||||
|
||||
def delete_webui_thread(session_key: str) -> bool:
|
||||
"""Remove legacy WebUI JSON snapshot and append-only transcript for *session_key*."""
|
||||
removed = False
|
||||
path = webui_thread_file_path(session_key)
|
||||
if path.is_file():
|
||||
try:
|
||||
path.unlink()
|
||||
removed = True
|
||||
except OSError as e:
|
||||
logger.warning("Failed to delete webui thread file {}: {}", path, e)
|
||||
if delete_webui_transcript(session_key):
|
||||
removed = True
|
||||
return removed
|
||||
@@ -0,0 +1,592 @@
|
||||
"""Append-only WebUI display transcript (JSONL), separate from agent session."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.config.paths import get_webui_dir
|
||||
from nanobot.session.manager import SessionManager
|
||||
|
||||
WEBUI_TRANSCRIPT_SCHEMA_VERSION = 3
|
||||
_MAX_TRANSCRIPT_FILE_BYTES = 8 * 1024 * 1024
|
||||
|
||||
|
||||
def webui_transcript_path(session_key: str) -> Path:
|
||||
stem = SessionManager.safe_key(session_key)
|
||||
return get_webui_dir() / f"{stem}.jsonl"
|
||||
|
||||
|
||||
def read_transcript_lines(session_key: str) -> list[dict[str, Any]]:
|
||||
path = webui_transcript_path(session_key)
|
||||
if not path.is_file():
|
||||
return []
|
||||
size = path.stat().st_size
|
||||
if size > _MAX_TRANSCRIPT_FILE_BYTES:
|
||||
logger.warning("webui transcript too large, skipping: {}", path)
|
||||
return []
|
||||
lines_out: list[dict[str, Any]] = []
|
||||
try:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
for line_no, line in enumerate(f, start=1):
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
obj = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
logger.warning("bad jsonl at {} line {}", path, line_no)
|
||||
continue
|
||||
if isinstance(obj, dict):
|
||||
lines_out.append(obj)
|
||||
except OSError as e:
|
||||
logger.warning("read transcript failed {}: {}", path, e)
|
||||
return []
|
||||
return lines_out
|
||||
|
||||
|
||||
def append_transcript_object(session_key: str, obj: dict[str, Any]) -> None:
|
||||
raw = json.dumps(obj, ensure_ascii=False, separators=(",", ":"))
|
||||
if len(raw.encode("utf-8")) > _MAX_TRANSCRIPT_FILE_BYTES:
|
||||
msg = "webui transcript line too large"
|
||||
raise ValueError(msg)
|
||||
path = webui_transcript_path(session_key)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
line = raw + "\n"
|
||||
with open(path, "a", encoding="utf-8") as f:
|
||||
f.write(line)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
|
||||
|
||||
def delete_webui_transcript(session_key: str) -> bool:
|
||||
path = webui_transcript_path(session_key)
|
||||
if not path.is_file():
|
||||
return False
|
||||
try:
|
||||
path.unlink()
|
||||
return True
|
||||
except OSError as e:
|
||||
logger.warning("Failed to delete webui transcript {}: {}", path, e)
|
||||
return False
|
||||
|
||||
|
||||
def _format_tool_call_trace(call: Any) -> str | None:
|
||||
if not call or not isinstance(call, dict):
|
||||
return None
|
||||
fn = call.get("function")
|
||||
name = fn.get("name") if isinstance(fn, dict) else None
|
||||
if not isinstance(name, str) or not name:
|
||||
raw_name = call.get("name")
|
||||
name = raw_name if isinstance(raw_name, str) else ""
|
||||
if not name:
|
||||
return None
|
||||
args = (fn.get("arguments") if isinstance(fn, dict) else None) or call.get("arguments")
|
||||
if isinstance(args, str) and args.strip():
|
||||
return f"{name}({args})"
|
||||
if args and isinstance(args, dict):
|
||||
return f"{name}({json.dumps(args, ensure_ascii=False)})"
|
||||
return f"{name}()"
|
||||
|
||||
|
||||
def tool_trace_lines_from_events(events: Any) -> list[str]:
|
||||
if not isinstance(events, list):
|
||||
return []
|
||||
lines: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for event in events:
|
||||
if not event or not isinstance(event, dict):
|
||||
continue
|
||||
if event.get("phase") not in {"start", "end", "error"}:
|
||||
continue
|
||||
call_id = event.get("call_id")
|
||||
if isinstance(call_id, str) and call_id:
|
||||
if call_id in seen:
|
||||
continue
|
||||
seen.add(call_id)
|
||||
t = _format_tool_call_trace(event)
|
||||
if t:
|
||||
lines.append(t)
|
||||
return lines
|
||||
|
||||
|
||||
def _merge_unique_tool_trace_lines(
|
||||
previous_traces: list[str],
|
||||
lines: list[str],
|
||||
) -> tuple[list[str], bool]:
|
||||
seen_lines = set(previous_traces)
|
||||
traces = list(previous_traces)
|
||||
added = False
|
||||
for line in lines:
|
||||
if line in seen_lines:
|
||||
continue
|
||||
seen_lines.add(line)
|
||||
traces.append(line)
|
||||
added = True
|
||||
return traces, added
|
||||
|
||||
|
||||
def replay_transcript_to_ui_messages(
|
||||
lines: list[dict[str, Any]],
|
||||
*,
|
||||
augment_user_media: Callable[[list[str]], list[dict[str, Any]]] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Fold JSONL records into ``UIMessage``-shaped dicts for the WebUI.
|
||||
|
||||
Mirrors the core fold in ``useNanobotStream.ts`` (delta, reasoning,
|
||||
message+kind, turn_end). ``augment_user_media`` maps persisted filesystem
|
||||
paths to ``{url, name?}`` / attachment dicts the client expects.
|
||||
"""
|
||||
messages: list[dict[str, Any]] = []
|
||||
buffer_message_id: str | None = None
|
||||
buffer_parts: list[str] = []
|
||||
suppress_until_turn_end = False
|
||||
active_activity_segment_id: str | None = None
|
||||
active_file_edit_segment_id: str | None = None
|
||||
activity_segment_counter = 0
|
||||
_ts_base = int(time.time() * 1000)
|
||||
|
||||
def _new_id(prefix: str, idx: int) -> str:
|
||||
return f"{prefix}-{idx}-{uuid.uuid4().hex[:8]}"
|
||||
|
||||
def _new_activity_segment(*, activate: bool = True) -> str:
|
||||
nonlocal active_activity_segment_id, activity_segment_counter
|
||||
activity_segment_counter += 1
|
||||
segment_id = f"activity-{activity_segment_counter}"
|
||||
if activate:
|
||||
active_activity_segment_id = segment_id
|
||||
return segment_id
|
||||
|
||||
def _ensure_activity_segment() -> str:
|
||||
return active_activity_segment_id or _new_activity_segment()
|
||||
|
||||
def close_activity_for_answer() -> None:
|
||||
nonlocal active_activity_segment_id, active_file_edit_segment_id
|
||||
active_activity_segment_id = None
|
||||
active_file_edit_segment_id = None
|
||||
|
||||
def close_file_edit_phase_before_activity() -> None:
|
||||
nonlocal active_activity_segment_id, active_file_edit_segment_id
|
||||
if active_file_edit_segment_id:
|
||||
active_activity_segment_id = None
|
||||
active_file_edit_segment_id = None
|
||||
|
||||
def attach_reasoning_chunk(prev: list[dict[str, Any]], chunk: str, idx: int) -> None:
|
||||
for i in range(len(prev) - 1, -1, -1):
|
||||
candidate = prev[i]
|
||||
if candidate.get("role") == "user":
|
||||
break
|
||||
if candidate.get("kind") == "trace":
|
||||
break
|
||||
if candidate.get("role") != "assistant":
|
||||
continue
|
||||
content = str(candidate.get("content") or "")
|
||||
has_answer = len(content) > 0
|
||||
if (
|
||||
candidate.get("reasoningStreaming")
|
||||
or candidate.get("reasoning") is not None
|
||||
or has_answer
|
||||
or candidate.get("isStreaming")
|
||||
):
|
||||
prev[i] = {
|
||||
**candidate,
|
||||
"reasoning": (str(candidate.get("reasoning") or "")) + chunk,
|
||||
"reasoningStreaming": True,
|
||||
"activitySegmentId": candidate.get("activitySegmentId") or _ensure_activity_segment(),
|
||||
}
|
||||
return
|
||||
if not has_answer and candidate.get("isStreaming"):
|
||||
prev[i] = {
|
||||
**candidate,
|
||||
"reasoning": chunk,
|
||||
"reasoningStreaming": True,
|
||||
"activitySegmentId": candidate.get("activitySegmentId") or _ensure_activity_segment(),
|
||||
}
|
||||
return
|
||||
break
|
||||
segment = _ensure_activity_segment()
|
||||
prev.append(
|
||||
{
|
||||
"id": _new_id("as", idx),
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"isStreaming": True,
|
||||
"reasoning": chunk,
|
||||
"reasoningStreaming": True,
|
||||
"activitySegmentId": segment,
|
||||
"createdAt": _ts_base + idx,
|
||||
},
|
||||
)
|
||||
|
||||
def find_active_placeholder(prev: list[dict[str, Any]]) -> str | None:
|
||||
last = prev[-1] if prev else None
|
||||
if not last:
|
||||
return None
|
||||
if last.get("role") != "assistant" or last.get("kind") == "trace":
|
||||
return None
|
||||
if str(last.get("content") or ""):
|
||||
return None
|
||||
if not last.get("isStreaming"):
|
||||
return None
|
||||
return str(last.get("id"))
|
||||
|
||||
def close_reasoning(prev: list[dict[str, Any]]) -> None:
|
||||
for i in range(len(prev) - 1, -1, -1):
|
||||
if prev[i].get("reasoningStreaming"):
|
||||
prev[i] = {**prev[i], "reasoningStreaming": False}
|
||||
return
|
||||
|
||||
def is_reasoning_only_placeholder(m: dict[str, Any]) -> bool:
|
||||
return (
|
||||
m.get("role") == "assistant"
|
||||
and m.get("kind") != "trace"
|
||||
and not str(m.get("content") or "").strip()
|
||||
and bool(m.get("reasoning"))
|
||||
and not m.get("reasoningStreaming")
|
||||
and not m.get("media")
|
||||
)
|
||||
|
||||
def is_tool_trace_at(index: int) -> bool:
|
||||
m = messages[index] if 0 <= index < len(messages) else None
|
||||
return bool(m and m.get("kind") == "trace")
|
||||
|
||||
def prune_reasoning_only() -> None:
|
||||
nonlocal messages
|
||||
kept: list[dict[str, Any]] = []
|
||||
for i, m in enumerate(messages):
|
||||
if is_reasoning_only_placeholder(m) and not is_tool_trace_at(i + 1):
|
||||
continue
|
||||
kept.append(m)
|
||||
messages = kept
|
||||
|
||||
def stamp_latency(latency_ms: int) -> None:
|
||||
for i in range(len(messages) - 1, -1, -1):
|
||||
if messages[i].get("role") == "assistant" and messages[i].get("kind") != "trace":
|
||||
messages[i] = {
|
||||
**messages[i],
|
||||
"latencyMs": latency_ms,
|
||||
"isStreaming": False,
|
||||
}
|
||||
return
|
||||
|
||||
def absorb_complete(extra: dict[str, Any], idx: int) -> None:
|
||||
nonlocal active_activity_segment_id, active_file_edit_segment_id
|
||||
last = messages[-1] if messages else None
|
||||
if last and is_reasoning_only_placeholder(last):
|
||||
messages[-1] = {
|
||||
**last,
|
||||
**extra,
|
||||
"isStreaming": False,
|
||||
"reasoningStreaming": False,
|
||||
}
|
||||
else:
|
||||
messages.append(
|
||||
{
|
||||
"id": _new_id("as", idx),
|
||||
"role": "assistant",
|
||||
"createdAt": _ts_base + idx,
|
||||
**extra,
|
||||
},
|
||||
)
|
||||
active_activity_segment_id = None
|
||||
active_file_edit_segment_id = None
|
||||
|
||||
def _file_edit_key(edit: dict[str, Any]) -> str:
|
||||
call_id = str(edit.get("call_id") or "")
|
||||
tool = str(edit.get("tool") or "")
|
||||
if call_id:
|
||||
return f"{call_id}|{tool}"
|
||||
return f"{tool}|{edit.get('path') or ''}"
|
||||
|
||||
def find_file_edit_trace_index(
|
||||
segment: str | None,
|
||||
edits: list[dict[str, Any]],
|
||||
) -> int | None:
|
||||
incoming_keys = {_file_edit_key(edit) for edit in edits if isinstance(edit, dict)}
|
||||
for i in range(len(messages) - 1, -1, -1):
|
||||
candidate = messages[i]
|
||||
if candidate.get("role") == "user":
|
||||
break
|
||||
if candidate.get("kind") != "trace" or not candidate.get("fileEdits"):
|
||||
continue
|
||||
if segment and candidate.get("activitySegmentId") == segment:
|
||||
return i
|
||||
existing_edits = candidate.get("fileEdits")
|
||||
if not isinstance(existing_edits, list):
|
||||
continue
|
||||
for existing in existing_edits:
|
||||
if isinstance(existing, dict) and _file_edit_key(existing) in incoming_keys:
|
||||
return i
|
||||
return None
|
||||
|
||||
def upsert_file_edits(edits: list[dict[str, Any]], idx: int) -> None:
|
||||
nonlocal active_file_edit_segment_id
|
||||
if not edits:
|
||||
return
|
||||
segment = active_file_edit_segment_id
|
||||
target_index = find_file_edit_trace_index(segment, edits)
|
||||
if target_index is not None:
|
||||
last = messages[target_index]
|
||||
segment = str(last.get("activitySegmentId") or segment or _new_activity_segment(activate=False))
|
||||
active_file_edit_segment_id = segment
|
||||
else:
|
||||
if not segment:
|
||||
segment = _new_activity_segment(activate=False)
|
||||
active_file_edit_segment_id = segment
|
||||
messages.append(
|
||||
{
|
||||
"id": _new_id("tr", idx),
|
||||
"role": "tool",
|
||||
"kind": "trace",
|
||||
"content": "",
|
||||
"traces": [],
|
||||
"fileEdits": [],
|
||||
"activitySegmentId": segment,
|
||||
"createdAt": _ts_base + idx,
|
||||
},
|
||||
)
|
||||
target_index = len(messages) - 1
|
||||
last = messages[target_index]
|
||||
if not segment:
|
||||
segment = _new_activity_segment(activate=False)
|
||||
active_file_edit_segment_id = segment
|
||||
existing = list(last.get("fileEdits") or [])
|
||||
index_by_key = {
|
||||
_file_edit_key(edit): pos
|
||||
for pos, edit in enumerate(existing)
|
||||
if isinstance(edit, dict)
|
||||
}
|
||||
for edit in edits:
|
||||
if not isinstance(edit, dict):
|
||||
continue
|
||||
key = _file_edit_key(edit)
|
||||
if key in index_by_key:
|
||||
pos = index_by_key[key]
|
||||
merged = {**existing[pos], **edit}
|
||||
if edit.get("path") and not edit.get("pending"):
|
||||
merged.pop("pending", None)
|
||||
existing[pos] = merged
|
||||
else:
|
||||
index_by_key[key] = len(existing)
|
||||
existing.append(dict(edit))
|
||||
messages[target_index] = {
|
||||
**last,
|
||||
"fileEdits": existing,
|
||||
"activitySegmentId": last.get("activitySegmentId") or segment,
|
||||
}
|
||||
|
||||
for idx, rec in enumerate(lines):
|
||||
ev = rec.get("event")
|
||||
if ev == "user":
|
||||
active_activity_segment_id = None
|
||||
active_file_edit_segment_id = None
|
||||
text = rec.get("text")
|
||||
text_s = text if isinstance(text, str) else ""
|
||||
media_paths = rec.get("media_paths")
|
||||
paths: list[str] = []
|
||||
if isinstance(media_paths, list):
|
||||
paths = [str(p) for p in media_paths if p]
|
||||
media_att: list[dict[str, Any]] | None = None
|
||||
if paths and augment_user_media is not None:
|
||||
media_att = augment_user_media(paths)
|
||||
row: dict[str, Any] = {
|
||||
"id": _new_id("u", idx),
|
||||
"role": "user",
|
||||
"content": text_s,
|
||||
"createdAt": _ts_base + idx,
|
||||
}
|
||||
if media_att:
|
||||
row["media"] = media_att
|
||||
if all(m.get("kind") == "image" for m in media_att):
|
||||
row["images"] = [{"url": m.get("url"), "name": m.get("name")} for m in media_att]
|
||||
messages.append(row)
|
||||
continue
|
||||
|
||||
if ev == "file_edit":
|
||||
raw_edits = rec.get("edits")
|
||||
if isinstance(raw_edits, list):
|
||||
upsert_file_edits([e for e in raw_edits if isinstance(e, dict)], idx)
|
||||
continue
|
||||
|
||||
if ev == "delta":
|
||||
if suppress_until_turn_end:
|
||||
continue
|
||||
chunk = rec.get("text")
|
||||
if not isinstance(chunk, str):
|
||||
continue
|
||||
close_activity_for_answer()
|
||||
adopted = find_active_placeholder(messages) if buffer_message_id is None else None
|
||||
if buffer_message_id is None:
|
||||
if adopted:
|
||||
buffer_message_id = adopted
|
||||
else:
|
||||
buffer_message_id = _new_id("buf", idx)
|
||||
messages.append(
|
||||
{
|
||||
"id": buffer_message_id,
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"isStreaming": True,
|
||||
"createdAt": _ts_base + idx,
|
||||
},
|
||||
)
|
||||
buffer_parts.append(chunk)
|
||||
combined = "".join(buffer_parts)
|
||||
for i, m in enumerate(messages):
|
||||
if m.get("id") == buffer_message_id:
|
||||
messages[i] = {**m, "content": combined, "isStreaming": True}
|
||||
break
|
||||
continue
|
||||
|
||||
if ev == "stream_end":
|
||||
if suppress_until_turn_end:
|
||||
buffer_message_id = None
|
||||
buffer_parts = []
|
||||
continue
|
||||
buffer_message_id = None
|
||||
buffer_parts = []
|
||||
continue
|
||||
|
||||
if ev == "reasoning_delta":
|
||||
if suppress_until_turn_end:
|
||||
continue
|
||||
chunk = rec.get("text")
|
||||
if not isinstance(chunk, str) or not chunk:
|
||||
continue
|
||||
close_file_edit_phase_before_activity()
|
||||
attach_reasoning_chunk(messages, chunk, idx)
|
||||
continue
|
||||
|
||||
if ev == "reasoning_end":
|
||||
if suppress_until_turn_end:
|
||||
continue
|
||||
close_reasoning(messages)
|
||||
continue
|
||||
|
||||
if ev == "message":
|
||||
if suppress_until_turn_end and rec.get("kind") in (
|
||||
"tool_hint",
|
||||
"progress",
|
||||
"reasoning",
|
||||
):
|
||||
continue
|
||||
kind = rec.get("kind")
|
||||
if kind == "reasoning":
|
||||
line = rec.get("text")
|
||||
if not isinstance(line, str) or not line:
|
||||
continue
|
||||
close_file_edit_phase_before_activity()
|
||||
attach_reasoning_chunk(messages, line, idx)
|
||||
close_reasoning(messages)
|
||||
continue
|
||||
if kind in ("tool_hint", "progress"):
|
||||
structured = tool_trace_lines_from_events(rec.get("tool_events"))
|
||||
text = rec.get("text")
|
||||
trace_lines = structured if structured else ([text] if isinstance(text, str) and text else [])
|
||||
if not trace_lines:
|
||||
continue
|
||||
segment = _ensure_activity_segment()
|
||||
last = messages[-1] if messages else None
|
||||
if (
|
||||
last
|
||||
and last.get("kind") == "trace"
|
||||
and not last.get("isStreaming")
|
||||
and (last.get("activitySegmentId") in (None, segment))
|
||||
):
|
||||
prev_traces = list(last.get("traces") or [last.get("content")])
|
||||
if structured:
|
||||
merged_traces, added = _merge_unique_tool_trace_lines(prev_traces, structured)
|
||||
if not added:
|
||||
continue
|
||||
else:
|
||||
merged_traces = prev_traces + trace_lines
|
||||
merged = {
|
||||
**last,
|
||||
"traces": merged_traces,
|
||||
"content": merged_traces[-1],
|
||||
"activitySegmentId": last.get("activitySegmentId") or segment,
|
||||
}
|
||||
messages[-1] = merged
|
||||
else:
|
||||
messages.append(
|
||||
{
|
||||
"id": _new_id("tr", idx),
|
||||
"role": "tool",
|
||||
"kind": "trace",
|
||||
"content": trace_lines[-1],
|
||||
"traces": trace_lines,
|
||||
"activitySegmentId": segment,
|
||||
"createdAt": _ts_base + idx,
|
||||
},
|
||||
)
|
||||
continue
|
||||
|
||||
buffer_message_id = None
|
||||
buffer_parts = []
|
||||
text = rec.get("text")
|
||||
content_s = text if isinstance(text, str) else ""
|
||||
media_urls = rec.get("media_urls")
|
||||
media: list[dict[str, Any]] = []
|
||||
if isinstance(media_urls, list):
|
||||
for m in media_urls:
|
||||
if isinstance(m, dict) and m.get("url"):
|
||||
media.append(
|
||||
{
|
||||
"kind": "image",
|
||||
"url": str(m["url"]),
|
||||
"name": str(m.get("name") or ""),
|
||||
},
|
||||
)
|
||||
extra: dict[str, Any] = {"content": content_s}
|
||||
if media:
|
||||
extra["media"] = media
|
||||
lat = rec.get("latency_ms")
|
||||
if isinstance(lat, (int, float)) and lat >= 0:
|
||||
extra["latencyMs"] = int(lat)
|
||||
absorb_complete(extra, idx)
|
||||
if media:
|
||||
suppress_until_turn_end = True
|
||||
continue
|
||||
|
||||
if ev == "turn_end":
|
||||
suppress_until_turn_end = False
|
||||
active_activity_segment_id = None
|
||||
active_file_edit_segment_id = None
|
||||
for i, m in enumerate(messages):
|
||||
if m.get("isStreaming"):
|
||||
messages[i] = {**m, "isStreaming": False}
|
||||
prune_reasoning_only()
|
||||
lat = rec.get("latency_ms")
|
||||
if isinstance(lat, (int, float)) and lat >= 0:
|
||||
stamp_latency(int(lat))
|
||||
buffer_message_id = None
|
||||
buffer_parts = []
|
||||
continue
|
||||
|
||||
for m in messages:
|
||||
m.pop("isStreaming", None)
|
||||
m.pop("reasoningStreaming", None)
|
||||
return messages
|
||||
|
||||
|
||||
def build_webui_thread_response(
|
||||
session_key: str,
|
||||
*,
|
||||
augment_user_media: Callable[[list[str]], list[dict[str, Any]]] | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Return a payload compatible with ``WebuiThreadPersistedPayload``."""
|
||||
lines = read_transcript_lines(session_key)
|
||||
if not lines:
|
||||
return None
|
||||
msgs = replay_transcript_to_ui_messages(lines, augment_user_media=augment_user_media)
|
||||
return {
|
||||
"schemaVersion": WEBUI_TRANSCRIPT_SCHEMA_VERSION,
|
||||
"sessionKey": session_key,
|
||||
"messages": msgs,
|
||||
}
|
||||
Reference in New Issue
Block a user