feat(desktop): polish desktop shell and shared WebUI surfaces (#4195)
* feat(desktop): add native host scaffold * feat(webui): track turns and usage in gateway * feat(webui): polish desktop chat experience * feat(apps): add ArcGIS and Joplin logos * feat(desktop): polish shell and shared surfaces * fix(webui): avoid preview chips for glob references * test: align CI expectations for token fallback * feat(webui): preview prompt rail entries * feat(webui): add prompt navigator drawer * style(webui): refine prompt navigator placement * style(webui): align prompt navigator with header actions * style(webui): simplify prompt navigator header * refactor(webui): clean thread resource refresh * feat(desktop): add native reply notifications * fix(webui): preserve desktop restart and replay state * fix(desktop): harden gateway proxy startup * fix(web): fall back when readability is unavailable * fix(desktop): hide window instead of closing on macos * fix(webui): unify desktop header actions * fix(webui): simplify prompt history rows * fix(desktop): log notification delivery failures * chore(desktop): clean source package artifacts * fix(cron): support one-time relative reminders * fix(webui): reveal scroll button in place * Revert "fix(cron): support one-time relative reminders" This reverts commit 4c4661da120a3c7283e0768412bae48604e7390b. * refactor(webui): extract token usage heatmap * docs(desktop): clarify contributor guides --------- Co-authored-by: chengyongru <2755839590@qq.com>
This commit is contained in:
1 parent
a1b9577224
commit
ab9f49970d
103 files changed
+10483
-1003
No files matched your search
@@ -0,0 +1,137 @@
|
||||
"""Workspace-scoped source preview payloads for the WebUI."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import unquote, urlparse
|
||||
|
||||
from nanobot.security.workspace_access import WorkspaceScope
|
||||
from nanobot.security.workspace_policy import WorkspaceBoundaryError, resolve_allowed_path
|
||||
|
||||
MAX_FILE_PREVIEW_BYTES = 384 * 1024
|
||||
|
||||
|
||||
class WebUIFilePreviewError(ValueError):
|
||||
"""Raised when a file cannot be previewed through the WebUI."""
|
||||
|
||||
def __init__(self, status: int, message: str) -> None:
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.message = message
|
||||
|
||||
|
||||
def file_preview_payload(
|
||||
raw_path: str | None,
|
||||
*,
|
||||
scope: WorkspaceScope,
|
||||
max_bytes: int = MAX_FILE_PREVIEW_BYTES,
|
||||
) -> dict[str, Any]:
|
||||
"""Return a text preview for a file inside the session workspace."""
|
||||
|
||||
path = _clean_preview_path(raw_path)
|
||||
if not path:
|
||||
raise WebUIFilePreviewError(400, "missing path")
|
||||
if len(path) > 4096:
|
||||
raise WebUIFilePreviewError(400, "path is too long")
|
||||
|
||||
try:
|
||||
resolved = resolve_allowed_path(
|
||||
path,
|
||||
workspace=scope.project_path,
|
||||
allowed_root=scope.project_path,
|
||||
strict=True,
|
||||
)
|
||||
except FileNotFoundError as e:
|
||||
raise WebUIFilePreviewError(404, "file not found") from e
|
||||
except WorkspaceBoundaryError as e:
|
||||
raise WebUIFilePreviewError(403, "file is outside the current workspace") from e
|
||||
except OSError as e:
|
||||
raise WebUIFilePreviewError(400, "invalid path") from e
|
||||
|
||||
if not resolved.is_file():
|
||||
raise WebUIFilePreviewError(404, "file not found")
|
||||
|
||||
try:
|
||||
with open(resolved, "rb") as f:
|
||||
raw = f.read(max_bytes + 1)
|
||||
except OSError as e:
|
||||
raise WebUIFilePreviewError(500, "failed to read file") from e
|
||||
|
||||
if b"\0" in raw[:4096]:
|
||||
raise WebUIFilePreviewError(415, "binary files cannot be previewed")
|
||||
|
||||
truncated = len(raw) > max_bytes
|
||||
preview_bytes = raw[:max_bytes]
|
||||
try:
|
||||
content = preview_bytes.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
content = preview_bytes.decode("utf-8", errors="replace")
|
||||
|
||||
display_path = _display_path(resolved, scope.project_path)
|
||||
return {
|
||||
"path": str(resolved),
|
||||
"display_path": display_path,
|
||||
"project_path": str(scope.project_path),
|
||||
"language": _language_for_path(resolved),
|
||||
"content": content,
|
||||
"size": resolved.stat().st_size,
|
||||
"truncated": truncated,
|
||||
}
|
||||
|
||||
|
||||
def _clean_preview_path(raw_path: str | None) -> str:
|
||||
if raw_path is None:
|
||||
return ""
|
||||
value = raw_path.strip()
|
||||
if not value:
|
||||
return ""
|
||||
if value.startswith("file://"):
|
||||
parsed = urlparse(value)
|
||||
value = unquote(parsed.path)
|
||||
if re.match(r"^/[A-Za-z]:[\\/]", value):
|
||||
value = value[1:]
|
||||
else:
|
||||
value = unquote(value)
|
||||
value = value.split("?", 1)[0].split("#", 1)[0].strip()
|
||||
if not re.match(r"^[A-Za-z]:[\\/]", value):
|
||||
value = re.sub(r":\d+(?::\d+)?$", "", value)
|
||||
return value
|
||||
|
||||
|
||||
def _display_path(path: Path, root: Path) -> str:
|
||||
try:
|
||||
return path.relative_to(root).as_posix()
|
||||
except ValueError:
|
||||
return path.as_posix()
|
||||
|
||||
|
||||
def _language_for_path(path: Path) -> str:
|
||||
name = path.name.lower()
|
||||
ext = path.suffix.lower().lstrip(".")
|
||||
if name == "dockerfile":
|
||||
return "dockerfile"
|
||||
return {
|
||||
"cjs": "javascript",
|
||||
"css": "css",
|
||||
"cts": "typescript",
|
||||
"html": "html",
|
||||
"js": "javascript",
|
||||
"json": "json",
|
||||
"jsonl": "json",
|
||||
"jsx": "jsx",
|
||||
"md": "markdown",
|
||||
"mdx": "markdown",
|
||||
"mjs": "javascript",
|
||||
"mts": "typescript",
|
||||
"py": "python",
|
||||
"pyi": "python",
|
||||
"scss": "scss",
|
||||
"sh": "bash",
|
||||
"toml": "toml",
|
||||
"ts": "typescript",
|
||||
"tsx": "tsx",
|
||||
"yaml": "yaml",
|
||||
"yml": "yaml",
|
||||
}.get(ext, ext or "text")
|
||||
@@ -10,6 +10,7 @@ from loguru import logger as default_logger
|
||||
|
||||
from nanobot.webui.gateway_tokens import GatewayTokenStore
|
||||
from nanobot.webui.media_gateway import WebUIMediaGateway
|
||||
from nanobot.webui.transcript import WebUITranscriptRecorder
|
||||
from nanobot.webui.workspaces import WebUIWorkspaceController
|
||||
from nanobot.webui.ws_http import GatewayHTTPHandler
|
||||
|
||||
@@ -21,8 +22,10 @@ class GatewayServices:
|
||||
http: GatewayHTTPHandler
|
||||
tokens: GatewayTokenStore
|
||||
media: WebUIMediaGateway
|
||||
transcripts: WebUITranscriptRecorder
|
||||
workspaces: WebUIWorkspaceController
|
||||
session_manager: Any | None
|
||||
cron_service: Any | None
|
||||
|
||||
|
||||
def build_gateway_services(
|
||||
@@ -36,6 +39,8 @@ def build_gateway_services(
|
||||
runtime_model_name: Any | None,
|
||||
runtime_surface: str,
|
||||
runtime_capabilities_overrides: dict[str, Any] | None,
|
||||
disabled_skills: set[str] | None = None,
|
||||
cron_service: Any | None = None,
|
||||
logger: Any = default_logger,
|
||||
) -> GatewayServices:
|
||||
tokens = GatewayTokenStore()
|
||||
@@ -43,6 +48,7 @@ def build_gateway_services(
|
||||
workspace_path=workspace_path,
|
||||
logger=logger,
|
||||
)
|
||||
transcripts = WebUITranscriptRecorder(log=logger)
|
||||
workspaces = WebUIWorkspaceController(
|
||||
session_manager=session_manager,
|
||||
default_workspace=workspace_path,
|
||||
@@ -59,12 +65,17 @@ def build_gateway_services(
|
||||
tokens=tokens,
|
||||
media=media,
|
||||
workspaces=workspaces,
|
||||
skills_workspace_path=workspace_path,
|
||||
disabled_skills=disabled_skills,
|
||||
cron_service=cron_service,
|
||||
log=logger,
|
||||
)
|
||||
return GatewayServices(
|
||||
http=http,
|
||||
tokens=tokens,
|
||||
media=media,
|
||||
transcripts=transcripts,
|
||||
workspaces=workspaces,
|
||||
session_manager=session_manager,
|
||||
cron_service=cron_service,
|
||||
)
|
||||
@@ -16,8 +16,8 @@ from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal, Mapping
|
||||
|
||||
from nanobot.apps.protocol import app_manifest, compact_dict
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.apps.protocol import app_manifest, compact_dict
|
||||
from nanobot.config.loader import load_config, resolve_config_env_vars, save_config
|
||||
from nanobot.config.paths import get_runtime_subdir
|
||||
from nanobot.config.schema import MCPServerConfig
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Session-scoped automation payloads for the embedded WebUI."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Protocol
|
||||
|
||||
from nanobot.cron.types import CronJob
|
||||
|
||||
|
||||
class _CronServiceLike(Protocol):
|
||||
def list_jobs(self, *, include_disabled: bool = False) -> list[CronJob]: ...
|
||||
|
||||
|
||||
def session_automations_payload(
|
||||
cron_service: _CronServiceLike | None,
|
||||
session_key: str,
|
||||
) -> dict[str, Any]:
|
||||
"""Return user-created automation jobs attached to a WebUI session."""
|
||||
jobs: list[CronJob] = []
|
||||
if cron_service is not None:
|
||||
all_jobs = cron_service.list_jobs(include_disabled=True)
|
||||
jobs = [job for job in all_jobs if _job_matches_session(job, session_key)]
|
||||
return {"jobs": [_serialize_job(job) for job in jobs]}
|
||||
|
||||
|
||||
def _job_matches_session(job: CronJob, session_key: str) -> bool:
|
||||
payload = job.payload
|
||||
if payload.kind != "agent_turn":
|
||||
return False
|
||||
if payload.session_key:
|
||||
return payload.session_key == session_key
|
||||
if payload.channel and payload.to:
|
||||
return f"{payload.channel}:{payload.to}" == session_key
|
||||
return False
|
||||
|
||||
|
||||
def _serialize_job(job: CronJob) -> dict[str, Any]:
|
||||
return {
|
||||
"id": job.id,
|
||||
"name": job.name,
|
||||
"enabled": job.enabled,
|
||||
"schedule": {
|
||||
"kind": job.schedule.kind,
|
||||
"at_ms": job.schedule.at_ms,
|
||||
"every_ms": job.schedule.every_ms,
|
||||
"expr": job.schedule.expr,
|
||||
"tz": job.schedule.tz,
|
||||
},
|
||||
"payload": {
|
||||
"message": job.payload.message,
|
||||
},
|
||||
"state": {
|
||||
"next_run_at_ms": job.state.next_run_at_ms,
|
||||
"last_status": job.state.last_status,
|
||||
},
|
||||
}
|
||||
@@ -23,6 +23,7 @@ from nanobot.providers.image_generation import (
|
||||
)
|
||||
from nanobot.providers.registry import PROVIDERS, find_by_name
|
||||
from nanobot.security.workspace_access import workspace_sandbox_status
|
||||
from nanobot.webui.token_usage import token_usage_payload
|
||||
from nanobot.webui.workspaces import (
|
||||
read_webui_default_access_mode,
|
||||
write_webui_default_access_mode,
|
||||
@@ -747,6 +748,7 @@ def settings_payload(
|
||||
},
|
||||
"unified_session": defaults.unified_session,
|
||||
},
|
||||
"usage": token_usage_payload(timezone_name=defaults.timezone),
|
||||
"advanced": {
|
||||
"restrict_to_workspace": config.tools.restrict_to_workspace,
|
||||
"workspace_sandbox": sandbox_status.as_dict(),
|
||||
@@ -771,6 +773,12 @@ def settings_payload(
|
||||
)
|
||||
|
||||
|
||||
def settings_usage_payload() -> dict[str, Any]:
|
||||
"""Return the lightweight token usage slice for Overview refreshes."""
|
||||
config = load_config()
|
||||
return token_usage_payload(timezone_name=config.agents.defaults.timezone)
|
||||
|
||||
|
||||
def update_agent_settings(query: QueryParams) -> dict[str, Any]:
|
||||
config = load_config()
|
||||
defaults = config.agents.defaults
|
||||
|
||||
@@ -27,6 +27,7 @@ from nanobot.webui.settings_api import (
|
||||
logout_oauth_provider,
|
||||
provider_models_payload,
|
||||
settings_payload,
|
||||
settings_usage_payload,
|
||||
update_agent_settings,
|
||||
update_image_generation_settings,
|
||||
update_model_configuration,
|
||||
@@ -79,6 +80,8 @@ class WebUISettingsRouter:
|
||||
async def dispatch(self, request: WsRequest, path: str) -> Response | None:
|
||||
if path == "/api/settings":
|
||||
return self._handle_settings(request)
|
||||
if path == "/api/settings/usage":
|
||||
return self._handle_settings_usage(request)
|
||||
if path == "/api/settings/update":
|
||||
return self._handle_settings_update(request)
|
||||
if path == "/api/settings/model-configurations/create":
|
||||
@@ -184,6 +187,11 @@ class WebUISettingsRouter:
|
||||
)
|
||||
)
|
||||
|
||||
def _handle_settings_usage(self, request: WsRequest) -> Response:
|
||||
if not self._authorized(request):
|
||||
return self._unauthorized()
|
||||
return self._json_response(settings_usage_payload())
|
||||
|
||||
def _handle_settings_update(self, request: WsRequest) -> Response:
|
||||
if not self._authorized(request):
|
||||
return self._unauthorized()
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Lightweight skill summaries for the WebUI."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from nanobot.agent.skills import SkillsLoader
|
||||
|
||||
|
||||
def webui_skills_payload(
|
||||
workspace_path: Path,
|
||||
*,
|
||||
disabled_skills: set[str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Return agent skills without leaking local filesystem paths."""
|
||||
loader = SkillsLoader(workspace_path, disabled_skills=disabled_skills)
|
||||
entries = sorted(
|
||||
loader.list_skills(filter_unavailable=False),
|
||||
key=lambda entry: (entry.get("source") != "workspace", entry["name"]),
|
||||
)
|
||||
return {"skills": [_skill_payload(loader, entry) for entry in entries]}
|
||||
|
||||
|
||||
def webui_skill_detail_payload(
|
||||
workspace_path: Path,
|
||||
name: str,
|
||||
*,
|
||||
disabled_skills: set[str] | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Return a single skill's safe detail payload."""
|
||||
loader = SkillsLoader(workspace_path, disabled_skills=disabled_skills)
|
||||
entries = loader.list_skills(filter_unavailable=False)
|
||||
entry = next((item for item in entries if item["name"] == name), None)
|
||||
if entry is None:
|
||||
return None
|
||||
return {
|
||||
**_skill_payload(loader, entry),
|
||||
"requirements": loader.get_skill_requirements(name),
|
||||
"raw_markdown": loader.load_skill(name) or "",
|
||||
}
|
||||
|
||||
|
||||
def _skill_payload(loader: SkillsLoader, entry: dict[str, str]) -> dict[str, Any]:
|
||||
name = entry["name"]
|
||||
metadata = loader.get_skill_metadata(name)
|
||||
available, unavailable_reason = loader.get_skill_availability(name)
|
||||
return {
|
||||
"name": name,
|
||||
"description": _description(metadata, name),
|
||||
"source": entry.get("source", "unknown"),
|
||||
"available": available,
|
||||
"unavailable_reason": unavailable_reason,
|
||||
}
|
||||
|
||||
|
||||
def _description(metadata: dict[str, Any] | None, fallback: str) -> str:
|
||||
if metadata is None:
|
||||
return fallback
|
||||
value = metadata.get("description")
|
||||
return value.strip() if isinstance(value, str) and value.strip() else fallback
|
||||
@@ -0,0 +1,357 @@
|
||||
"""Workspace-scoped token usage telemetry for WebUI overview surfaces."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.agent.hook import AgentHook, AgentHookContext
|
||||
from nanobot.config.paths import get_webui_dir
|
||||
|
||||
TOKEN_USAGE_SCHEMA_VERSION = 1
|
||||
_MAX_STATE_FILE_BYTES = 512 * 1024
|
||||
_MAX_DAYS_RETAINED = 400
|
||||
_USAGE_KEYS = (
|
||||
"prompt_tokens",
|
||||
"completion_tokens",
|
||||
"cached_tokens",
|
||||
"total_tokens",
|
||||
"provider_tokens",
|
||||
"estimated_tokens",
|
||||
)
|
||||
_REQUEST_KEYS = ("requests", "provider_requests", "estimated_requests")
|
||||
_SOURCE_KEYS = ("user", "api", "cron", "dream", "system")
|
||||
_WRITE_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def token_usage_state_path() -> Path:
|
||||
return get_webui_dir() / "token-usage.json"
|
||||
|
||||
|
||||
def default_token_usage_state() -> dict[str, Any]:
|
||||
return {
|
||||
"schema_version": TOKEN_USAGE_SCHEMA_VERSION,
|
||||
"days": {},
|
||||
"updated_at": None,
|
||||
}
|
||||
|
||||
|
||||
def _utc_now_iso() -> str:
|
||||
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||||
|
||||
|
||||
def _zone(timezone_name: str | None) -> timezone | ZoneInfo:
|
||||
if not timezone_name:
|
||||
return timezone.utc
|
||||
try:
|
||||
return ZoneInfo(timezone_name)
|
||||
except ZoneInfoNotFoundError:
|
||||
return timezone.utc
|
||||
|
||||
|
||||
def _local_day(now: datetime | None = None, *, timezone_name: str | None = None) -> str:
|
||||
dt = now or datetime.now(timezone.utc)
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=timezone.utc)
|
||||
return dt.astimezone(_zone(timezone_name)).date().isoformat()
|
||||
|
||||
|
||||
def _clean_int(value: Any) -> int:
|
||||
try:
|
||||
return max(0, int(value or 0))
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
def _clean_source(value: str | None) -> str:
|
||||
return value if value in _SOURCE_KEYS else "system"
|
||||
|
||||
|
||||
def _source_from_session_key(session_key: str | None) -> str:
|
||||
key = session_key or ""
|
||||
if key.startswith("dream:"):
|
||||
return "dream"
|
||||
if key == "heartbeat" or key.startswith("cron:"):
|
||||
return "cron"
|
||||
if key.startswith("api:"):
|
||||
return "api"
|
||||
if key.startswith("system:"):
|
||||
return "system"
|
||||
return "user"
|
||||
|
||||
|
||||
def _normalize_usage(raw: dict[str, Any] | None) -> dict[str, int]:
|
||||
if not isinstance(raw, dict):
|
||||
return {}
|
||||
usage = {key: _clean_int(raw.get(key)) for key in _USAGE_KEYS}
|
||||
fallback_total = usage["prompt_tokens"] + usage["completion_tokens"]
|
||||
if usage["total_tokens"] <= 0:
|
||||
usage["total_tokens"] = fallback_total
|
||||
if usage["estimated_tokens"] <= 0 and usage["provider_tokens"] <= 0:
|
||||
usage["provider_tokens"] = usage["total_tokens"]
|
||||
elif usage["estimated_tokens"] > 0 and usage["provider_tokens"] <= 0:
|
||||
usage["estimated_tokens"] = min(usage["estimated_tokens"], usage["total_tokens"])
|
||||
elif usage["provider_tokens"] > 0 and usage["estimated_tokens"] <= 0:
|
||||
usage["provider_tokens"] = min(usage["provider_tokens"], usage["total_tokens"])
|
||||
return usage if usage["total_tokens"] > 0 else {}
|
||||
|
||||
|
||||
def _normalize_usage_row(row: dict[str, Any]) -> dict[str, int]:
|
||||
cleaned = {key: _clean_int(row.get(key)) for key in _USAGE_KEYS}
|
||||
if cleaned["total_tokens"] <= 0:
|
||||
cleaned["total_tokens"] = cleaned["prompt_tokens"] + cleaned["completion_tokens"]
|
||||
if cleaned["provider_tokens"] <= 0 and cleaned["estimated_tokens"] <= 0:
|
||||
cleaned["provider_tokens"] = cleaned["total_tokens"]
|
||||
requests = {key: _clean_int(row.get(key)) for key in _REQUEST_KEYS}
|
||||
if (
|
||||
requests["requests"] > 0
|
||||
and requests["provider_requests"] <= 0
|
||||
and requests["estimated_requests"] <= 0
|
||||
):
|
||||
if cleaned["estimated_tokens"] > 0 and cleaned["provider_tokens"] <= 0:
|
||||
requests["estimated_requests"] = requests["requests"]
|
||||
else:
|
||||
requests["provider_requests"] = requests["requests"]
|
||||
return {**cleaned, **requests}
|
||||
|
||||
|
||||
def _normalize_sources(raw: Any, fallback: dict[str, int]) -> dict[str, dict[str, int]]:
|
||||
sources: dict[str, dict[str, int]] = {}
|
||||
if isinstance(raw, dict):
|
||||
for source, row in raw.items():
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
normalized = _normalize_usage_row(row)
|
||||
if normalized["total_tokens"] <= 0 and normalized["requests"] <= 0:
|
||||
continue
|
||||
source_key = _clean_source(str(source))
|
||||
current = sources.get(source_key)
|
||||
if current is None:
|
||||
sources[source_key] = normalized
|
||||
else:
|
||||
for key in (*_USAGE_KEYS, *_REQUEST_KEYS):
|
||||
current[key] = _clean_int(current.get(key)) + normalized[key]
|
||||
if not sources and (fallback["total_tokens"] > 0 or fallback["requests"] > 0):
|
||||
sources["user"] = {key: fallback[key] for key in (*_USAGE_KEYS, *_REQUEST_KEYS)}
|
||||
return sources
|
||||
|
||||
|
||||
def normalize_token_usage_state(raw: Any) -> dict[str, Any]:
|
||||
state = default_token_usage_state()
|
||||
if not isinstance(raw, dict):
|
||||
return state
|
||||
days_raw = raw.get("days")
|
||||
if not isinstance(days_raw, dict):
|
||||
return state
|
||||
|
||||
days: dict[str, dict[str, Any]] = {}
|
||||
for date, row in sorted(days_raw.items())[-_MAX_DAYS_RETAINED:]:
|
||||
if not isinstance(date, str) or len(date) != 10 or not isinstance(row, dict):
|
||||
continue
|
||||
normalized = _normalize_usage_row(row)
|
||||
if normalized["total_tokens"] <= 0 and normalized["requests"] <= 0:
|
||||
continue
|
||||
days[date] = {
|
||||
"date": date,
|
||||
**normalized,
|
||||
"sources": _normalize_sources(row.get("sources"), normalized),
|
||||
}
|
||||
|
||||
state["days"] = days
|
||||
updated_at = raw.get("updated_at")
|
||||
state["updated_at"] = updated_at if isinstance(updated_at, str) else None
|
||||
return state
|
||||
|
||||
|
||||
def read_token_usage_state() -> dict[str, Any]:
|
||||
path = token_usage_state_path()
|
||||
if not path.is_file():
|
||||
return default_token_usage_state()
|
||||
try:
|
||||
if path.stat().st_size > _MAX_STATE_FILE_BYTES:
|
||||
logger.warning("token usage state too large, ignoring: {}", path)
|
||||
return default_token_usage_state()
|
||||
with open(path, encoding="utf-8") as f:
|
||||
raw = json.load(f)
|
||||
except (OSError, json.JSONDecodeError) as e:
|
||||
logger.warning("read token usage state failed {}: {}", path, e)
|
||||
return default_token_usage_state()
|
||||
return normalize_token_usage_state(raw)
|
||||
|
||||
|
||||
def write_token_usage_state(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
state = normalize_token_usage_state(raw)
|
||||
state["updated_at"] = _utc_now_iso()
|
||||
encoded = json.dumps(
|
||||
state,
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
sort_keys=True,
|
||||
).encode("utf-8")
|
||||
if len(encoded) > _MAX_STATE_FILE_BYTES:
|
||||
raise ValueError("token usage state is too large")
|
||||
|
||||
path = token_usage_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
|
||||
|
||||
|
||||
def record_token_usage(
|
||||
usage: dict[str, Any] | None,
|
||||
*,
|
||||
source: str = "user",
|
||||
timezone_name: str | None = None,
|
||||
now: datetime | None = None,
|
||||
) -> dict[str, Any]:
|
||||
normalized = _normalize_usage(usage)
|
||||
if not normalized:
|
||||
return read_token_usage_state()
|
||||
|
||||
with _WRITE_LOCK:
|
||||
state = read_token_usage_state()
|
||||
day = _local_day(now, timezone_name=timezone_name)
|
||||
row = dict(state["days"].get(day) or {"date": day, "requests": 0})
|
||||
for key in _USAGE_KEYS:
|
||||
row[key] = _clean_int(row.get(key)) + normalized.get(key, 0)
|
||||
row["requests"] = _clean_int(row.get("requests")) + 1
|
||||
if normalized.get("estimated_tokens", 0) > 0 and normalized.get("provider_tokens", 0) <= 0:
|
||||
row["estimated_requests"] = _clean_int(row.get("estimated_requests")) + 1
|
||||
else:
|
||||
row["provider_requests"] = _clean_int(row.get("provider_requests")) + 1
|
||||
|
||||
source_key = _clean_source(source)
|
||||
sources = dict(row.get("sources") or {})
|
||||
source_row = dict(sources.get(source_key) or {"requests": 0})
|
||||
for key in _USAGE_KEYS:
|
||||
source_row[key] = _clean_int(source_row.get(key)) + normalized.get(key, 0)
|
||||
source_row["requests"] = _clean_int(source_row.get("requests")) + 1
|
||||
if normalized.get("estimated_tokens", 0) > 0 and normalized.get("provider_tokens", 0) <= 0:
|
||||
source_row["estimated_requests"] = _clean_int(source_row.get("estimated_requests")) + 1
|
||||
else:
|
||||
source_row["provider_requests"] = _clean_int(source_row.get("provider_requests")) + 1
|
||||
sources[source_key] = source_row
|
||||
row["sources"] = sources
|
||||
|
||||
state["days"][day] = row
|
||||
if len(state["days"]) > _MAX_DAYS_RETAINED:
|
||||
kept = dict(sorted(state["days"].items())[-_MAX_DAYS_RETAINED:])
|
||||
state["days"] = kept
|
||||
return write_token_usage_state(state)
|
||||
|
||||
|
||||
def record_response_token_usage(
|
||||
response: Any,
|
||||
*,
|
||||
source: str,
|
||||
timezone_name: str | None = None,
|
||||
) -> None:
|
||||
try:
|
||||
record_token_usage(
|
||||
getattr(response, "usage", None),
|
||||
source=source,
|
||||
timezone_name=timezone_name,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("failed to record {} token usage", source)
|
||||
|
||||
|
||||
def token_usage_payload(
|
||||
*,
|
||||
days: int = 371,
|
||||
timezone_name: str | None = None,
|
||||
now: datetime | None = None,
|
||||
) -> dict[str, Any]:
|
||||
state = read_token_usage_state()
|
||||
today = datetime.fromisoformat(_local_day(now, timezone_name=timezone_name)).date()
|
||||
start = today - timedelta(days=max(1, days) - 1)
|
||||
day_rows = [
|
||||
row
|
||||
for date, row in sorted(state["days"].items())
|
||||
if start.isoformat() <= date <= today.isoformat()
|
||||
]
|
||||
last_30_start = today - timedelta(days=29)
|
||||
last_30 = [
|
||||
row
|
||||
for date, row in state["days"].items()
|
||||
if last_30_start.isoformat() <= date <= today.isoformat()
|
||||
]
|
||||
last_365_start = today - timedelta(days=364)
|
||||
last_365 = [
|
||||
row
|
||||
for date, row in state["days"].items()
|
||||
if last_365_start.isoformat() <= date <= today.isoformat()
|
||||
]
|
||||
active_dates = {
|
||||
datetime.fromisoformat(date).date()
|
||||
for date, row in state["days"].items()
|
||||
if _clean_int(row.get("total_tokens")) > 0
|
||||
}
|
||||
current_streak = 0
|
||||
cursor = today
|
||||
while cursor in active_dates:
|
||||
current_streak += 1
|
||||
cursor -= timedelta(days=1)
|
||||
|
||||
longest_streak = 0
|
||||
running_streak = 0
|
||||
for cursor in sorted(active_dates):
|
||||
if cursor - timedelta(days=1) in active_dates:
|
||||
running_streak += 1
|
||||
else:
|
||||
running_streak = 1
|
||||
longest_streak = max(longest_streak, running_streak)
|
||||
|
||||
all_rows = list(state["days"].values())
|
||||
return {
|
||||
"days": day_rows,
|
||||
"total_tokens": sum(_clean_int(row.get("total_tokens")) for row in all_rows),
|
||||
"total_tokens_30d": sum(_clean_int(row.get("total_tokens")) for row in last_30),
|
||||
"total_tokens_365d": sum(_clean_int(row.get("total_tokens")) for row in last_365),
|
||||
"peak_day_tokens": max([_clean_int(row.get("total_tokens")) for row in all_rows] or [0]),
|
||||
"current_streak_days": current_streak,
|
||||
"longest_streak_days": longest_streak,
|
||||
"active_days_30d": sum(1 for row in last_30 if _clean_int(row.get("total_tokens")) > 0),
|
||||
"requests_30d": sum(_clean_int(row.get("requests")) for row in last_30),
|
||||
"updated_at": state.get("updated_at"),
|
||||
}
|
||||
|
||||
|
||||
class TokenUsageHook(AgentHook):
|
||||
"""Persist provider-reported token usage without coupling it to chat messages."""
|
||||
|
||||
def __init__(self, *, timezone_name: str | None = None) -> None:
|
||||
super().__init__()
|
||||
self._timezone_name = timezone_name
|
||||
|
||||
async def after_iteration(self, context: AgentHookContext) -> None:
|
||||
try:
|
||||
record_token_usage(
|
||||
context.usage,
|
||||
source=_source_from_session_key(context.session_key),
|
||||
timezone_name=self._timezone_name,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("failed to record token usage")
|
||||
+222
-10
@@ -18,6 +18,9 @@ from nanobot.session.manager import SessionManager
|
||||
|
||||
WEBUI_TRANSCRIPT_SCHEMA_VERSION = 3
|
||||
_MAX_TRANSCRIPT_FILE_BYTES = 8 * 1024 * 1024
|
||||
_WEBUI_TURN_ID_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
||||
WEBUI_TURN_METADATA_KEY = "webui_turn_id"
|
||||
WEBUI_MESSAGE_SOURCE_METADATA_KEY = "_webui_message_source"
|
||||
_MARKDOWN_LOCAL_IMAGE_RE = re.compile(
|
||||
r"!\[([^\]]*)\]\((<[^>]+>|[^)\s]+)(\s+(?:\"[^\"]*\"|'[^']*'))?\)"
|
||||
)
|
||||
@@ -152,6 +155,125 @@ def append_transcript_object(session_key: str, obj: dict[str, Any]) -> None:
|
||||
os.fsync(f.fileno())
|
||||
|
||||
|
||||
def normalize_webui_turn_id(value: Any) -> str:
|
||||
if isinstance(value, str):
|
||||
candidate = value.strip()
|
||||
if _WEBUI_TURN_ID_RE.fullmatch(candidate):
|
||||
return candidate
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
def webui_message_source(metadata: dict[str, Any] | None) -> dict[str, str] | None:
|
||||
raw = (metadata or {}).get(WEBUI_MESSAGE_SOURCE_METADATA_KEY)
|
||||
if not isinstance(raw, dict) or raw.get("kind") != "cron":
|
||||
return None
|
||||
source: dict[str, str] = {"kind": "cron"}
|
||||
label = raw.get("label")
|
||||
if isinstance(label, str) and label.strip():
|
||||
source["label"] = label.strip()
|
||||
return source
|
||||
|
||||
|
||||
class WebUITranscriptRecorder:
|
||||
"""Prepare and persist WebUI wire events without leaking UI rules into channels."""
|
||||
|
||||
def __init__(self, log: Any = logger) -> None:
|
||||
self._log = log
|
||||
self._turn_sequences: dict[tuple[str, str], int] = {}
|
||||
|
||||
def client_turn_metadata(self, value: Any) -> dict[str, str]:
|
||||
return {WEBUI_TURN_METADATA_KEY: normalize_webui_turn_id(value)}
|
||||
|
||||
def prepare_event(
|
||||
self,
|
||||
chat_id: str,
|
||||
event: dict[str, Any],
|
||||
*,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
phase: str | None = None,
|
||||
include_source: bool = False,
|
||||
) -> None:
|
||||
if include_source and (source := webui_message_source(metadata)):
|
||||
event["source"] = source
|
||||
self._annotate_turn(chat_id, event, metadata, phase)
|
||||
|
||||
def prepare_and_append(
|
||||
self,
|
||||
chat_id: str,
|
||||
event: dict[str, Any],
|
||||
*,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
phase: str | None = None,
|
||||
include_source: bool = False,
|
||||
transcript_overrides: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
self.prepare_event(
|
||||
chat_id,
|
||||
event,
|
||||
metadata=metadata,
|
||||
phase=phase,
|
||||
include_source=include_source,
|
||||
)
|
||||
record = dict(event)
|
||||
if transcript_overrides:
|
||||
record.update(transcript_overrides)
|
||||
self.append(chat_id, record)
|
||||
|
||||
def append_user_message(
|
||||
self,
|
||||
chat_id: str,
|
||||
text: str,
|
||||
*,
|
||||
metadata: dict[str, Any],
|
||||
media_paths: list[str] | None = None,
|
||||
cli_apps: list[dict[str, Any]] | None = None,
|
||||
mcp_presets: list[dict[str, Any]] | None = None,
|
||||
) -> None:
|
||||
if text.strip() == "/stop" and not media_paths:
|
||||
return
|
||||
payload = build_user_transcript_event(
|
||||
chat_id,
|
||||
text,
|
||||
media_paths=media_paths,
|
||||
cli_apps=cli_apps,
|
||||
mcp_presets=mcp_presets,
|
||||
)
|
||||
if payload is None:
|
||||
return
|
||||
self.prepare_and_append(chat_id, payload, metadata=metadata, phase="user")
|
||||
|
||||
def append(self, chat_id: str, event: dict[str, Any]) -> None:
|
||||
try:
|
||||
dup = json.loads(json.dumps(event, ensure_ascii=False))
|
||||
append_transcript_object(f"websocket:{chat_id}", dup)
|
||||
except (OSError, ValueError, TypeError) as e:
|
||||
self._log.warning("webui transcript append failed: {}", e)
|
||||
|
||||
def _next_turn_seq(self, chat_id: str, turn_id: str) -> int:
|
||||
key = (chat_id, turn_id)
|
||||
seq = self._turn_sequences.get(key, 0) + 1
|
||||
self._turn_sequences[key] = seq
|
||||
return seq
|
||||
|
||||
def _annotate_turn(
|
||||
self,
|
||||
chat_id: str,
|
||||
event: dict[str, Any],
|
||||
metadata: dict[str, Any] | None,
|
||||
phase: str | None,
|
||||
) -> None:
|
||||
if phase is None:
|
||||
return
|
||||
turn_id = (metadata or {}).get(WEBUI_TURN_METADATA_KEY)
|
||||
if not isinstance(turn_id, str) or not turn_id:
|
||||
return
|
||||
event["turn_id"] = turn_id
|
||||
event["turn_phase"] = phase
|
||||
event["turn_seq"] = self._next_turn_seq(chat_id, turn_id)
|
||||
if phase == "complete":
|
||||
self._turn_sequences.pop((chat_id, turn_id), None)
|
||||
|
||||
|
||||
def delete_webui_transcript(session_key: str) -> bool:
|
||||
path = webui_transcript_path(session_key)
|
||||
if not path.is_file():
|
||||
@@ -560,6 +682,8 @@ def replay_transcript_to_ui_messages(
|
||||
active_file_edit_segment_id: str | None = None
|
||||
activity_segment_counter = 0
|
||||
_ts_base = int(time.time() * 1000)
|
||||
closed_turn_ids: set[str] = set()
|
||||
replay_turn_aliases: dict[str, str] = {}
|
||||
|
||||
def _new_id(prefix: str, idx: int) -> str:
|
||||
return f"{prefix}-{idx}-{uuid.uuid4().hex[:8]}"
|
||||
@@ -572,6 +696,42 @@ def replay_transcript_to_ui_messages(
|
||||
active_activity_segment_id = segment_id
|
||||
return segment_id
|
||||
|
||||
def _turn_fields(rec: dict[str, Any], fallback_phase: str | None = None) -> dict[str, Any]:
|
||||
fields: dict[str, Any] = {}
|
||||
turn_id = rec.get("turn_id")
|
||||
if isinstance(turn_id, str) and turn_id:
|
||||
if turn_id in closed_turn_ids:
|
||||
fields["turnId"] = replay_turn_aliases.setdefault(
|
||||
turn_id,
|
||||
f"{turn_id}:replay:{idx}",
|
||||
)
|
||||
else:
|
||||
fields["turnId"] = turn_id
|
||||
phase = rec.get("turn_phase")
|
||||
if isinstance(phase, str) and phase:
|
||||
fields["turnPhase"] = phase
|
||||
elif fallback_phase:
|
||||
fields["turnPhase"] = fallback_phase
|
||||
seq = rec.get("turn_seq")
|
||||
if isinstance(seq, (int, float)):
|
||||
fields["turnSeq"] = int(seq)
|
||||
return fields
|
||||
|
||||
def _source_fields(rec: dict[str, Any]) -> dict[str, Any]:
|
||||
source = rec.get("source")
|
||||
if not isinstance(source, dict) or source.get("kind") != "cron":
|
||||
return {}
|
||||
out: dict[str, Any] = {"source": {"kind": "cron"}}
|
||||
label = source.get("label")
|
||||
if isinstance(label, str) and label.strip():
|
||||
out["source"]["label"] = label.strip()
|
||||
return out
|
||||
|
||||
def _same_turn(message: dict[str, Any], turn_fields: dict[str, Any]) -> bool:
|
||||
turn_id = turn_fields.get("turnId")
|
||||
message_turn_id = message.get("turnId")
|
||||
return not turn_id or not message_turn_id or turn_id == message_turn_id
|
||||
|
||||
def _ensure_activity_segment() -> str:
|
||||
return active_activity_segment_id or _new_activity_segment()
|
||||
|
||||
@@ -586,7 +746,13 @@ def replay_transcript_to_ui_messages(
|
||||
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:
|
||||
def attach_reasoning_chunk(
|
||||
prev: list[dict[str, Any]],
|
||||
chunk: str,
|
||||
idx: int,
|
||||
turn_fields: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
turn_fields = turn_fields or {}
|
||||
for i in range(len(prev) - 1, -1, -1):
|
||||
candidate = prev[i]
|
||||
if candidate.get("role") == "user":
|
||||
@@ -595,6 +761,8 @@ def replay_transcript_to_ui_messages(
|
||||
break
|
||||
if candidate.get("role") != "assistant":
|
||||
continue
|
||||
if not _same_turn(candidate, turn_fields):
|
||||
break
|
||||
content = str(candidate.get("content") or "")
|
||||
has_answer = len(content) > 0
|
||||
if (
|
||||
@@ -608,6 +776,7 @@ def replay_transcript_to_ui_messages(
|
||||
"reasoning": (str(candidate.get("reasoning") or "")) + chunk,
|
||||
"reasoningStreaming": True,
|
||||
"activitySegmentId": candidate.get("activitySegmentId") or _ensure_activity_segment(),
|
||||
**turn_fields,
|
||||
}
|
||||
return
|
||||
if not has_answer and candidate.get("isStreaming"):
|
||||
@@ -616,6 +785,7 @@ def replay_transcript_to_ui_messages(
|
||||
"reasoning": chunk,
|
||||
"reasoningStreaming": True,
|
||||
"activitySegmentId": candidate.get("activitySegmentId") or _ensure_activity_segment(),
|
||||
**turn_fields,
|
||||
}
|
||||
return
|
||||
break
|
||||
@@ -629,11 +799,16 @@ def replay_transcript_to_ui_messages(
|
||||
"reasoning": chunk,
|
||||
"reasoningStreaming": True,
|
||||
"activitySegmentId": segment,
|
||||
**turn_fields,
|
||||
"createdAt": _ts_base + idx,
|
||||
},
|
||||
)
|
||||
|
||||
def find_active_placeholder(prev: list[dict[str, Any]]) -> str | None:
|
||||
def find_active_placeholder(
|
||||
prev: list[dict[str, Any]],
|
||||
turn_fields: dict[str, Any] | None = None,
|
||||
) -> str | None:
|
||||
turn_fields = turn_fields or {}
|
||||
last = prev[-1] if prev else None
|
||||
if not last:
|
||||
return None
|
||||
@@ -643,6 +818,8 @@ def replay_transcript_to_ui_messages(
|
||||
return None
|
||||
if not last.get("isStreaming"):
|
||||
return None
|
||||
if not _same_turn(last, turn_fields):
|
||||
return None
|
||||
return str(last.get("id"))
|
||||
|
||||
def demote_interrupted_assistant(segment: str) -> None:
|
||||
@@ -721,7 +898,7 @@ def replay_transcript_to_ui_messages(
|
||||
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):
|
||||
if last and is_reasoning_only_placeholder(last) and _same_turn(last, extra):
|
||||
messages[-1] = {
|
||||
**last,
|
||||
**extra,
|
||||
@@ -768,8 +945,13 @@ def replay_transcript_to_ui_messages(
|
||||
return i
|
||||
return None
|
||||
|
||||
def upsert_file_edits(edits: list[dict[str, Any]], idx: int) -> None:
|
||||
def upsert_file_edits(
|
||||
edits: list[dict[str, Any]],
|
||||
idx: int,
|
||||
turn_fields: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
nonlocal active_file_edit_segment_id
|
||||
turn_fields = turn_fields or {}
|
||||
if not edits:
|
||||
return
|
||||
segment = active_file_edit_segment_id
|
||||
@@ -796,6 +978,7 @@ def replay_transcript_to_ui_messages(
|
||||
"traces": [],
|
||||
"fileEdits": [],
|
||||
"activitySegmentId": segment,
|
||||
**turn_fields,
|
||||
"createdAt": _ts_base + idx,
|
||||
},
|
||||
)
|
||||
@@ -827,6 +1010,7 @@ def replay_transcript_to_ui_messages(
|
||||
**last,
|
||||
"fileEdits": existing,
|
||||
"activitySegmentId": last.get("activitySegmentId") or segment,
|
||||
**turn_fields,
|
||||
}
|
||||
|
||||
for idx, rec in enumerate(lines):
|
||||
@@ -847,6 +1031,7 @@ def replay_transcript_to_ui_messages(
|
||||
"id": _new_id("u", idx),
|
||||
"role": "user",
|
||||
"content": text_s,
|
||||
**_turn_fields(rec, "user"),
|
||||
"createdAt": _ts_base + idx,
|
||||
}
|
||||
if media_att:
|
||||
@@ -867,7 +1052,11 @@ def replay_transcript_to_ui_messages(
|
||||
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)
|
||||
upsert_file_edits(
|
||||
[e for e in raw_edits if isinstance(e, dict)],
|
||||
idx,
|
||||
_turn_fields(rec, "activity"),
|
||||
)
|
||||
continue
|
||||
|
||||
if ev == "delta":
|
||||
@@ -877,7 +1066,8 @@ def replay_transcript_to_ui_messages(
|
||||
if not isinstance(chunk, str):
|
||||
continue
|
||||
close_activity_for_answer()
|
||||
adopted = find_active_placeholder(messages) if buffer_message_id is None else None
|
||||
turn_fields = _turn_fields(rec, "answer")
|
||||
adopted = find_active_placeholder(messages, turn_fields) if buffer_message_id is None else None
|
||||
if buffer_message_id is None:
|
||||
if adopted:
|
||||
buffer_message_id = adopted
|
||||
@@ -889,6 +1079,7 @@ def replay_transcript_to_ui_messages(
|
||||
"role": "assistant",
|
||||
"content": "",
|
||||
"isStreaming": True,
|
||||
**_turn_fields(rec, "answer"),
|
||||
"createdAt": _ts_base + idx,
|
||||
},
|
||||
)
|
||||
@@ -896,7 +1087,12 @@ def replay_transcript_to_ui_messages(
|
||||
combined = "".join(buffer_parts)
|
||||
for i, m in enumerate(messages):
|
||||
if m.get("id") == buffer_message_id:
|
||||
messages[i] = {**m, "content": combined, "isStreaming": True}
|
||||
messages[i] = {
|
||||
**m,
|
||||
"content": combined,
|
||||
"isStreaming": True,
|
||||
**_turn_fields(rec, "answer"),
|
||||
}
|
||||
break
|
||||
continue
|
||||
|
||||
@@ -915,13 +1111,19 @@ def replay_transcript_to_ui_messages(
|
||||
"role": "assistant",
|
||||
"content": final_text,
|
||||
"isStreaming": True,
|
||||
**_turn_fields(rec, "answer"),
|
||||
"createdAt": _ts_base + idx,
|
||||
},
|
||||
)
|
||||
else:
|
||||
for i, m in enumerate(messages):
|
||||
if m.get("id") == buffer_message_id:
|
||||
messages[i] = {**m, "content": final_text, "isStreaming": True}
|
||||
messages[i] = {
|
||||
**m,
|
||||
"content": final_text,
|
||||
"isStreaming": True,
|
||||
**_turn_fields(rec, "answer"),
|
||||
}
|
||||
break
|
||||
buffer_message_id = None
|
||||
buffer_parts = []
|
||||
@@ -934,7 +1136,7 @@ def replay_transcript_to_ui_messages(
|
||||
if not isinstance(chunk, str) or not chunk:
|
||||
continue
|
||||
close_file_edit_phase_before_activity()
|
||||
attach_reasoning_chunk(messages, chunk, idx)
|
||||
attach_reasoning_chunk(messages, chunk, idx, _turn_fields(rec, "reasoning"))
|
||||
continue
|
||||
|
||||
if ev == "reasoning_end":
|
||||
@@ -956,7 +1158,7 @@ def replay_transcript_to_ui_messages(
|
||||
if not isinstance(line, str) or not line:
|
||||
continue
|
||||
close_file_edit_phase_before_activity()
|
||||
attach_reasoning_chunk(messages, line, idx)
|
||||
attach_reasoning_chunk(messages, line, idx, _turn_fields(rec, "reasoning"))
|
||||
close_reasoning(messages)
|
||||
continue
|
||||
if kind in ("tool_hint", "progress"):
|
||||
@@ -998,6 +1200,7 @@ def replay_transcript_to_ui_messages(
|
||||
if visible_structured_events
|
||||
else last.get("toolEvents"),
|
||||
"activitySegmentId": last.get("activitySegmentId") or segment,
|
||||
**_turn_fields(rec, "activity"),
|
||||
}
|
||||
messages[-1] = merged
|
||||
else:
|
||||
@@ -1010,6 +1213,7 @@ def replay_transcript_to_ui_messages(
|
||||
"traces": trace_lines,
|
||||
**({"toolEvents": visible_structured_events} if visible_structured_events else {}),
|
||||
"activitySegmentId": segment,
|
||||
**_turn_fields(rec, "activity"),
|
||||
"createdAt": _ts_base + idx,
|
||||
},
|
||||
)
|
||||
@@ -1033,6 +1237,8 @@ def replay_transcript_to_ui_messages(
|
||||
lat = rec.get("latency_ms")
|
||||
if isinstance(lat, (int, float)) and lat >= 0:
|
||||
extra["latencyMs"] = int(lat)
|
||||
extra.update(_turn_fields(rec, "answer"))
|
||||
extra.update(_source_fields(rec))
|
||||
absorb_complete(extra, idx)
|
||||
if media:
|
||||
suppress_until_turn_end = True
|
||||
@@ -1042,6 +1248,12 @@ def replay_transcript_to_ui_messages(
|
||||
suppress_until_turn_end = False
|
||||
active_activity_segment_id = None
|
||||
active_file_edit_segment_id = None
|
||||
turn_id = rec.get("turn_id")
|
||||
if isinstance(turn_id, str) and turn_id:
|
||||
if turn_id in replay_turn_aliases:
|
||||
replay_turn_aliases.pop(turn_id, None)
|
||||
else:
|
||||
closed_turn_ids.add(turn_id)
|
||||
for i, m in enumerate(messages):
|
||||
if m.get("isStreaming"):
|
||||
messages[i] = {**m, "isStreaming": False}
|
||||
|
||||
@@ -22,6 +22,7 @@ from websockets.http11 import Response
|
||||
|
||||
from nanobot.command.builtin import builtin_command_palette
|
||||
from nanobot.utils.subagent_channel_display import scrub_subagent_messages_for_channel
|
||||
from nanobot.webui.file_preview import WebUIFilePreviewError, file_preview_payload
|
||||
from nanobot.webui.gateway_tokens import GatewayTokenStore, token_response_payload
|
||||
from nanobot.webui.http_utils import (
|
||||
case_insensitive_header as _case_insensitive_header,
|
||||
@@ -60,16 +61,19 @@ from nanobot.webui.http_utils import (
|
||||
safe_host_header as _safe_host_header,
|
||||
)
|
||||
from nanobot.webui.media_gateway import WebUIMediaGateway
|
||||
from nanobot.webui.session_automations import session_automations_payload
|
||||
from nanobot.webui.sidebar_state import (
|
||||
read_webui_sidebar_state,
|
||||
write_webui_sidebar_state,
|
||||
)
|
||||
from nanobot.webui.skills_api import webui_skill_detail_payload, webui_skills_payload
|
||||
from nanobot.webui.thread_disk import delete_webui_thread
|
||||
from nanobot.webui.transcript import build_webui_thread_response
|
||||
from nanobot.webui.workspaces import WebUIWorkspaceController
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from nanobot.cron.service import CronService
|
||||
from nanobot.session.manager import SessionManager
|
||||
|
||||
|
||||
@@ -95,7 +99,7 @@ def _default_model_name_from_config() -> str | None:
|
||||
|
||||
def _resolve_bootstrap_model_name(
|
||||
runtime_name: Callable[[], str | None] | None,
|
||||
) -> str | None:
|
||||
) -> str:
|
||||
if runtime_name is not None:
|
||||
try:
|
||||
raw = runtime_name()
|
||||
@@ -106,7 +110,7 @@ def _resolve_bootstrap_model_name(
|
||||
stripped = raw.strip()
|
||||
if stripped:
|
||||
return stripped
|
||||
return _default_model_name_from_config()
|
||||
return _default_model_name_from_config() or ""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -134,6 +138,9 @@ class GatewayHTTPHandler:
|
||||
tokens: GatewayTokenStore,
|
||||
media: WebUIMediaGateway,
|
||||
workspaces: WebUIWorkspaceController,
|
||||
skills_workspace_path: Path,
|
||||
disabled_skills: set[str] | None = None,
|
||||
cron_service: CronService | None = None,
|
||||
log: Any = logger,
|
||||
) -> None:
|
||||
self.config = config
|
||||
@@ -144,6 +151,9 @@ class GatewayHTTPHandler:
|
||||
self.tokens = tokens
|
||||
self.media = media
|
||||
self.workspaces = workspaces
|
||||
self.skills_workspace_path = skills_workspace_path
|
||||
self.disabled_skills = disabled_skills or set()
|
||||
self.cron_service = cron_service
|
||||
self._log = log
|
||||
self._runtime_surface = runtime_surface
|
||||
|
||||
@@ -162,6 +172,9 @@ class GatewayHTTPHandler:
|
||||
runtime_capabilities=self._capabilities,
|
||||
)
|
||||
|
||||
def workspace_controls_available(self, connection: Any) -> bool:
|
||||
return self._runtime_surface == "native" or _is_localhost(connection)
|
||||
|
||||
# -- Token management ---------------------------------------------------
|
||||
|
||||
def check_api_token(self, request: WsRequest) -> bool:
|
||||
@@ -291,6 +304,14 @@ class GatewayHTTPHandler:
|
||||
if m:
|
||||
return self._handle_webui_thread_get(request, m.group(1))
|
||||
|
||||
m = re.match(r"^/api/sessions/([^/]+)/file-preview$", got)
|
||||
if m:
|
||||
return self._handle_file_preview(request, m.group(1))
|
||||
|
||||
m = re.match(r"^/api/sessions/([^/]+)/automations$", got)
|
||||
if m:
|
||||
return self._handle_session_automations(request, m.group(1))
|
||||
|
||||
m = re.match(r"^/api/sessions/([^/]+)/delete$", got)
|
||||
if m:
|
||||
return self._handle_session_delete(request, m.group(1))
|
||||
@@ -369,6 +390,36 @@ class GatewayHTTPHandler:
|
||||
data["workspace_scope"] = scope.payload()
|
||||
return _http_json_response(data)
|
||||
|
||||
def _handle_file_preview(self, request: WsRequest, key: str) -> Response:
|
||||
if not self.check_api_token(request):
|
||||
return _http_error(401, "Unauthorized")
|
||||
decoded_key = _decode_api_key(key)
|
||||
if decoded_key is None:
|
||||
return _http_error(400, "invalid session key")
|
||||
if not _is_websocket_channel_session_key(decoded_key):
|
||||
return _http_error(404, "session not found")
|
||||
path = _query_first(_parse_query(request.path), "path")
|
||||
try:
|
||||
payload = file_preview_payload(
|
||||
path,
|
||||
scope=self.workspaces.scope_for_session_key(decoded_key),
|
||||
)
|
||||
except WebUIFilePreviewError as e:
|
||||
return _http_error(e.status, e.message)
|
||||
return _http_json_response(payload)
|
||||
|
||||
def _handle_session_automations(self, request: WsRequest, key: str) -> Response:
|
||||
if not self.check_api_token(request):
|
||||
return _http_error(401, "Unauthorized")
|
||||
decoded_key = _decode_api_key(key)
|
||||
if decoded_key is None:
|
||||
return _http_error(400, "invalid session key")
|
||||
if not _is_websocket_channel_session_key(decoded_key):
|
||||
return _http_error(404, "session not found")
|
||||
return _http_json_response(
|
||||
session_automations_payload(self.cron_service, decoded_key)
|
||||
)
|
||||
|
||||
def _handle_session_delete(self, request: WsRequest, key: str) -> Response:
|
||||
if not self.check_api_token(request):
|
||||
return _http_error(401, "Unauthorized")
|
||||
@@ -411,6 +462,11 @@ class GatewayHTTPHandler:
|
||||
return self._handle_commands(request)
|
||||
if got == "/api/workspaces":
|
||||
return self._handle_workspaces(connection, request)
|
||||
if got == "/api/webui/skills":
|
||||
return self._handle_webui_skills(request)
|
||||
m = re.match(r"^/api/webui/skills/([^/]+)$", got)
|
||||
if m:
|
||||
return self._handle_webui_skill_detail(request, m.group(1))
|
||||
if got == "/api/webui/sidebar-state":
|
||||
return self._handle_webui_sidebar_state(request)
|
||||
if got == "/api/webui/sidebar-state/update":
|
||||
@@ -426,9 +482,38 @@ class GatewayHTTPHandler:
|
||||
if not self.check_api_token(request):
|
||||
return _http_error(401, "Unauthorized")
|
||||
return _http_json_response(
|
||||
self.workspaces.payload(controls_available=_is_localhost(connection))
|
||||
self.workspaces.payload(
|
||||
controls_available=self.workspace_controls_available(connection)
|
||||
)
|
||||
)
|
||||
|
||||
def _handle_webui_skills(self, request: WsRequest) -> Response:
|
||||
if not self.check_api_token(request):
|
||||
return _http_error(401, "Unauthorized")
|
||||
return _http_json_response(
|
||||
webui_skills_payload(
|
||||
self.skills_workspace_path,
|
||||
disabled_skills=self.disabled_skills,
|
||||
)
|
||||
)
|
||||
|
||||
def _handle_webui_skill_detail(self, request: WsRequest, raw_name: str) -> Response:
|
||||
if not self.check_api_token(request):
|
||||
return _http_error(401, "Unauthorized")
|
||||
from urllib.parse import unquote
|
||||
|
||||
name = unquote(raw_name)
|
||||
if not name or "/" in name or "\\" in name:
|
||||
return _http_error(400, "invalid skill name")
|
||||
payload = webui_skill_detail_payload(
|
||||
self.skills_workspace_path,
|
||||
name,
|
||||
disabled_skills=self.disabled_skills,
|
||||
)
|
||||
if payload is None:
|
||||
return _http_error(404, "skill not found")
|
||||
return _http_json_response(payload)
|
||||
|
||||
def _handle_webui_sidebar_state(self, request: WsRequest) -> Response:
|
||||
if not self.check_api_token(request):
|
||||
return _http_error(401, "Unauthorized")
|
||||
|
||||
Reference in new issue
Block a user