Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(docker)!: drop legacy console (keep BFF + Caddy), ship web-studio in pip, fix favicons (#2160)

Zayn Jarvisd6a024efa5ca
diff --git a/Caddyfile b/Caddyfile
index 4d431e72e..50cbc24e2 100644
--- a/Caddyfile
+++ b/Caddyfile
@@ -1,20 +1,17 @@
# OpenViking aggregated reverse proxy
#
-# Port 1934 merges the API server (1933) and Console (8020) under one origin.
-# This block always serves plain HTTP — suitable for local dev, internal
-# networks, and as an upstream behind your own TLS-terminating proxy.
+# Port 1934 fronts the OV server (1933) under one stable origin. This block
+# always serves plain HTTP — suitable for local dev, internal networks, and
+# as an upstream behind your own TLS-terminating proxy.
+#
+# Web Studio (the in-server SPA) is served by OV itself at `/studio`, so a
+# single upstream is all that's needed here.
#
# To add public HTTPS, append a domain block below (Caddy auto-provisions
# Let's Encrypt certs):
#
# {$OPENVIKING_PUBLIC_BASE_URL} {
-# @console path /console /console/*
-# handle @console {
-# reverse_proxy openviking:8020
-# }
-# handle {
-# reverse_proxy openviking:1933
-# }
+# reverse_proxy openviking:1933
# # Optional: pin ACME email
# # tls {$OV_ACME_EMAIL}
# }
@@ -23,11 +20,5 @@
# OPENVIKING_PUBLIC_BASE_URL=https://your-domain.com in .env.
:1934 {
- @console path /console /console/*
- handle @console {
- reverse_proxy openviking:8020
- }
- handle {
- reverse_proxy openviking:1933
- }
+ reverse_proxy openviking:1933
}
diff --git a/Dockerfile b/Dockerfile
index d8cfeed27..de6eb55c7 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -4,7 +4,26 @@
# ragfs-python's default S3-enabled dependency set currently requires rustc >= 1.91.1.
FROM rust:1.91.1-trixie AS rust-toolchain
-# Stage 2: build Python environment with uv (builds Rust CLI + C++ extension from source)
+# Stage 2: build web-studio static bundle (Vite SPA). Runs before py-builder so
+# the dist can be copied into openviking/web_studio/dist/ and included in the
+# python wheel via package-data — no separate runtime COPY required.
+#
+# WEB_STUDIO_BASE_PATH is passed to `vite build --base=...` and is also
+# consumed at runtime by getRouterBasePath() through import.meta.env.BASE_URL,
+# so the SPA's asset URLs and TanStack Router basepath stay in sync.
+FROM node:20-bookworm-slim AS web-studio-builder
+WORKDIR /web-studio
+ARG TARGETPLATFORM
+ARG WEB_STUDIO_BASE_PATH=/studio/
+
+COPY web-studio/package.json web-studio/package-lock.json ./
+RUN --mount=type=cache,target=/root/.npm,id=npm-${TARGETPLATFORM} \
+ npm ci
+
+COPY web-studio/ ./
+RUN npm run build -- --base="${WEB_STUDIO_BASE_PATH}"
+
+# Stage 3: build Python environment with uv (builds Rust CLI + C++ extension from source)
FROM ghcr.io/astral-sh/uv:python3.13-trixie-slim AS py-builder
# Reuse Rust toolchain from stage 1 so setup.py can compile ov CLI in-place.
@@ -49,6 +68,11 @@ COPY openviking_cli/ openviking_cli/
COPY src/ src/
COPY third_party/ third_party/
+# Bundle the prebuilt web-studio dist into the openviking python package so the
+# wheel produced by `uv sync` ships /studio assets out of the box (parallel to
+# the legacy openviking/console/static layout, just for the new SPA).
+COPY --from=web-studio-builder /web-studio/dist /app/openviking/web_studio/dist
+
# Install project and dependencies (triggers setup.py artifact builds + build_extension).
# Default to auto-refreshing uv.lock inside the ephemeral build context when it is
# stale, so Docker builds stay unblocked after dependency changes. Set
@@ -82,26 +106,6 @@ RUN --mount=type=cache,target=/root/.cache/uv,id=uv-${TARGETPLATFORM} \
;; \
esac
-# Stage 3: build web-studio static bundle (Vite SPA).
-# Produces /web-studio/dist which the runtime stage mounts at /studio in the
-# OpenViking server. Lockfile-first dependency install keeps the layer cached
-# until package.json / lockfile actually change.
-#
-# WEB_STUDIO_BASE_PATH is passed to `vite build --base=...` and is also
-# consumed at runtime by getRouterBasePath() through import.meta.env.BASE_URL,
-# so the SPA's asset URLs and TanStack Router basepath stay in sync.
-FROM node:20-bookworm-slim AS web-studio-builder
-WORKDIR /web-studio
-ARG TARGETPLATFORM
-ARG WEB_STUDIO_BASE_PATH=/studio/
-
-COPY web-studio/package.json web-studio/package-lock.json ./
-RUN --mount=type=cache,target=/root/.npm,id=npm-${TARGETPLATFORM} \
- npm ci
-
-COPY web-studio/ ./
-RUN npm run build -- --base="${WEB_STUDIO_BASE_PATH}"
-
# Stage 4: runtime
FROM python:3.13-slim-trixie
@@ -114,18 +118,16 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
WORKDIR /app
COPY --from=py-builder /app/.venv /app/.venv
-COPY --from=web-studio-builder /web-studio/dist /app/web-studio/dist
-COPY docker/openviking-console-entrypoint.sh /usr/local/bin/openviking-console-entrypoint
+COPY docker/openviking-entrypoint.sh /usr/local/bin/openviking-entrypoint
COPY docker/pending_health_server.py /usr/local/bin/openviking-pending-health
RUN mkdir -p /app/.openviking \
- && chmod +x /usr/local/bin/openviking-console-entrypoint /usr/local/bin/openviking-pending-health
+ && chmod +x /usr/local/bin/openviking-entrypoint /usr/local/bin/openviking-pending-health
ENV HOME="/app" \
PATH="/app/.venv/bin:$PATH" \
OPENVIKING_CONFIG_FILE="/app/.openviking/ov.conf" \
- OPENVIKING_CLI_CONFIG_FILE="/app/.openviking/ovcli.conf" \
- OPENVIKING_WEB_STUDIO_DIR="/app/web-studio/dist"
+ OPENVIKING_CLI_CONFIG_FILE="/app/.openviking/ovcli.conf"
-EXPOSE 1933 8020
+EXPOSE 1933
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
CMD curl -fsS http://127.0.0.1:1933/health || exit 1
@@ -138,4 +140,4 @@ HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
# JSON, or `docker exec` in and run `openviking-server init`.
# Override command to run CLI, e.g.:
# docker run --rm -v ~/.openviking:/app/.openviking <image> openviking --help
-ENTRYPOINT ["openviking-console-entrypoint"]
+ENTRYPOINT ["openviking-entrypoint"]
diff --git a/docker-compose.yml b/docker-compose.yml
index 33b6822ff..c9a32e3eb 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -16,12 +16,10 @@ services:
openviking:
image: ghcr.io/volcengine/openviking:latest
container_name: openviking
- # Direct access to individual services (optional — caddy:1934 is the
- # recommended single entry point). Comment these out once Caddy is your
- # only ingress.
+ # Direct access (optional — caddy:1934 is the recommended single entry
+ # point). Comment this out once Caddy is your only ingress.
ports:
- "1933:1933"
- - "8020:8020"
volumes:
- ~/.openviking:/app/.openviking
environment:
@@ -34,8 +32,8 @@ services:
start_period: 30s
restart: unless-stopped
- # Aggregated reverse proxy — merges API (1933) + Console (8020) on port
- # 1934 under one origin. Always enabled, plain HTTP by default.
+ # Aggregated reverse proxy — fronts OV (1933) on port 1934 under one stable
+ # origin. Always enabled, plain HTTP by default.
#
# For public HTTPS: edit the Caddyfile to add a domain block, set
# OPENVIKING_PUBLIC_BASE_URL in .env, uncomment the 80/443 port lines
diff --git a/docker/openviking-console-entrypoint.sh b/docker/openviking-entrypoint.sh
similarity index 56%
rename from docker/openviking-console-entrypoint.sh
rename to docker/openviking-entrypoint.sh
index b844601a9..eb48a9fcc 100644
--- a/docker/openviking-console-entrypoint.sh
+++ b/docker/openviking-entrypoint.sh
@@ -3,16 +3,11 @@ set -eu
SERVER_URL="http://127.0.0.1:1933"
SERVER_HEALTH_URL="${SERVER_URL}/health"
-SERVER_READY_URL="${SERVER_URL}/ready"
-CONSOLE_PORT="${OPENVIKING_CONSOLE_PORT:-8020}"
-CONSOLE_HOST="${OPENVIKING_CONSOLE_HOST:-0.0.0.0}"
WITH_BOT="${OPENVIKING_WITH_BOT:-1}"
HEALTH_MAX_ATTEMPTS="${OPENVIKING_HEALTH_MAX_ATTEMPTS:-120}"
-READY_MAX_ATTEMPTS="${OPENVIKING_READY_MAX_ATTEMPTS:-300}"
CONFIG_FILE="${OPENVIKING_CONFIG_FILE:-/app/.openviking/ov.conf}"
PENDING_HEALTH_SCRIPT="/usr/local/bin/openviking-pending-health"
SERVER_PID=""
-CONSOLE_PID=""
PENDING_PID=""
stop_pending_health() {
@@ -30,11 +25,11 @@ ensure_config() {
mkdir -p "$(dirname "${CONFIG_FILE}")"
if [ -n "${OPENVIKING_CONF_CONTENT:-}" ]; then
printf '%s' "${OPENVIKING_CONF_CONTENT}" > "${CONFIG_FILE}"
- echo "[openviking-console-entrypoint] wrote ${CONFIG_FILE} from OPENVIKING_CONF_CONTENT"
+ echo "[openviking-entrypoint] wrote ${CONFIG_FILE} from OPENVIKING_CONF_CONTENT"
return
fi
cat >&2 <<EOF
-[openviking-console-entrypoint] ${CONFIG_FILE} not found.
+[openviking-entrypoint] ${CONFIG_FILE} not found.
To start OpenViking, do one of:
- mount ~/.openviking on the host to /app/.openviking
@@ -52,7 +47,7 @@ EOF
while [ ! -f "${CONFIG_FILE}" ]; do
if ! kill -0 "${PENDING_PID}" 2>/dev/null; then
- echo "[openviking-console-entrypoint] pending health server exited unexpectedly" >&2
+ echo "[openviking-entrypoint] pending health server exited unexpectedly" >&2
PENDING_PID=""
exit 1
fi
@@ -61,7 +56,7 @@ EOF
stop_pending_health
trap - INT TERM
- echo "[openviking-console-entrypoint] detected ${CONFIG_FILE}, starting OpenViking"
+ echo "[openviking-entrypoint] detected ${CONFIG_FILE}, starting OpenViking"
}
normalize_with_bot() {
@@ -73,7 +68,7 @@ normalize_with_bot() {
WITH_BOT="0"
;;
*)
- echo "[openviking-console-entrypoint] invalid OPENVIKING_WITH_BOT=${1}" >&2
+ echo "[openviking-entrypoint] invalid OPENVIKING_WITH_BOT=${1}" >&2
exit 2
;;
esac
@@ -102,9 +97,6 @@ forward_signal() {
if [ -n "${SERVER_PID}" ] && kill -0 "${SERVER_PID}" 2>/dev/null; then
kill "${SERVER_PID}" 2>/dev/null || true
fi
- if [ -n "${CONSOLE_PID}" ] && kill -0 "${CONSOLE_PID}" 2>/dev/null; then
- kill "${CONSOLE_PID}" 2>/dev/null || true
- fi
}
trap 'forward_signal' INT TERM
@@ -122,58 +114,19 @@ attempt=0
until curl -fsS "${SERVER_HEALTH_URL}" >/dev/null 2>&1; do
attempt=$((attempt + 1))
if ! kill -0 "${SERVER_PID}" 2>/dev/null; then
- echo "[openviking-console-entrypoint] openviking-server exited before becoming healthy" >&2
+ echo "[openviking-entrypoint] openviking-server exited before becoming healthy" >&2
wait "${SERVER_PID}" || true
exit 1
fi
if [ "${attempt}" -ge "${HEALTH_MAX_ATTEMPTS}" ]; then
- echo "[openviking-console-entrypoint] timed out waiting for ${SERVER_HEALTH_URL}" >&2
+ echo "[openviking-entrypoint] timed out waiting for ${SERVER_HEALTH_URL}" >&2
forward_signal
wait "${SERVER_PID}" || true
exit 1
fi
sleep 1
done
+echo "[openviking-entrypoint] openviking-server is healthy"
-# Wait for server to become fully ready before starting console
-ready_attempt=0
-until curl -fsS "${SERVER_READY_URL}" 2>/dev/null | grep -q '"status":"ready"'; do
- ready_attempt=$((ready_attempt + 1))
- if ! kill -0 "${SERVER_PID}" 2>/dev/null; then
- echo "[openviking-console-entrypoint] openviking-server exited before becoming ready" >&2
- wait "${SERVER_PID}" || true
- exit 1
- fi
- if [ "${ready_attempt}" -ge "${READY_MAX_ATTEMPTS}" ]; then
- echo "[openviking-console-entrypoint] timed out waiting for ${SERVER_READY_URL}" >&2
- forward_signal
- wait "${SERVER_PID}" || true
- exit 1
- fi
- sleep 2
-done
-echo "[openviking-console-entrypoint] openviking-server is ready"
-
-python -m openviking.console.bootstrap \
- --host "${CONSOLE_HOST}" \
- --port "${CONSOLE_PORT}" \
- --openviking-url "${SERVER_URL}" &
-CONSOLE_PID=$!
-
-while kill -0 "${SERVER_PID}" 2>/dev/null && kill -0 "${CONSOLE_PID}" 2>/dev/null; do
- sleep 1
-done
-
-if ! kill -0 "${SERVER_PID}" 2>/dev/null; then
- wait "${SERVER_PID}" || SERVER_STATUS=$?
- SERVER_STATUS=${SERVER_STATUS:-1}
- forward_signal
- wait "${CONSOLE_PID}" || true
- exit "${SERVER_STATUS}"
-fi
-
-wait "${CONSOLE_PID}" || CONSOLE_STATUS=$?
-CONSOLE_STATUS=${CONSOLE_STATUS:-0}
-forward_signal
-wait "${SERVER_PID}" || true
-exit "${CONSOLE_STATUS}"
+wait "${SERVER_PID}" || SERVER_STATUS=$?
+exit "${SERVER_STATUS:-0}"
diff --git a/docs/en/getting-started/02-quickstart.md b/docs/en/getting-started/02-quickstart.md
index 9f42ecf62..02d9d0653 100644
--- a/docs/en/getting-started/02-quickstart.md
+++ b/docs/en/getting-started/02-quickstart.md
@@ -40,7 +40,6 @@ If you prefer to run OpenViking as a standalone service, Docker is recommended.
container_name: openviking
ports:
- "1933:1933"
- - "8020:8020"
volumes:
- ~/.openviking:/app/.openviking
restart: unless-stopped
@@ -50,7 +49,7 @@ If you prefer to run OpenViking as a standalone service, Docker is recommended.
docker-compose up -d
```
- By default, the container starts the OpenViking API server on `1933`, the Console UI on `8020`, and the bundled `vikingbot` gateway. If you need to disable `vikingbot`, add either `command: ["--without-bot"]` or `environment: ["OPENVIKING_WITH_BOT=0"]`.
+ By default, the container starts the OpenViking API server on `1933` (which also serves the Web Studio UI at `/studio`) and the bundled `vikingbot` gateway. If you need to disable `vikingbot`, add either `command: ["--without-bot"]` or `environment: ["OPENVIKING_WITH_BOT=0"]`.
On platforms that don't allow bind mounts, set `OPENVIKING_CONF_CONTENT` to the full config JSON to bootstrap on first start, or `docker exec` in and run `openviking-server init` after the container is up. See [Deployment Guide](../guides/03-deployment.md#when-docker--v-is-not-available) for details.
@@ -65,7 +64,6 @@ If you prefer to run OpenViking as a standalone service, Docker is recommended.
> openviking:
> image: ghcr.io/volcengine/openviking:latest
> ports:
-> - "8020:8020"
> - "1933:1934" # Map host 1933 to container 1934
> volumes:
> - ~/.openviking:/app/.openviking
diff --git a/docs/zh/getting-started/02-quickstart.md b/docs/zh/getting-started/02-quickstart.md
index ebb2ce8c7..5b57914d0 100644
--- a/docs/zh/getting-started/02-quickstart.md
+++ b/docs/zh/getting-started/02-quickstart.md
@@ -40,7 +40,6 @@ pip install openviking --upgrade --force-reinstall
container_name: openviking
ports:
- "1933:1933"
- - "8020:8020"
volumes:
- ~/.openviking:/app/.openviking
restart: unless-stopped
@@ -50,7 +49,7 @@ pip install openviking --upgrade --force-reinstall
docker-compose up -d
```
- 默认情况下,容器会同时启动 OpenViking API 服务(`1933`)、Console 界面(`8020`)以及内置的 `vikingbot` gateway。如果你需要关闭 `vikingbot`,可以在 Compose 里增加 `command: ["--without-bot"]`,或者设置 `environment: ["OPENVIKING_WITH_BOT=0"]`。
+ 默认情况下,容器会启动 OpenViking API 服务(`1933`,同时在 `/studio` 提供 Web Studio 前端)以及内置的 `vikingbot` gateway。如果你需要关闭 `vikingbot`,可以在 Compose 里增加 `command: ["--without-bot"]`,或者设置 `environment: ["OPENVIKING_WITH_BOT=0"]`。
如果运行平台不支持 bind mount,可以通过 `OPENVIKING_CONF_CONTENT` 环境变量传入完整的配置 JSON,或在容器启动后 `docker exec` 进去执行 `openviking-server init`。详见 [部署指南](../guides/03-deployment.md#无法使用-docker--v-时)。
@@ -65,7 +64,6 @@ pip install openviking --upgrade --force-reinstall
> openviking:
> image: ghcr.io/volcengine/openviking:latest
> ports:
-> - "8020:8020"
> - "1933:1934" # 将宿主机 1933 映射到容器 1934
> volumes:
> - ~/.openviking:/app/.openviking
diff --git a/openviking/console/README.md b/openviking/console/README.md
deleted file mode 100644
index 0dd8be6de..000000000
--- a/openviking/console/README.md
+++ /dev/null
@@ -1,59 +0,0 @@
-# OpenViking Console
-
-This is a standalone console service.
-It is not wired into release packaging or CLI commands.
-
-## What it provides
-
-- File system browsing (`ls/read/stat`)
-- Find query
-- Add resource (`/api/v1/resources`)
-- Tenant/account management UI
-- System/observer status panels
-
-## Quick start
-
-1. Start OpenViking server (default: `http://127.0.0.1:1933`)
-2. Start the console service:
-
-```bash
-python -m openviking.console.bootstrap \
- --host 127.0.0.1 \
- --port 8020 \
- --openviking-url http://127.0.0.1:1933
-```
-
-3. Open:
-
-```text
-http://127.0.0.1:8020/
-```
-
-4. In **Settings**, configure headers for your upstream auth mode.
-`api_key` is the default server mode, so in that mode you normally paste `X-API-Key` and click **Save** (or press Enter). If the upstream server runs in `trusted` mode, you can omit `X-API-Key` for ordinary requests only when that server is localhost-only and has no `root_api_key`; otherwise you still need `X-API-Key`, and you should also set `X-OpenViking-Account` and `X-OpenViking-User` (and optionally `X-OpenViking-Agent`).
-`X-API-Key` is stored locally in the browser and restored into the current tab.
-
-When the upstream server runs in `trusted` mode, ordinary access does not require user registration first. If you try account or user management actions against Admin API endpoints in `trusted` mode, the server now returns an explicit error explaining that `trusted` mode resolves requests as `USER` and that account/user management requires `api_key` mode with `root_api_key`.
-
-## Startup parameters
-
-- `--openviking-url` (default `http://127.0.0.1:1933`)
-- `--host` (default `127.0.0.1`)
-- `--port` (default `8020`)
-- `--write-enabled` (default `false`)
-- `--request-timeout-sec` (default `30`)
-- `--cors-origins` (default `*`, comma-separated)
-
-Without `--write-enabled`, write operations are blocked by backend guardrails.
-If you need **Add Resource** or **multi-tenant management** (create/delete account, add/delete user, role/key changes),
-start with `--write-enabled`.
-
-Example:
-
-```bash
-python -m openviking.console.bootstrap \
- --host 127.0.0.1 \
- --port 8020 \
- --openviking-url http://127.0.0.1:1933 \
- --write-enabled
-```
diff --git a/openviking/console/__init__.py b/openviking/console/__init__.py
deleted file mode 100644
index 3d71e1049..000000000
--- a/openviking/console/__init__.py
+++ /dev/null
@@ -1,10 +0,0 @@
-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: AGPL-3.0
-
-"""OpenViking Console (standalone web dashboard).
-
-This package contains the FastAPI app and static frontend assets.
-"""
-
-from .app import create_console_app # noqa: F401
-from .config import ConsoleConfig, load_console_config # noqa: F401
diff --git a/openviking/console/app.py b/openviking/console/app.py
deleted file mode 100644
index 8883a063f..000000000
--- a/openviking/console/app.py
+++ /dev/null
@@ -1,514 +0,0 @@
-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: AGPL-3.0
-"""FastAPI app for the standalone OpenViking console service."""
-
-from __future__ import annotations
-
-import json
-import re
-from contextlib import asynccontextmanager
-from pathlib import Path
-from typing import Optional
-
-import httpx
-from fastapi import APIRouter, FastAPI, Request
-from fastapi.middleware.cors import CORSMiddleware
-from fastapi.responses import FileResponse, JSONResponse, Response
-
-from .config import (
- ConsoleConfig,
- as_runtime_capabilities,
- load_console_config,
-)
-
-PROXY_PREFIX = "/console/api/v1"
-_CONSOLE_NO_STORE_HEADERS = {"Cache-Control": "no-store"}
-_SAFE_PATH_SEGMENT = re.compile(r"^[\w.@+-]+$")
-
-_ALLOWED_FORWARD_HEADERS = {
- "accept",
- "x-api-key",
- "authorization",
- "x-openviking-account",
- "x-openviking-user",
- "x-openviking-agent",
- "content-type",
-}
-
-_ALLOWED_FORWARD_RESPONSE_HEADERS = {
- # Content negotiation / caching / downloads
- "content-type",
- "content-disposition",
- "cache-control",
- "etag",
- "last-modified",
- # Observability
- "x-request-id",
-}
-
-
-def _is_json_content_type(content_type: str) -> bool:
- value = (content_type or "").lower()
- return "application/json" in value or "+json" in value
-
-
-def _should_default_telemetry(upstream_path: str) -> bool:
- if upstream_path in {"/api/v1/search/find", "/api/v1/resources"}:
- return True
- return upstream_path.startswith("/api/v1/sessions/") and upstream_path.endswith("/commit")
-
-
-def _with_default_telemetry(request: Request, upstream_path: str, body: bytes) -> bytes:
- if request.method.upper() != "POST":
- return body
- if not _should_default_telemetry(upstream_path):
- return body
- if not _is_json_content_type(request.headers.get("content-type", "")):
- return body
-
- try:
- payload = json.loads(body.decode("utf-8")) if body else {}
- except (json.JSONDecodeError, UnicodeDecodeError):
- return body
- if not isinstance(payload, dict):
- return body
-
- payload.setdefault("telemetry", True)
- return json.dumps(payload).encode("utf-8")
-
-
-def _error_response(status_code: int, code: str, message: str, details: Optional[dict] = None):
- return JSONResponse(
- status_code=status_code,
- content={
- "status": "error",
- "error": {
- "code": code,
- "message": message,
- "details": details or {},
- },
- },
- )
-
-
-def _copy_forward_headers(request: Request) -> dict[str, str]:
- headers: dict[str, str] = {}
- for key, value in request.headers.items():
- if key.lower() in _ALLOWED_FORWARD_HEADERS:
- headers[key] = value
- return headers
-
-
-def _copy_forward_response_headers(upstream_response: httpx.Response) -> dict[str, str]:
- headers: dict[str, str] = {}
- for key, value in upstream_response.headers.items():
- if key.lower() in _ALLOWED_FORWARD_RESPONSE_HEADERS:
- headers[key] = value
- return headers
-
-
-async def _forward_request(request: Request, upstream_path: str) -> Response:
- """Forward the incoming request to OpenViking upstream."""
- client: httpx.AsyncClient = request.app.state.upstream_client
- body = await request.body()
- body = _with_default_telemetry(request, upstream_path, body)
- try:
- upstream_response = await client.request(
- method=request.method,
- url=upstream_path,
- params=request.query_params,
- content=body,
- headers=_copy_forward_headers(request),
- )
- except httpx.RequestError as exc:
- return _error_response(
- status_code=502,
- code="UPSTREAM_UNAVAILABLE",
- message=f"Failed to reach OpenViking upstream: {exc}",
- )
-
- content_type = upstream_response.headers.get("content-type", "application/json")
- return Response(
- content=upstream_response.content,
- status_code=upstream_response.status_code,
- media_type=content_type,
- headers=_copy_forward_response_headers(upstream_response),
- )
-
-
-def _ensure_write_enabled(request: Request) -> Optional[JSONResponse]:
- config: ConsoleConfig = request.app.state.console_config
- if config.write_enabled:
- return None
- return _error_response(
- status_code=403,
- code="WRITE_DISABLED",
- message=(
- "Console write mode is disabled. Start service with --write-enabled "
- "and restart the service to allow write operations."
- ),
- )
-
-
-def _validate_path_param(value: str, name: str) -> Optional[JSONResponse]:
- if not value or value in {".", ".."} or not _SAFE_PATH_SEGMENT.match(value):
- return _error_response(
- status_code=400,
- code="INVALID_PARAMETER",
- message=f"Invalid {name}",
- )
- return None
-
-
-def _validate_fs_path(path_str: str) -> Optional[JSONResponse]:
- """Validate file system path to prevent directory traversal attacks."""
- if not path_str:
- # Empty path is allowed (means current directory)
- return None
-
- # Reject absolute paths
- if path_str.startswith("/") or path_str.startswith("\\"):
- return _error_response(
- status_code=400,
- code="INVALID_PATH",
- message="Absolute paths are not allowed",
- )
-
- # Check for Windows drive letters (C:, D:, etc.)
- if len(path_str) >= 2 and path_str[1] == ":":
- return _error_response(
- status_code=400,
- code="INVALID_PATH",
- message="Absolute paths are not allowed",
- )
-
- # Check for parent directory traversal
- if ".." in path_str:
- return _error_response(
- status_code=400,
- code="INVALID_PATH",
- message="Path traversal sequences (..) are not allowed",
- )
-
- return None
-
-
-def _create_proxy_router() -> APIRouter:
- router = APIRouter(prefix=PROXY_PREFIX, tags=["console"])
-
- @router.get("/runtime/capabilities")
- async def runtime_capabilities(request: Request):
- config: ConsoleConfig = request.app.state.console_config
- return {"status": "ok", "result": as_runtime_capabilities(config)}
-
- # ---- Read routes ----
-
- @router.get("/ov/fs/ls")
- async def fs_ls(request: Request):
- path = request.query_params.get("path", "")
- invalid = _validate_fs_path(path)
- if invalid:
- return invalid
- return await _forward_request(request, "/api/v1/fs/ls")
-
- @router.get("/ov/fs/tree")
- async def fs_tree(request: Request):
- path = request.query_params.get("path", "")
- invalid = _validate_fs_path(path)
- if invalid:
- return invalid
- return await _forward_request(request, "/api/v1/fs/tree")
-
- @router.get("/ov/fs/stat")
- async def fs_stat(request: Request):
- return await _forward_request(request, "/api/v1/fs/stat")
-
- @router.post("/ov/search/find")
- async def search_find(request: Request):
- return await _forward_request(request, "/api/v1/search/find")
-
- @router.get("/ov/content/read")
- async def content_read(request: Request):
- return await _forward_request(request, "/api/v1/content/read")
-
- @router.get("/ov/admin/accounts")
- async def admin_accounts(request: Request):
- return await _forward_request(request, "/api/v1/admin/accounts")
-
- @router.get("/ov/admin/accounts/{account_id}/users")
- async def admin_users(request: Request, account_id: str):
- invalid = _validate_path_param(account_id, "account_id")
- if invalid:
- return invalid
- return await _forward_request(request, f"/api/v1/admin/accounts/{account_id}/users")
-
- @router.get("/ov/admin/accounts/{account_id}/agents")
- async def admin_agents(request: Request, account_id: str):
- invalid = _validate_path_param(account_id, "account_id")
- if invalid:
- return invalid
- return await _forward_request(request, f"/api/v1/admin/accounts/{account_id}/agents")
-
- @router.get("/ov/system/status")
- async def system_status(request: Request):
- return await _forward_request(request, "/api/v1/system/status")
-
- @router.get("/ov/console/dashboard/summary")
- async def console_dashboard_summary(request: Request):
- return await _forward_request(request, "/api/v1/console/dashboard/summary")
-
- @router.get("/ov/console/tokens")
- async def console_tokens(request: Request):
- return await _forward_request(request, "/api/v1/console/tokens")
-
- @router.get("/ov/console/context-commits")
- async def console_context_commits(request: Request):
- return await _forward_request(request, "/api/v1/console/context-commits")
-
- @router.get("/ov/console/audit")
- async def console_audit(request: Request):
- return await _forward_request(request, "/api/v1/console/audit")
-
- @router.get("/ov/observer/{component}")
- async def observer_component(request: Request, component: str):
- invalid = _validate_path_param(component, "component")
- if invalid:
- return invalid
- return await _forward_request(request, f"/api/v1/observer/{component}")
-
- @router.post("/ov/auth/otp")
- async def issue_otp(request: Request):
- # OTP issuance binds to the caller's existing API key identity, so it
- # uses the same auth flow as any other read endpoint. Not gated by
- # write_enabled — minting an authentication artifact for yourself is
- # not a data mutation.
- return await _forward_request(request, "/api/v1/auth/otp")
-
- @router.post("/ov/auth/oauth-verify")
- async def oauth_verify(request: Request):
- # Confirm a pending OAuth authorization (device-flow style). The
- # caller is the console-authenticated user; the API key in their
- # session storage is what binds the issuing identity.
- return await _forward_request(request, "/api/v1/auth/oauth-verify")
-
- # ---- Write routes ----
-
- @router.post("/ov/fs/mkdir")
- async def fs_mkdir(request: Request):
- blocked = _ensure_write_enabled(request)
- if blocked:
- return blocked
- return await _forward_request(request, "/api/v1/fs/mkdir")
-
- @router.post("/ov/resources")
- async def add_resource(request: Request):
- blocked = _ensure_write_enabled(request)
- if blocked:
- return blocked
- return await _forward_request(request, "/api/v1/resources")
-
- @router.post("/ov/resources/temp_upload")
- async def add_resource_temp_upload(request: Request):
- blocked = _ensure_write_enabled(request)
- if blocked:
- return blocked
- return await _forward_request(request, "/api/v1/resources/temp_upload")
-
- @router.post("/ov/fs/mv")
- async def fs_mv(request: Request):
- blocked = _ensure_write_enabled(request)
- if blocked:
- return blocked
- return await _forward_request(request, "/api/v1/fs/mv")
-
- @router.delete("/ov/fs")
- async def fs_rm(request: Request):
- blocked = _ensure_write_enabled(request)
- if blocked:
- return blocked
- return await _forward_request(request, "/api/v1/fs")
-
- @router.post("/ov/admin/accounts")
- async def create_account(request: Request):
- blocked = _ensure_write_enabled(request)
- if blocked:
- return blocked
- return await _forward_request(request, "/api/v1/admin/accounts")
-
- @router.delete("/ov/admin/accounts/{account_id}")
- async def delete_account(request: Request, account_id: str):
- blocked = _ensure_write_enabled(request)
- if blocked:
- return blocked
- invalid = _validate_path_param(account_id, "account_id")
- if invalid:
- return invalid
- return await _forward_request(request, f"/api/v1/admin/accounts/{account_id}")
-
- @router.post("/ov/admin/accounts/{account_id}/users")
- async def create_user(request: Request, account_id: str):
- blocked = _ensure_write_enabled(request)
- if blocked:
- return blocked
- invalid = _validate_path_param(account_id, "account_id")
- if invalid:
- return invalid
- return await _forward_request(request, f"/api/v1/admin/accounts/{account_id}/users")
-
- @router.delete("/ov/admin/accounts/{account_id}/users/{user_id}")
- async def delete_user(request: Request, account_id: str, user_id: str):
- blocked = _ensure_write_enabled(request)
- if blocked:
- return blocked
- invalid = _validate_path_param(account_id, "account_id")
- if invalid:
- return invalid
- invalid = _validate_path_param(user_id, "user_id")
- if invalid:
- return invalid
- return await _forward_request(
- request, f"/api/v1/admin/accounts/{account_id}/users/{user_id}"
- )
-
- @router.put("/ov/admin/accounts/{account_id}/users/{user_id}/role")
- async def set_user_role(request: Request, account_id: str, user_id: str):
- blocked = _ensure_write_enabled(request)
- if blocked:
- return blocked
- invalid = _validate_path_param(account_id, "account_id")
- if invalid:
- return invalid
- invalid = _validate_path_param(user_id, "user_id")
- if invalid:
- return invalid
- return await _forward_request(
- request,
- f"/api/v1/admin/accounts/{account_id}/users/{user_id}/role",
- )
-
- @router.post("/ov/admin/accounts/{account_id}/users/{user_id}/key")
- async def regenerate_key(request: Request, account_id: str, user_id: str):
- blocked = _ensure_write_enabled(request)
- if blocked:
- return blocked
- invalid = _validate_path_param(account_id, "account_id")
- if invalid:
- return invalid
- invalid = _validate_path_param(user_id, "user_id")
- if invalid:
- return invalid
- return await _forward_request(
- request,
- f"/api/v1/admin/accounts/{account_id}/users/{user_id}/key",
- )
-
- @router.post("/ov/sessions")
- async def create_session(request: Request):
- blocked = _ensure_write_enabled(request)
- if blocked:
- return blocked
- return await _forward_request(request, "/api/v1/sessions")
-
- @router.post("/ov/sessions/{session_id}/messages")
- async def add_session_message(request: Request, session_id: str):
- blocked = _ensure_write_enabled(request)
- if blocked:
- return blocked
- invalid = _validate_path_param(session_id, "session_id")
- if invalid:
- return invalid
- return await _forward_request(request, f"/api/v1/sessions/{session_id}/messages")
-
- @router.post("/ov/sessions/{session_id}/commit")
- async def commit_session(request: Request, session_id: str):
- blocked = _ensure_write_enabled(request)
- if blocked:
- return blocked
- invalid = _validate_path_param(session_id, "session_id")
- if invalid:
- return invalid
- return await _forward_request(request, f"/api/v1/sessions/{session_id}/commit")
-
- return router
-
-
-def create_console_app(
- config: Optional[ConsoleConfig] = None,
- upstream_transport: Optional[httpx.AsyncBaseTransport] = None,
-) -> FastAPI:
- """Create console app instance."""
- if config is None:
- config = load_console_config()
-
- static_dir = Path(__file__).resolve().parent / "static"
- index_file = static_dir / "index.html"
-
- @asynccontextmanager
- async def lifespan(app: FastAPI):
- try:
- yield
- finally:
- client: httpx.AsyncClient = app.state.upstream_client
- if not client.is_closed:
- await client.aclose()
-
- app = FastAPI(
- title="OpenViking Console",
- description="Standalone console for OpenViking HTTP APIs",
- version="0.1.0",
- lifespan=lifespan,
- )
-
- app.state.console_config = config
- app.state.upstream_client = httpx.AsyncClient(
- base_url=config.normalized_base_url(),
- timeout=config.request_timeout_sec,
- transport=upstream_transport,
- )
-
- app.add_middleware(
- CORSMiddleware,
- allow_origins=config.cors_origins,
- allow_methods=["*"],
- allow_headers=["*"],
- # Avoid invalid/unsafe combination: allow_credentials + wildcard origin.
- allow_credentials=("*" not in config.cors_origins),
- )
-
- app.include_router(_create_proxy_router())
-
- def _console_file_response(path: Path) -> FileResponse:
- return FileResponse(path, headers=_CONSOLE_NO_STORE_HEADERS)
-
- @app.get("/health", include_in_schema=False)
- async def healthz():
- return {"status": "ok", "service": "openviking-console"}
-
- @app.get("/", include_in_schema=False)
- async def index_root():
- return _console_file_response(index_file)
-
- @app.get("/console", include_in_schema=False)
- async def index_console():
- return _console_file_response(index_file)
-
- @app.get("/console/{path:path}", include_in_schema=False)
- async def console_assets(path: str):
- if path.startswith("api/"):
- return _error_response(status_code=404, code="NOT_FOUND", message="Not found")
-
- # Prevent directory traversal (e.g. /console/%2e%2e/...)
- static_root = static_dir.resolve()
- try:
- requested_file = (static_dir / path).resolve()
- except OSError:
- return _error_response(status_code=404, code="NOT_FOUND", message="Not found")
-
- if not requested_file.is_relative_to(static_root):
- return _error_response(status_code=404, code="NOT_FOUND", message="Not found")
-
- if requested_file.exists() and requested_file.is_file():
- return _console_file_response(requested_file)
- return _console_file_response(index_file)
-
- return app
diff --git a/openviking/console/bootstrap.py b/openviking/console/bootstrap.py
deleted file mode 100644
index 1ad56a188..000000000
--- a/openviking/console/bootstrap.py
+++ /dev/null
@@ -1,75 +0,0 @@
-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: AGPL-3.0
-"""Bootstrap entrypoint for OpenViking console service."""
-
-from __future__ import annotations
-
-import argparse
-import sys
-from pathlib import Path
-
-import uvicorn
-
-if __package__ in {None, ""}:
- # Allow running as a script from a source checkout:
- # python openviking/console/bootstrap.py
- sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
-
-from openviking.console.app import create_console_app
-from openviking.console.config import load_console_config
-
-
-def _build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(
- description="OpenViking Console",
- formatter_class=argparse.ArgumentDefaultsHelpFormatter,
- )
- parser.add_argument("--host", type=str, default="127.0.0.1", help="Host to bind to")
- parser.add_argument("--port", type=int, default=8020, help="Port to bind to")
- parser.add_argument(
- "--openviking-url",
- type=str,
- default="http://127.0.0.1:1933",
- help="Base URL for OpenViking HTTP service",
- )
- parser.add_argument(
- "--write-enabled",
- action="store_true",
- help="Enable write operations in console proxy",
- )
- parser.add_argument(
- "--request-timeout-sec",
- type=float,
- default=3600.0,
- help="Upstream request timeout in seconds",
- )
- parser.add_argument(
- "--cors-origins",
- type=str,
- default="*",
- help="Comma-separated CORS origins",
- )
- return parser
-
-
-def main() -> None:
- """Run console service."""
- parser = _build_parser()
- args = parser.parse_args()
-
- config = load_console_config(
- host=args.host,
- port=args.port,
- openviking_base_url=args.openviking_url,
- write_enabled=args.write_enabled,
- request_timeout_sec=args.request_timeout_sec,
- cors_origins=args.cors_origins,
- )
-
- app = create_console_app(config=config)
- print(f"OpenViking Console is running on {config.host}:{config.port}")
- uvicorn.run(app, host=config.host, port=config.port)
-
-
-if __name__ == "__main__":
- main()
diff --git a/openviking/console/config.py b/openviking/console/config.py
deleted file mode 100644
index 0b26c82eb..000000000
--- a/openviking/console/config.py
+++ /dev/null
@@ -1,84 +0,0 @@
-# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
-# SPDX-License-Identifier: AGPL-3.0
-"""Configuration for the standalone OpenViking console service."""
-
-from __future__ import annotations
-
-from dataclasses import dataclass, field
-from typing import Iterable, List
-
-
-def _parse_cors_origins(raw_value: str | None) -> List[str]:
- if not raw_value:
- return ["*"]
- return [item.strip() for item in raw_value.split(",") if item.strip()]
-
-
-@dataclass(slots=True)
-class ConsoleConfig:
- """Runtime settings for console BFF + static frontend."""
-
- host: str = "127.0.0.1"
- port: int = 8020
- openviking_base_url: str = "http://127.0.0.1:1933"
- write_enabled: bool = False
- request_timeout_sec: float = 30.0
- cors_origins: List[str] = field(default_factory=lambda: ["*"])
-
- def normalized_base_url(self) -> str:
- """Return upstream base URL without trailing slash."""
- return self.openviking_base_url.rstrip("/")
-
-
-def load_console_config(
- *,
- host: str = "127.0.0.1",
- port: int = 8020,
- openviking_base_url: str = "http://127.0.0.1:1933",
- write_enabled: bool = False,
- request_timeout_sec: float = 30.0,
- cors_origins: str | List[str] | None = None,
-) -> ConsoleConfig:
- """Load console config from startup parameters."""
- resolved_cors_origins = (
- _parse_cors_origins(cors_origins)
- if isinstance(cors_origins, str) or cors_origins is None
- else list(cors_origins)
- )
- return ConsoleConfig(
- host=host,
- port=port,
- openviking_base_url=openviking_base_url,
- write_enabled=write_enabled,
- request_timeout_sec=request_timeout_sec,
- cors_origins=resolved_cors_origins,
- )
-
-
-def as_runtime_capabilities(config: ConsoleConfig) -> dict:
- """Expose runtime behavior switches for UI gating."""
- allowed_modules: Iterable[str] = [
- "fs.read",
- "search.find",
- "admin.read",
- "monitor.read",
- ]
- if config.write_enabled:
- allowed_modules = [*allowed_modules, "fs.write", "admin.write", "resources.write"]
-
- return {
- "write_enabled": config.write_enabled,
- "allowed_modules": list(allowed_modules),
- "dangerous_actions": [
- "fs.mkdir",
- "fs.mv",
- "fs.rm",
- "admin.create_account",
- "admin.delete_account",
- "admin.create_user",
- "admin.delete_user",
- "admin.set_role",
- "admin.regenerate_key",
- "resources.add_resource",
- ],
- }
diff --git a/openviking/console/static/app.js b/openviking/console/static/app.js
deleted file mode 100644
index 26fd86ea4..000000000
--- a/openviking/console/static/app.js
+++ /dev/null
@@ -1,2663 +0,0 @@
-import {
- buildRequestHeaders,
- resolveRuntimeConsoleSettings,
- saveConsoleSettings,
-} from "./console_settings.js";
-
-const API_BASE = "/console/api/v1";
-const SESSION_KEY = "ov_console_api_key";
-const THEME_MODE_KEY = "ov_console_theme_mode";
-const NAV_COLLAPSED_KEY = "ov_console_nav_collapsed";
-const RESULT_COLLAPSED_KEY = "ov_console_result_collapsed_v2";
-
-const state = {
- activePanel: "filesystem",
- writeEnabled: false,
- fsCurrentUri: "viking://",
- fsHistory: [],
- fsSortField: "uri",
- fsSortDirection: "asc",
- fsViewMode: "list",
- fsTreeData: {},
- fsTreeExpanded: new Set(),
- findRows: [],
- findSortField: "",
- findSortDirection: "asc",
- addResourceMode: "path",
- tenantAccounts: [],
- tenantFilteredAccounts: [],
- tenantUsers: [],
- tenantSelectedAccountId: "",
- tenantAccountsLoaded: false,
- tenantAccountSortField: "account_id",
- tenantAccountSortDirection: "asc",
- tenantUserSortField: "user_id",
- tenantUserSortDirection: "asc",
- tenantConfirmRequest: null,
- themeMode: "dark",
- navCollapsed: false,
- resultCollapsed: false,
- connectionSettings: {
- apiKey: "",
- accountId: "",
- userId: "",
- agentId: "",
- },
-};
-
-const elements = {
- workspace: document.querySelector(".workspace"),
- shell: document.querySelector(".shell"),
- content: document.querySelector(".content"),
- panelStack: document.querySelector(".panel-stack"),
- sidebar: document.querySelector(".sidebar"),
- resultCard: document.querySelector(".result-card"),
- sidebarResizer: document.getElementById("sidebarResizer"),
- outputResizer: document.getElementById("outputResizer"),
- apiKeyInput: document.getElementById("apiKeyInput"),
- accountInput: document.getElementById("accountInput"),
- userInput: document.getElementById("userInput"),
- agentIdInput: document.getElementById("agentIdInput"),
- saveKeyBtn: document.getElementById("saveKeyBtn"),
- clearKeyBtn: document.getElementById("clearKeyBtn"),
- connectionHint: document.getElementById("connectionHint"),
- getOtpBtn: document.getElementById("getOtpBtn"),
- otpBox: document.getElementById("otpBox"),
- otpValue: document.getElementById("otpValue"),
- otpCopyBtn: document.getElementById("otpCopyBtn"),
- otpExpiry: document.getElementById("otpExpiry"),
- oauthVerifyInput: document.getElementById("oauthVerifyInput"),
- oauthVerifyBtn: document.getElementById("oauthVerifyBtn"),
- oauthDenyBtn: document.getElementById("oauthDenyBtn"),
- oauthVerifyHint: document.getElementById("oauthVerifyHint"),
- writeBadge: document.getElementById("writeBadge"),
- output: document.getElementById("output"),
- tabs: document.querySelectorAll(".tab"),
- panels: document.querySelectorAll(".panel"),
- fsBackBtn: document.getElementById("fsBackBtn"),
- fsUpBtn: document.getElementById("fsUpBtn"),
- fsRefreshBtn: document.getElementById("fsRefreshBtn"),
- fsModeListBtn: document.getElementById("fsModeListBtn"),
- fsModeTreeBtn: document.getElementById("fsModeTreeBtn"),
- fsGoBtn: document.getElementById("fsGoBtn"),
- fsCurrentUri: document.getElementById("fsCurrentUri"),
- fsEntries: document.getElementById("fsEntries"),
- fsSortHeaders: document.querySelectorAll(".fs-sort-btn"),
- fsTable: document.querySelector(".fs-table"),
- fsTableWrap: document.querySelector(".fs-table-wrap"),
- fsTree: document.getElementById("fsTree"),
- findQuery: document.getElementById("findQuery"),
- findTarget: document.getElementById("findTarget"),
- findLimit: document.getElementById("findLimit"),
- findBtn: document.getElementById("findBtn"),
- findResultsHead: document.getElementById("findResultsHead"),
- findResultsBody: document.getElementById("findResultsBody"),
- addResourcePath: document.getElementById("addResourcePath"),
- addResourceFile: document.getElementById("addResourceFile"),
- addResourceModePathBtn: document.getElementById("addResourceModePathBtn"),
- addResourceModeUploadBtn: document.getElementById("addResourceModeUploadBtn"),
- addResourcePathPane: document.getElementById("addResourcePathPane"),
- addResourceUploadPane: document.getElementById("addResourceUploadPane"),
- addResourceTarget: document.getElementById("addResourceTarget"),
- addResourceWait: document.getElementById("addResourceWait"),
- addResourceStrict: document.getElementById("addResourceStrict"),
- addResourceUploadMedia: document.getElementById("addResourceUploadMedia"),
- addResourceTimeout: document.getElementById("addResourceTimeout"),
- addResourceIgnoreDirs: document.getElementById("addResourceIgnoreDirs"),
- addResourceInclude: document.getElementById("addResourceInclude"),
- addResourceExclude: document.getElementById("addResourceExclude"),
- addResourceReason: document.getElementById("addResourceReason"),
- addResourceInstruction: document.getElementById("addResourceInstruction"),
- addResourceSubmitBtn: document.getElementById("addResourceSubmitBtn"),
- addMemoryInput: document.getElementById("addMemoryInput"),
- addMemoryBtn: document.getElementById("addMemoryBtn"),
- tenantAccountSearch: document.getElementById("tenantAccountSearch"),
- tenantRefreshAccountsBtn: document.getElementById("tenantRefreshAccountsBtn"),
- tenantCreateAccountBtn: document.getElementById("tenantCreateAccountBtn"),
- tenantCreateAccountId: document.getElementById("tenantCreateAccountId"),
- tenantCreateAdminUserId: document.getElementById("tenantCreateAdminUserId"),
- tenantAccountsBody: document.getElementById("tenantAccountsBody"),
- tenantCurrentAccount: document.getElementById("tenantCurrentAccount"),
- tenantAddUserBtn: document.getElementById("tenantAddUserBtn"),
- tenantAddUserId: document.getElementById("tenantAddUserId"),
- tenantAddUserRole: document.getElementById("tenantAddUserRole"),
- tenantUsersBody: document.getElementById("tenantUsersBody"),
- tenantAccountSortBtns: document.querySelectorAll("[data-tenant-account-sort]"),
- tenantUserSortBtns: document.querySelectorAll("[data-tenant-user-sort]"),
- tenantConfirmModal: document.getElementById("tenantConfirmModal"),
- tenantConfirmTitle: document.getElementById("tenantConfirmTitle"),
- tenantConfirmMessage: document.getElementById("tenantConfirmMessage"),
- tenantConfirmLabel: document.getElementById("tenantConfirmLabel"),
- tenantConfirmInput: document.getElementById("tenantConfirmInput"),
- tenantConfirmError: document.getElementById("tenantConfirmError"),
- tenantConfirmActionBtn: document.getElementById("tenantConfirmActionBtn"),
- tenantConfirmCancelBtn: document.getElementById("tenantConfirmCancelBtn"),
- systemBtn: document.getElementById("systemBtn"),
- observerBtn: document.getElementById("observerBtn"),
- monitorResults: document.getElementById("monitorResults"),
- navToggleBtn: document.getElementById("navToggleBtn"),
- resultToggleBtn: document.getElementById("resultToggleBtn"),
- clearOutputBtn: document.getElementById("clearOutputBtn"),
- themeButtons: document.querySelectorAll("[data-theme-mode]"),
-};
-
-const layoutLimits = {
- minSidebar: 200,
- maxSidebar: 560,
- minPanel: 180,
- minResult: 56,
-};
-
-function readLocalStorage(key) {
- try {
- return window.localStorage.getItem(key);
- } catch (_error) {
- return null;
- }
-}
-
-function writeLocalStorage(key, value) {
- try {
- window.localStorage.setItem(key, value);
- } catch (_error) {
- // Ignore storage failures in private mode or restricted browsers.
- }
-}
-
-function prefersDarkTheme() {
- return window.matchMedia("(prefers-color-scheme: dark)").matches;
-}
-
-function resolveThemeMode(mode) {
- if (mode === "light") {
- return "light";
- }
- if (mode === "system") {
- return prefersDarkTheme() ? "dark" : "light";
- }
- return "dark";
-}
-
-function updateThemeButtons() {
- for (const button of elements.themeButtons) {
- const selected = button.dataset.themeMode === state.themeMode;
- button.classList.toggle("active", selected);
- button.setAttribute("aria-pressed", selected ? "true" : "false");
- }
-}
-
-function applyThemeMode(mode, { persist = true } = {}) {
- const normalized = mode === "light" || mode === "system" ? mode : "dark";
- state.themeMode = normalized;
- const resolved = resolveThemeMode(normalized);
- document.documentElement.setAttribute("data-theme", resolved);
- updateThemeButtons();
- if (persist) {
- writeLocalStorage(THEME_MODE_KEY, normalized);
- }
-}
-
-function applyShellStateClasses() {
- if (!elements.shell) {
- return;
- }
- elements.shell.classList.toggle("shell--nav-collapsed", state.navCollapsed);
- elements.shell.classList.toggle("shell--result-collapsed", state.resultCollapsed);
-}
-
-function setNavCollapsed(collapsed, { persist = true } = {}) {
- state.navCollapsed = Boolean(collapsed);
- applyShellStateClasses();
- if (persist) {
- writeLocalStorage(NAV_COLLAPSED_KEY, state.navCollapsed ? "1" : "0");
- }
-}
-
-function setResultCollapsed(collapsed, { persist = true } = {}) {
- state.resultCollapsed = Boolean(collapsed);
- applyShellStateClasses();
- if (elements.resultToggleBtn) {
- elements.resultToggleBtn.textContent = state.resultCollapsed ? "Show Result" : "Hide Result";
- }
- if (persist) {
- writeLocalStorage(RESULT_COLLAPSED_KEY, state.resultCollapsed ? "1" : "0");
- }
-}
-
-function syncResultEmptyState() {
- const isEmpty = !elements.output.textContent.trim();
- elements.shell.classList.toggle("shell--result-empty", isEmpty);
- elements.resultCard.classList.toggle("result-card--empty", isEmpty);
- elements.output.dataset.empty = isEmpty ? "true" : "false";
-}
-
-function setOutput(value) {
- const content = typeof value === "string" ? value : JSON.stringify(value, null, 2);
- elements.output.textContent = content;
- syncResultEmptyState();
-}
-
-function setActivePanel(panel) {
- state.activePanel = panel;
- for (const tab of elements.tabs) {
- tab.classList.toggle("active", tab.dataset.panel === panel);
- }
- for (const panelNode of elements.panels) {
- panelNode.classList.toggle("active", panelNode.id === `panel-${panel}`);
- }
-
- if (window.matchMedia("(max-width: 900px)").matches) {
- setNavCollapsed(true);
- }
-
- // If a confirmation dialog was left open, never carry it across panel switches.
- if (elements.tenantConfirmModal && !elements.tenantConfirmModal.hidden) {
- closeTenantConfirmModal();
- }
-
- if (panel === "tenants") {
- ensureTenantsLoaded().catch((error) => {
- setOutput(error.message);
- });
- }
-}
-
-function getApiKey() {
- return window.sessionStorage.getItem(SESSION_KEY) || state.connectionSettings.apiKey || "";
-}
-
-function updateConnectionHint() {
- const key = getApiKey();
- const identities = [
- state.connectionSettings.accountId ? `account=${state.connectionSettings.accountId}` : "",
- state.connectionSettings.userId ? `user=${state.connectionSettings.userId}` : "",
- state.connectionSettings.agentId ? `agent=${state.connectionSettings.agentId}` : "",
- ].filter(Boolean);
-
- const apiKeySummary = key ? `API key loaded in session (${key.length} chars).` : "No API key in session.";
- const identitySummary = identities.length
- ? ` Identity headers: ${identities.join(", ")}.`
- : " No account/user/agent id configured.";
- elements.connectionHint.textContent = `${apiKeySummary}${identitySummary}`;
-}
-
-function truncateText(value, maxLength = 4000) {
- const text = String(value || "");
- if (text.length <= maxLength) {
- return text;
- }
- return `${text.slice(0, maxLength)}\n... (truncated, ${text.length} chars total)`;
-}
-
-function isJsonLikeContentType(contentType) {
- const value = (contentType || "").toLowerCase();
- return value.includes("application/json") || value.includes("+json");
-}
-
-async function callConsole(path, options = {}) {
- const baseHeaders = {
- ...(options.headers || {}),
- };
-
- if (!(options.body instanceof FormData)) {
- baseHeaders["Content-Type"] = baseHeaders["Content-Type"] || "application/json";
- }
- const headers = buildRequestHeaders(baseHeaders, {
- apiKey: getApiKey(),
- ...state.connectionSettings,
- });
-
- let response;
- try {
- response = await fetch(`${API_BASE}${path}`, {
- ...options,
- headers,
- });
- } catch (error) {
- const message = error instanceof Error ? error.message : String(error);
- throw new Error(`NETWORK_ERROR: ${message}`);
- }
-
- const contentType = response.headers.get("content-type") || "";
- const status = response.status;
-
- let payload = null;
- let rawText = "";
-
- if (status === 204 || status === 205) {
- payload = { status: "ok", result: null };
- } else if (isJsonLikeContentType(contentType)) {
- const clone = response.clone();
- try {
- payload = await response.json();
- } catch (_error) {
- rawText = await clone.text().catch(() => "");
- payload = response.ok
- ? { status: "ok", result: rawText }
- : {
- status: "error",
- error: {
- code: "BAD_RESPONSE",
- message: "Invalid JSON response from console",
- detail: truncateText(rawText, 2000),
- },
- };
- }
- } else {
- rawText = await response.text().catch(() => "");
- payload = response.ok
- ? { status: "ok", result: rawText }
- : {
- status: "error",
- error: {
- code: "HTTP_ERROR",
- message: rawText ? truncateText(rawText, 2000) : `Request failed with status ${status}`,
- },
- };
- }
-
- if (!response.ok) {
- const code = payload?.error?.code || "ERROR";
- const message =
- payload?.error?.message || `Request failed with status ${response.status} ${response.statusText}`;
- const missingApiKey =
- code === "UNAUTHENTICATED" && String(message).toLowerCase().includes("missing api key");
- const hint = missingApiKey ? " Please go to Settings and set X-API-Key." : "";
- throw new Error(`${code}: ${message}${hint}`);
- }
-
- return payload;
-}
-
-function normalizeDirUri(uri) {
- const value = (uri || "").trim();
- if (!value) {
- return "viking://";
- }
- if (value === "viking://") {
- return value;
- }
- return value.endsWith("/") ? value : `${value}/`;
-}
-
-function parentUri(uri) {
- const normalized = normalizeDirUri(uri);
- if (normalized === "viking://") {
- return normalized;
- }
-
- const scheme = "viking://";
- if (!normalized.startsWith(scheme)) {
- return scheme;
- }
-
- const withoutTrailingSlash = normalized.slice(0, -1);
- const body = withoutTrailingSlash.slice(scheme.length);
- if (!body.includes("/")) {
- return scheme;
- }
-
- const prefix = body.slice(0, body.lastIndexOf("/") + 1);
- return `${scheme}${prefix}`;
-}
-
-function joinUri(baseUri, child) {
- const raw = String(child || "").trim();
- if (!raw) {
- return normalizeDirUri(baseUri);
- }
- if (raw.startsWith("viking://")) {
- return raw;
- }
-
- const normalizedBase = normalizeDirUri(baseUri);
- const cleanedChild = raw.replace(/^\//, "");
- return `${normalizedBase}${cleanedChild}`;
-}
-
-function pickFirstNonEmpty(candidates) {
- for (const candidate of candidates) {
- if (candidate !== undefined && candidate !== null && String(candidate).trim() !== "") {
- return candidate;
- }
- }
- return null;
-}
-
-function normalizeFsEntries(result, currentUri) {
- const toEntry = (item) => {
- if (typeof item === "string") {
- const rawName = item.trim();
- const isDir = rawName.endsWith("/");
- const resolvedUri = joinUri(currentUri, rawName);
- return {
- uri: isDir ? normalizeDirUri(resolvedUri) : resolvedUri,
- size: null,
- isDir,
- modTime: null,
- abstract: "",
- };
- }
-
- if (item && typeof item === "object") {
- const baseLabel =
- item.name || item.path || item.relative_path || item.uri || item.id || JSON.stringify(item);
- const isDir =
- Boolean(item.is_dir) ||
- Boolean(item.isDir) ||
- item.type === "dir" ||
- item.type === "directory" ||
- item.kind === "dir" ||
- String(baseLabel).endsWith("/");
- const rawUri = item.uri || item.path || item.relative_path || baseLabel;
- const resolvedUri = joinUri(currentUri, rawUri);
- const size = pickFirstNonEmpty([
- item.size,
- item.size_bytes,
- item.content_length,
- item.contentLength,
- item.bytes,
- ]);
- const modTime = pickFirstNonEmpty([
- item.modTime,
- item.mod_time,
- item.mtime,
- item.modified_at,
- item.modifiedAt,
- item.updated_at,
- item.updatedAt,
- item.last_modified,
- item.lastModified,
- item.timestamp,
- item.time,
- ]);
- const abstract = pickFirstNonEmpty([
- item.abstract,
- item.summary,
- item.description,
- item.desc,
- ]);
-
- return {
- uri: isDir ? normalizeDirUri(resolvedUri) : resolvedUri,
- size,
- isDir,
- modTime,
- abstract: abstract === null ? "" : String(abstract),
- };
- }
-
- return {
- uri: joinUri(currentUri, String(item)),
- size: null,
- isDir: false,
- modTime: null,
- abstract: "",
- };
- };
-
- if (Array.isArray(result)) {
- return result.map(toEntry);
- }
-
- if (result && typeof result === "object") {
- const candidates = [result.entries, result.items, result.children, result.results];
- for (const candidate of candidates) {
- if (Array.isArray(candidate)) {
- return candidate.map(toEntry);
- }
- }
- }
-
- if (typeof result === "string") {
- return result
- .split("\n")
- .map((line) => line.trim())
- .filter(Boolean)
- .map(toEntry);
- }
-
- return [];
-}
-
-function normalizeSortString(value) {
- if (value === null || value === undefined) {
- return "";
- }
- return String(value).toLowerCase();
-}
-
-function toSortableNumber(value) {
- if (typeof value === "number" && Number.isFinite(value)) {
- return value;
- }
- if (typeof value === "string") {
- const parsed = Number.parseFloat(value);
- if (Number.isFinite(parsed)) {
- return parsed;
- }
- }
- return null;
-}
-
-function toSortableTime(value) {
- if (!value) {
- return null;
- }
-
- const date = new Date(value);
- if (!Number.isNaN(date.getTime())) {
- return date.getTime();
- }
- return toSortableNumber(value);
-}
-
-function compareNullable(left, right, compareFn) {
- const leftMissing = left === null || left === undefined || left === "";
- const rightMissing = right === null || right === undefined || right === "";
- if (leftMissing && rightMissing) {
- return 0;
- }
- if (leftMissing) {
- return 1;
- }
- if (rightMissing) {
- return -1;
- }
- return compareFn(left, right);
-}
-
-function compareFsEntries(left, right, field) {
- switch (field) {
- case "size":
- return compareNullable(left.size, right.size, (a, b) => {
- const leftNum = toSortableNumber(a);
- const rightNum = toSortableNumber(b);
- if (leftNum !== null && rightNum !== null) {
- return leftNum - rightNum;
- }
- return normalizeSortString(a).localeCompare(normalizeSortString(b));
- });
- case "isDir":
- return Number(left.isDir) - Number(right.isDir);
- case "modTime":
- return compareNullable(left.modTime, right.modTime, (a, b) => {
- const leftTime = toSortableTime(a);
- const rightTime = toSortableTime(b);
- if (leftTime !== null && rightTime !== null) {
- return leftTime - rightTime;
- }
- return normalizeSortString(a).localeCompare(normalizeSortString(b));
- });
- case "abstract":
- return compareNullable(left.abstract, right.abstract, (a, b) =>
- normalizeSortString(a).localeCompare(normalizeSortString(b))
- );
- case "uri":
- default:
- return normalizeSortString(left.uri).localeCompare(normalizeSortString(right.uri));
- }
-}
-
-function sortFilesystemEntries(entries) {
- const sorted = [...entries].sort((left, right) =>
- compareFsEntries(left, right, state.fsSortField)
- );
- if (state.fsSortDirection === "desc") {
- sorted.reverse();
- }
- return sorted;
-}
-
-function updateFilesystemSortHeaders() {
- for (const button of elements.fsSortHeaders) {
- const field = button.dataset.fsSort || "";
- const isActive = field === state.fsSortField;
- button.classList.toggle("active", isActive);
- button.setAttribute(
- "aria-sort",
- isActive ? (state.fsSortDirection === "asc" ? "ascending" : "descending") : "none"
- );
- const suffix = !isActive ? "" : state.fsSortDirection === "asc" ? " ↑" : " ↓";
- button.textContent = `${field}${suffix}`;
- }
-}
-
-function bindFilesystemSort() {
- for (const button of elements.fsSortHeaders) {
- button.addEventListener("click", async () => {
- const field = button.dataset.fsSort;
- if (!field) {
- return;
- }
-
- if (state.fsSortField === field) {
- state.fsSortDirection = state.fsSortDirection === "asc" ? "desc" : "asc";
- } else {
- state.fsSortField = field;
- state.fsSortDirection = "asc";
- }
-
- updateFilesystemSortHeaders();
-
- try {
- await loadFilesystem(state.fsCurrentUri);
- } catch (error) {
- setOutput(error.message);
- }
- });
- }
-}
-
-function initFsColumnResize() {
- if (!elements.fsTable) {
- return;
- }
-
- const headers = elements.fsTable.querySelectorAll("thead th");
- for (const header of headers) {
- if (header.dataset.resizable === "false") {
- continue;
- }
- if (header.querySelector(".fs-col-resizer")) {
- continue;
- }
-
- const handle = document.createElement("div");
- handle.className = "fs-col-resizer";
- handle.setAttribute("role", "separator");
- handle.setAttribute("aria-orientation", "vertical");
- handle.setAttribute("aria-label", "Resize column");
- header.appendChild(handle);
-
- handle.addEventListener("pointerdown", (event) => {
- event.preventDefault();
- event.stopPropagation();
- document.body.classList.add("dragging-fs-column");
-
- const startX = event.clientX;
- const startWidth = header.getBoundingClientRect().width;
- const minWidth = Number.parseFloat(header.dataset.minWidth || "90");
-
- handle.setPointerCapture(event.pointerId);
-
- const onMove = (moveEvent) => {
- const nextWidth = clamp(startWidth + (moveEvent.clientX - startX), minWidth, 1200);
- header.style.width = `${nextWidth}px`;
- header.style.minWidth = `${nextWidth}px`;
- };
-
- const onUp = () => {
- handle.removeEventListener("pointermove", onMove);
- handle.removeEventListener("pointerup", onUp);
- handle.removeEventListener("pointercancel", onUp);
- document.body.classList.remove("dragging-fs-column");
- handle.releasePointerCapture(event.pointerId);
- };
-
- handle.addEventListener("pointermove", onMove);
- handle.addEventListener("pointerup", onUp);
- handle.addEventListener("pointercancel", onUp);
- });
- }
-}
-
-function normalizeReadContent(result) {
- if (typeof result === "string") {
- return result;
- }
- if (Array.isArray(result)) {
- return result.map((item) => String(item)).join("\n");
- }
- if (result && typeof result === "object") {
- const content = pickFirstNonEmpty([
- result.content,
- result.text,
- result.body,
- result.value,
- result.data,
- ]);
- if (content !== null) {
- return typeof content === "string" ? content : JSON.stringify(content, null, 2);
- }
- }
- return JSON.stringify(result, null, 2);
-}
-
-async function readFilesystemFile(entry) {
- const uri = String(entry?.uri || "").replace(/\/$/, "");
- if (!uri) {
- throw new Error("Invalid file uri.");
- }
-
- setOutput(`Reading ${uri} ...`);
- const payload = await callConsole(
- `/ov/content/read?uri=${encodeURIComponent(uri)}&offset=0&limit=-1`,
- { method: "GET" }
- );
- const content = normalizeReadContent(payload.result);
- setOutput(content && content.trim() ? content : "(empty file)");
-}
-
-async function statFilesystemResource(entry) {
- let uri = String(entry?.uri || "").trim();
- if (!uri) {
- throw new Error("Invalid resource uri.");
- }
- if (uri !== "viking://") {
- uri = uri.replace(/\/$/, "");
- }
-
- const payload = await callConsole(`/ov/fs/stat?uri=${encodeURIComponent(uri)}`, { method: "GET" });
- setOutput(payload);
-}
-
-function renderFilesystemEntries(target, rows, onOpen, onOpenContent) {
- target.innerHTML = "";
-
- if (!rows.length) {
- const tr = document.createElement("tr");
- const td = document.createElement("td");
- td.colSpan = 6;
- td.className = "fs-empty";
- td.textContent = "No data";
- tr.appendChild(td);
- target.appendChild(tr);
- return;
- }
-
- for (const row of rows) {
- const tr = document.createElement("tr");
-
- const actionCell = document.createElement("td");
- actionCell.className = "fs-col-action";
- const openBtn = document.createElement("button");
- openBtn.type = "button";
- openBtn.className = "fs-open-btn";
- openBtn.title = "Show stat info";
- openBtn.setAttribute("aria-label", `Show stat info for ${row.uri}`);
- openBtn.textContent = "ⓘ";
- openBtn.addEventListener("click", async (event) => {
- event.preventDefault();
- event.stopPropagation();
- try {
- await onOpenContent(row);
- } catch (error) {
- setOutput(error.message);
- }
- });
- actionCell.appendChild(openBtn);
- tr.appendChild(actionCell);
-
- const uriCell = document.createElement("td");
- uriCell.className = "fs-col-uri";
- const uriBtn = document.createElement("button");
- uriBtn.type = "button";
- uriBtn.className = "fs-uri-btn";
- uriBtn.textContent = row.uri || "-";
- uriBtn.addEventListener("click", () => onOpen(row));
- uriCell.appendChild(uriBtn);
- tr.appendChild(uriCell);
-
- const sizeCell = document.createElement("td");
- sizeCell.className = "fs-col-size";
- sizeCell.textContent = row.size === null || row.size === undefined || row.size === "" ? "-" : String(row.size);
- tr.appendChild(sizeCell);
-
- const dirCell = document.createElement("td");
- dirCell.className = "fs-col-dir";
- dirCell.textContent = row.isDir ? "true" : "false";
- tr.appendChild(dirCell);
-
- const modTimeCell = document.createElement("td");
- modTimeCell.className = "fs-col-mod-time";
- modTimeCell.textContent =
- row.modTime === null || row.modTime === undefined || row.modTime === ""
- ? "-"
- : String(row.modTime);
- tr.appendChild(modTimeCell);
-
- const abstractCell = document.createElement("td");
- abstractCell.className = "fs-col-abstract";
- abstractCell.textContent = row.abstract || "-";
- tr.appendChild(abstractCell);
-
- target.appendChild(tr);
- }
-}
-
-function isRecord(value) {
- return value !== null && typeof value === "object" && !Array.isArray(value);
-}
-
-function extractDeepestObjectArray(value) {
- const best = { depth: -1, rows: null };
-
- const visit = (current, depth) => {
- if (Array.isArray(current)) {
- if (current.length > 0 && current.every((item) => isRecord(item))) {
- if (depth > best.depth) {
- best.depth = depth;
- best.rows = current;
- }
- }
-
- for (const item of current) {
- visit(item, depth + 1);
- }
- return;
- }
-
- if (!isRecord(current)) {
- return;
- }
-
- for (const nested of Object.values(current)) {
- visit(nested, depth + 1);
- }
- };
-
- visit(value, 0);
- return best.rows;
-}
-
-function normalizeFindRows(result) {
- if (Array.isArray(result)) {
- return result.map((item) => (isRecord(item) ? item : { value: item }));
- }
-
- if (isRecord(result)) {
- const typedBucketKeys = ["memories", "resources", "skills"];
- const hasTypedBuckets = typedBucketKeys.some((key) => Array.isArray(result[key]));
- if (hasTypedBuckets) {
- const typedRows = [];
- for (const key of typedBucketKeys) {
- const rows = Array.isArray(result[key]) ? result[key] : [];
- for (const row of rows) {
- const normalized = isRecord(row) ? row : { value: row };
- typedRows.push({
- ...normalized,
- context_type:
- normalized.context_type || (key === "memories" ? "memory" : key.slice(0, -1)),
- });
- }
- }
- return typedRows;
- }
-
- const topLevelArrays = [
- result.results,
- result.items,
- result.matches,
- result.hits,
- result.rows,
- result.entries,
- result.data,
- ];
- for (const rows of topLevelArrays) {
- if (Array.isArray(rows)) {
- return rows.map((item) => (isRecord(item) ? item : { value: item }));
- }
- }
-
- const deepestRows = extractDeepestObjectArray(result);
- if (deepestRows) {
- return deepestRows;
- }
-
- return [result];
- }
-
- if (result === null || result === undefined) {
- return [];
- }
-
- return [{ value: result }];
-}
-
-function collectFindColumns(rows) {
- const columns = [];
- const seen = new Set();
-
- for (const row of rows) {
- if (!isRecord(row)) {
- continue;
- }
-
- for (const key of Object.keys(row)) {
- if (!seen.has(key)) {
- seen.add(key);
- columns.push(key);
- }
- }
- }
-
- return columns;
-}
-
-function formatFindCellValue(value) {
- if (value === null || value === undefined || value === "") {
- return "-";
- }
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
- return String(value);
- }
- return JSON.stringify(value);
-}
-
-function renderFindCellContent(td, column, value) {
- const expandableColumns = new Set(["abstract", "overview"]);
- const formattedValue = formatFindCellValue(value);
- if (!expandableColumns.has(column) || formattedValue === "-") {
- td.textContent = formattedValue;
- return;
- }
-
- td.classList.add("find-cell-expandable");
- td.classList.add("find-col-abstract");
-
- const wrapper = document.createElement("div");
- wrapper.className = "find-cell-content";
-
- const text = document.createElement("span");
- text.className = "find-cell-text";
- text.textContent = formattedValue;
-
- const toggle = document.createElement("button");
- toggle.type = "button";
- toggle.className = "find-cell-expand-btn";
- toggle.textContent = "Expand";
-
- let expanded = false;
- toggle.addEventListener("click", () => {
- expanded = !expanded;
- text.classList.toggle("expanded", expanded);
- wrapper.classList.toggle("expanded", expanded);
- toggle.textContent = expanded ? "Collapse" : "Expand";
- toggle.setAttribute("aria-expanded", expanded ? "true" : "false");
- });
- toggle.setAttribute("aria-expanded", "false");
-
- wrapper.appendChild(text);
- wrapper.appendChild(toggle);
- td.appendChild(wrapper);
-}
-
-function toFindComparable(value) {
- if (value === null || value === undefined || value === "") {
- return { missing: true, type: "missing", value: "" };
- }
-
- if (typeof value === "number" && Number.isFinite(value)) {
- return { missing: false, type: "number", value };
- }
-
- if (typeof value === "boolean") {
- return { missing: false, type: "number", value: Number(value) };
- }
-
- if (typeof value === "string") {
- const trimmed = value.trim();
- const asNumber = Number.parseFloat(trimmed);
- if (trimmed !== "" && Number.isFinite(asNumber)) {
- return { missing: false, type: "number", value: asNumber };
- }
-
- const asDate = new Date(trimmed);
- if (!Number.isNaN(asDate.getTime())) {
- return { missing: false, type: "date", value: asDate.getTime() };
- }
-
- return { missing: false, type: "string", value: trimmed.toLowerCase() };
- }
-
- return { missing: false, type: "string", value: JSON.stringify(value).toLowerCase() };
-}
-
-function compareFindValues(left, right) {
- const leftValue = toFindComparable(left);
- const rightValue = toFindComparable(right);
-
- if (leftValue.missing && rightValue.missing) {
- return 0;
- }
- if (leftValue.missing) {
- return 1;
- }
- if (rightValue.missing) {
- return -1;
- }
-
- if (leftValue.type === rightValue.type && (leftValue.type === "number" || leftValue.type === "date")) {
- return leftValue.value - rightValue.value;
- }
-
- return String(leftValue.value).localeCompare(String(rightValue.value));
-}
-
-function sortFindRows(rows, column, direction) {
- const sorted = [...rows].sort((left, right) => {
- const leftCell = isRecord(left) ? left[column] : undefined;
- const rightCell = isRecord(right) ? right[column] : undefined;
- return compareFindValues(leftCell, rightCell);
- });
-
- if (direction === "desc") {
- sorted.reverse();
- }
- return sorted;
-}
-
-function renderFindTable(rows) {
- state.findRows = rows;
- elements.findResultsHead.innerHTML = "";
- elements.findResultsBody.innerHTML = "";
-
- const columns = collectFindColumns(rows);
- if (!columns.length) {
- columns.push("value");
- }
-
- if (!state.findSortField || !columns.includes(state.findSortField)) {
- state.findSortField = columns[0];
- state.findSortDirection = "asc";
- }
-
- const headerRow = document.createElement("tr");
- for (const column of columns) {
- const th = document.createElement("th");
- th.scope = "col";
-
- const sortBtn = document.createElement("button");
- sortBtn.type = "button";
- sortBtn.className = "find-sort-btn";
- sortBtn.dataset.findSort = column;
-
- const isActive = state.findSortField === column;
- const sortLabel = isActive ? (state.findSortDirection === "asc" ? " ↑" : " ↓") : "";
- sortBtn.textContent = `${column}${sortLabel}`;
- sortBtn.setAttribute(
- "aria-sort",
- isActive ? (state.findSortDirection === "asc" ? "ascending" : "descending") : "none"
- );
-
- sortBtn.addEventListener("click", () => {
- if (state.findSortField === column) {
- state.findSortDirection = state.findSortDirection === "asc" ? "desc" : "asc";
- } else {
- state.findSortField = column;
- state.findSortDirection = "asc";
- }
- renderFindTable(state.findRows);
- });
-
- th.appendChild(sortBtn);
- headerRow.appendChild(th);
- }
- elements.findResultsHead.appendChild(headerRow);
-
- if (!rows.length) {
- const emptyRow = document.createElement("tr");
- const emptyCell = document.createElement("td");
- emptyCell.colSpan = columns.length;
- emptyCell.className = "find-empty";
- emptyCell.textContent = "No data";
- emptyRow.appendChild(emptyCell);
- elements.findResultsBody.appendChild(emptyRow);
- return;
- }
-
- const sortedRows = sortFindRows(rows, state.findSortField, state.findSortDirection);
- for (const row of sortedRows) {
- const tr = document.createElement("tr");
- for (const column of columns) {
- const td = document.createElement("td");
- const cellValue = isRecord(row) ? row[column] : undefined;
- renderFindCellContent(td, column, cellValue);
- tr.appendChild(td);
- }
- elements.findResultsBody.appendChild(tr);
- }
-}
-
-function renderList(target, rows, onClick) {
- target.innerHTML = "";
- if (!rows.length) {
- const empty = document.createElement("li");
- empty.innerHTML = '<div class="row-item">No data</div>';
- target.appendChild(empty);
- return;
- }
-
- for (const row of rows) {
- const li = document.createElement("li");
- if (onClick) {
- const button = document.createElement("button");
- button.type = "button";
- button.textContent = row.label;
- button.addEventListener("click", () => onClick(row));
- li.appendChild(button);
- } else {
- const div = document.createElement("div");
- div.className = "row-item";
- div.textContent = row.label;
- li.appendChild(div);
- }
- target.appendChild(li);
- }
-}
-
-function clamp(value, min, max) {
- return Math.max(min, Math.min(max, value));
-}
-
-function syncWriteControls() {
- const writeButtons = document.querySelectorAll("[data-tenant-write]");
- for (const button of writeButtons) {
- button.disabled = !state.writeEnabled;
- }
-}
-
-function initResizablePanes() {
- const rootStyle = document.documentElement.style;
-
- if (elements.sidebarResizer && elements.sidebar) {
- elements.sidebarResizer.addEventListener("pointerdown", (event) => {
- if (window.matchMedia("(max-width: 900px)").matches) {
- return;
- }
- event.preventDefault();
- document.body.classList.add("dragging-sidebar");
- elements.sidebarResizer.setPointerCapture(event.pointerId);
- const startX = event.clientX;
- const startWidth = elements.sidebar.getBoundingClientRect().width;
-
- const onMove = (moveEvent) => {
- const nextWidth = clamp(
- startWidth + (moveEvent.clientX - startX),
- layoutLimits.minSidebar,
- layoutLimits.maxSidebar
- );
- rootStyle.setProperty("--sidebar-width", `${nextWidth}px`);
- };
-
- const onUp = () => {
- elements.sidebarResizer.removeEventListener("pointermove", onMove);
- elements.sidebarResizer.removeEventListener("pointerup", onUp);
- elements.sidebarResizer.removeEventListener("pointercancel", onUp);
- document.body.classList.remove("dragging-sidebar");
- elements.sidebarResizer.releasePointerCapture(event.pointerId);
- };
-
- elements.sidebarResizer.addEventListener("pointermove", onMove);
- elements.sidebarResizer.addEventListener("pointerup", onUp);
- elements.sidebarResizer.addEventListener("pointercancel", onUp);
- });
- }
-
- if (elements.outputResizer && elements.resultCard) {
- elements.outputResizer.addEventListener("pointerdown", (event) => {
- if (window.matchMedia("(max-width: 900px)").matches) {
- return;
- }
- event.preventDefault();
- document.body.classList.add("dragging-output");
- elements.outputResizer.setPointerCapture(event.pointerId);
- const startY = event.clientY;
- const startHeight =
- elements.panelStack?.getBoundingClientRect().height || layoutLimits.minPanel;
-
- const onMove = (moveEvent) => {
- const contentHeight = elements.content?.getBoundingClientRect().height || window.innerHeight;
- const resizerHeight = elements.outputResizer.getBoundingClientRect().height || 8;
- const rowGap = Number.parseFloat(
- window.getComputedStyle(elements.content || document.body).rowGap || "0"
- );
- const totalGap = Number.isFinite(rowGap) ? rowGap * 2 : 0;
- const availableHeight = Math.max(
- layoutLimits.minPanel + layoutLimits.minResult,
- contentHeight - resizerHeight - totalGap
- );
- const maxPanel = Math.max(layoutLimits.minPanel, availableHeight - layoutLimits.minResult);
- const nextPanelHeight = clamp(
- startHeight + (moveEvent.clientY - startY),
- layoutLimits.minPanel,
- maxPanel
- );
- rootStyle.setProperty("--panel-height", `${nextPanelHeight}px`);
- };
-
- const onUp = () => {
- elements.outputResizer.removeEventListener("pointermove", onMove);
- elements.outputResizer.removeEventListener("pointerup", onUp);
- elements.outputResizer.removeEventListener("pointercancel", onUp);
- document.body.classList.remove("dragging-output");
- elements.outputResizer.releasePointerCapture(event.pointerId);
- };
-
- elements.outputResizer.addEventListener("pointermove", onMove);
- elements.outputResizer.addEventListener("pointerup", onUp);
- elements.outputResizer.addEventListener("pointercancel", onUp);
- });
- }
-}
-
-function buildFsTreeItem(entry, depth) {
- const uriStr = entry.uri || "";
- const trimmed = uriStr.replace(/\/$/, "");
- const lastSlash = trimmed.lastIndexOf("/");
- const displayName = lastSlash >= 0 ? trimmed.slice(lastSlash + 1) || trimmed : trimmed;
-
- const item = document.createElement("div");
- item.className = `fs-tree-item${entry.isDir ? " fs-tree-item--dir" : ""}`;
- item.style.paddingLeft = `${10 + depth * 16}px`;
-
- // ⓘ button — leftmost, matches list view action column
- const infoBtn = document.createElement("button");
- infoBtn.type = "button";
- infoBtn.className = "fs-tree-info-btn";
- infoBtn.textContent = "ⓘ";
- infoBtn.title = "Show stat info";
- infoBtn.setAttribute("aria-label", `Show stat info for ${uriStr}`);
- infoBtn.addEventListener("click", async (event) => {
- event.stopPropagation();
- try {
- await statFilesystemResource(entry);
- } catch (error) {
- setOutput(error.message);
- }
- });
- item.appendChild(infoBtn);
-
- // collapse/expand arrow (dirs only; files get a fixed-width placeholder)
- const toggle = document.createElement("span");
- toggle.className = "fs-tree-toggle";
- toggle.setAttribute("aria-hidden", "true");
- toggle.textContent = entry.isDir ? (state.fsTreeExpanded.has(entry.uri) ? "▼" : "▶") : "";
- item.appendChild(toggle);
-
- const name = document.createElement("span");
- name.className = "fs-tree-name";
- name.textContent = displayName;
- name.title = uriStr;
- item.appendChild(name);
-
- item.addEventListener("click", async () => {
- if (entry.isDir) {
- if (state.fsTreeExpanded.has(entry.uri)) {
- state.fsTreeExpanded.delete(entry.uri);
- await renderFsTree();
- } else if (state.fsTreeData[entry.uri]) {
- state.fsTreeExpanded.add(entry.uri);
- await renderFsTree();
- } else {
- try {
- const payload = await callConsole(
- `/ov/fs/ls?uri=${encodeURIComponent(entry.uri)}&show_all_hidden=true`,
- { method: "GET" }
- );
- const children = normalizeFsEntries(payload.result, entry.uri);
- children.sort((a, b) => {
- if (a.isDir !== b.isDir) {
- return a.isDir ? -1 : 1;
- }
- return (a.uri || "").localeCompare(b.uri || "");
- });
- state.fsTreeData[entry.uri] = children;
- state.fsTreeExpanded.add(entry.uri);
- await renderFsTree();
- } catch (error) {
- setOutput(error.message);
- }
- }
- } else {
- try {
- await readFilesystemFile(entry);
- } catch (error) {
- setOutput(error.message);
- }
- }
- });
-
- return item;
-}
-
-async function renderFsTreeLevel(container, uri, depth) {
- const entries = state.fsTreeData[uri] || [];
- for (const entry of entries) {
- const item = buildFsTreeItem(entry, depth);
- container.appendChild(item);
- if (entry.isDir && state.fsTreeExpanded.has(entry.uri)) {
- const childContainer = document.createElement("div");
- childContainer.className = "fs-tree-children";
- container.appendChild(childContainer);
- await renderFsTreeLevel(childContainer, entry.uri, depth + 1);
- }
- }
-}
-
-async function renderFsTree() {
- elements.fsTree.innerHTML = "";
- await renderFsTreeLevel(elements.fsTree, state.fsCurrentUri, 0);
-}
-
-function setFsViewMode(mode) {
- state.fsViewMode = mode;
- elements.fsModeListBtn.classList.toggle("active", mode === "list");
- elements.fsModeTreeBtn.classList.toggle("active", mode === "tree");
- elements.fsModeListBtn.setAttribute("aria-pressed", String(mode === "list"));
- elements.fsModeTreeBtn.setAttribute("aria-pressed", String(mode === "tree"));
- elements.fsTableWrap.hidden = mode === "tree";
- elements.fsTree.hidden = mode === "list";
-}
-
-async function loadFilesystem(uri, { pushHistory = false } = {}) {
- const targetUri = normalizeDirUri(uri);
- const payload = await callConsole(
- `/ov/fs/ls?uri=${encodeURIComponent(targetUri)}&show_all_hidden=true`,
- { method: "GET" }
- );
-
- if (pushHistory && state.fsCurrentUri !== targetUri) {
- state.fsHistory.push(state.fsCurrentUri);
- }
-
- state.fsCurrentUri = targetUri;
- elements.fsCurrentUri.value = targetUri;
-
- const rawEntries = normalizeFsEntries(payload.result, targetUri);
-
- if (state.fsViewMode === "list") {
- const entries = sortFilesystemEntries(rawEntries);
- renderFilesystemEntries(
- elements.fsEntries,
- entries,
- async (entry) => {
- if (entry.isDir) {
- try {
- await loadFilesystem(entry.uri, { pushHistory: true });
- } catch (error) {
- setOutput(error.message);
- }
- return;
- }
- try {
- await readFilesystemFile(entry);
- } catch (error) {
- setOutput(error.message);
- }
- },
- async (entry) => {
- await statFilesystemResource(entry);
- }
- );
- } else {
- rawEntries.sort((a, b) => {
- if (a.isDir !== b.isDir) {
- return a.isDir ? -1 : 1;
- }
- return (a.uri || "").localeCompare(b.uri || "");
- });
- state.fsTreeData[targetUri] = rawEntries;
- await renderFsTree();
- }
-
-}
-
-async function refreshCapabilities() {
- try {
- const payload = await callConsole("/runtime/capabilities", { method: "GET" });
- state.writeEnabled = Boolean(payload.result?.write_enabled);
- elements.writeBadge.textContent = state.writeEnabled ? "Write Enabled" : "Readonly";
- elements.writeBadge.classList.toggle("write", state.writeEnabled);
- elements.addResourceSubmitBtn.disabled = !state.writeEnabled;
- syncWriteControls();
- renderAccountsTable();
- renderUsersTable();
- } catch (error) {
- setOutput(`Failed to load capabilities: ${error.message}`);
- }
-}
-
-function bindShellControls() {
- const preferDark = window.matchMedia("(prefers-color-scheme: dark)");
-
- if (elements.navToggleBtn) {
- elements.navToggleBtn.addEventListener("click", () => {
- setNavCollapsed(!state.navCollapsed);
- });
- }
-
- if (elements.resultToggleBtn) {
- elements.resultToggleBtn.addEventListener("click", () => {
- setResultCollapsed(!state.resultCollapsed);
- });
- }
-
- if (elements.clearOutputBtn) {
- elements.clearOutputBtn.addEventListener("click", () => {
- setOutput("");
- });
- }
-
- for (const button of elements.themeButtons) {
- button.addEventListener("click", () => {
- applyThemeMode(button.dataset.themeMode || "dark");
- });
- }
-
- if (elements.content) {
- elements.content.addEventListener("click", () => {
- if (window.matchMedia("(max-width: 900px)").matches && !state.navCollapsed) {
- setNavCollapsed(true);
- }
- });
- }
-
- const onThemeChange = () => {
- if (state.themeMode === "system") {
- applyThemeMode("system", { persist: false });
- }
- };
- if (typeof preferDark.addEventListener === "function") {
- preferDark.addEventListener("change", onThemeChange);
- } else if (typeof preferDark.addListener === "function") {
- preferDark.addListener(onThemeChange);
- }
-}
-
-function initShellState() {
- const storedTheme = readLocalStorage(THEME_MODE_KEY);
- const themeMode = storedTheme === "light" || storedTheme === "system" ? storedTheme : "dark";
- applyThemeMode(themeMode, { persist: false });
-
- const storedNav = readLocalStorage(NAV_COLLAPSED_KEY);
- const defaultNavCollapsed =
- storedNav === "1" || (storedNav === null && window.matchMedia("(max-width: 900px)").matches);
- setNavCollapsed(defaultNavCollapsed, { persist: false });
-
- const storedResult = readLocalStorage(RESULT_COLLAPSED_KEY);
- setResultCollapsed(storedResult === null ? false : storedResult === "1", { persist: false });
-}
-
-function bindTabs() {
- for (const tab of elements.tabs) {
- tab.addEventListener("click", () => {
- const panel = tab.dataset.panel;
- if (!panel) {
- return;
- }
- setActivePanel(panel);
- });
- }
-}
-
-function bindConnection() {
- const saveConnection = () => {
- const nextApiKey = elements.apiKeyInput.value.trim() || state.connectionSettings.apiKey;
- state.connectionSettings = saveConsoleSettings(window.localStorage, {
- apiKey: nextApiKey,
- accountId: elements.accountInput.value,
- userId: elements.userInput.value,
- agentId: elements.agentIdInput.value,
- });
-
- elements.accountInput.value = state.connectionSettings.accountId;
- elements.userInput.value = state.connectionSettings.userId;
- elements.agentIdInput.value = state.connectionSettings.agentId;
-
- if (state.connectionSettings.apiKey) {
- window.sessionStorage.setItem(SESSION_KEY, state.connectionSettings.apiKey);
- elements.apiKeyInput.value = "";
- } else {
- window.sessionStorage.removeItem(SESSION_KEY);
- }
-
- updateConnectionHint();
- setOutput(nextApiKey ? "Connection settings saved." : "Identity settings saved. API key unchanged.");
- return true;
- };
-
- elements.saveKeyBtn.addEventListener("click", () => {
- saveConnection();
- });
-
- elements.apiKeyInput.addEventListener("keydown", (event) => {
- if (event.key !== "Enter") {
- return;
- }
- event.preventDefault();
- saveConnection();
- });
-
- elements.clearKeyBtn.addEventListener("click", () => {
- window.sessionStorage.removeItem(SESSION_KEY);
- state.connectionSettings = saveConsoleSettings(window.localStorage, {});
- elements.accountInput.value = "";
- elements.userInput.value = "";
- elements.agentIdInput.value = "";
- elements.apiKeyInput.value = "";
- updateConnectionHint();
- setOutput("Connection settings cleared from browser storage.");
- });
-
- if (elements.getOtpBtn) {
- elements.getOtpBtn.addEventListener("click", async () => {
- if (!getApiKey()) {
- setOutput("Save an API key first — OTP issuance requires authentication.");
- return;
- }
- elements.getOtpBtn.disabled = true;
- const originalLabel = elements.getOtpBtn.textContent;
- elements.getOtpBtn.textContent = "Generating…";
- try {
- const payload = await callConsole("/ov/auth/otp", {
- method: "POST",
- body: JSON.stringify({}),
- });
- const result = payload && payload.result ? payload.result : payload;
- const otp = result && (result.otp || result.code);
- if (!otp) {
- throw new Error("Server did not return an OTP");
- }
- elements.otpValue.textContent = otp;
- const ttl = result.ttl_seconds || 300;
- const expiresAt = result.expires_at
- ? new Date(result.expires_at * 1000).toLocaleTimeString()
- : null;
- elements.otpExpiry.textContent = expiresAt
- ? `Expires at ${expiresAt} (${ttl}s). One-time use.`
- : `Expires in ${ttl}s. One-time use.`;
- elements.otpBox.hidden = false;
- } catch (error) {
- const message = error instanceof Error ? error.message : String(error);
- setOutput(`Failed to generate OTP: ${message}`);
- } finally {
- elements.getOtpBtn.disabled = false;
- elements.getOtpBtn.textContent = originalLabel;
- }
- });
- }
-
- if (elements.otpCopyBtn) {
- elements.otpCopyBtn.addEventListener("click", async () => {
- const otp = elements.otpValue.textContent.trim();
- if (!otp) {
- return;
- }
- try {
- await navigator.clipboard.writeText(otp);
- const originalLabel = elements.otpCopyBtn.textContent;
- elements.otpCopyBtn.textContent = "Copied";
- setTimeout(() => {
- elements.otpCopyBtn.textContent = originalLabel;
- }, 1500);
- } catch (_error) {
- setOutput("Could not copy to clipboard — long-press the code to copy manually.");
- }
- });
- }
-
- // OAuth verification (device-flow style: user reads code from the MCP
- // client's authorize page and pastes it here).
- async function submitOAuthVerify(decision) {
- if (!getApiKey()) {
- elements.oauthVerifyHint.textContent =
- "Save an API key first — verification requires authentication.";
- return;
- }
- const code = (elements.oauthVerifyInput.value || "").trim().toUpperCase();
- if (!code) {
- elements.oauthVerifyHint.textContent = "Enter the 6-character code shown on the authorize page.";
- return;
- }
- elements.oauthVerifyBtn.disabled = true;
- elements.oauthDenyBtn.disabled = true;
- elements.oauthVerifyHint.textContent = decision === "deny" ? "Denying…" : "Authorizing…";
- try {
- const payload = await callConsole("/ov/auth/oauth-verify", {
- method: "POST",
- body: JSON.stringify({ code, decision }),
- });
- const result = payload && payload.result ? payload.result : payload;
- const status = result && result.status;
- if (status === "approved") {
- const name = (result && result.client_name) || "the client";
- elements.oauthVerifyHint.textContent =
- `Authorized ${name}. Switch back to the client tab — it will continue automatically.`;
- elements.oauthVerifyInput.value = "";
- } else if (status === "denied") {
- elements.oauthVerifyHint.textContent = "Denied. The client will see an error.";
- elements.oauthVerifyInput.value = "";
- } else {
- elements.oauthVerifyHint.textContent =
- "Server returned an unexpected response — check the result panel.";
- setOutput(payload);
- }
- } catch (error) {
- const message = error instanceof Error ? error.message : String(error);
- elements.oauthVerifyHint.textContent = `Failed: ${message}`;
- } finally {
- elements.oauthVerifyBtn.disabled = false;
- elements.oauthDenyBtn.disabled = false;
- }
- }
-
- if (elements.oauthVerifyBtn) {
- elements.oauthVerifyBtn.addEventListener("click", () => submitOAuthVerify("approve"));
- }
- if (elements.oauthDenyBtn) {
- elements.oauthDenyBtn.addEventListener("click", () => submitOAuthVerify("deny"));
- }
- if (elements.oauthVerifyInput) {
- elements.oauthVerifyInput.addEventListener("keydown", (event) => {
- if (event.key !== "Enter") {
- return;
- }
- event.preventDefault();
- submitOAuthVerify("approve");
- });
- }
-}
-
-function bindFilesystem() {
- bindFilesystemSort();
- updateFilesystemSortHeaders();
-
- elements.fsGoBtn.addEventListener("click", async () => {
- try {
- await loadFilesystem(elements.fsCurrentUri.value, { pushHistory: true });
- } catch (error) {
- setOutput(error.message);
- }
- });
-
- elements.fsRefreshBtn.addEventListener("click", async () => {
- try {
- await loadFilesystem(state.fsCurrentUri);
- } catch (error) {
- setOutput(error.message);
- }
- });
-
- elements.fsBackBtn.addEventListener("click", async () => {
- if (!state.fsHistory.length) {
- setOutput("No previous directory.");
- return;
- }
-
- const previous = state.fsHistory.pop();
- try {
- await loadFilesystem(previous);
- } catch (error) {
- setOutput(error.message);
- }
- });
-
- elements.fsUpBtn.addEventListener("click", async () => {
- const parent = parentUri(state.fsCurrentUri);
- if (parent === state.fsCurrentUri) {
- setOutput("Already at viking:// root.");
- return;
- }
-
- state.fsHistory.push(state.fsCurrentUri);
- try {
- await loadFilesystem(parent);
- } catch (error) {
- setOutput(error.message);
- }
- });
-
- elements.fsModeListBtn.addEventListener("click", () => {
- setFsViewMode("list");
- loadFilesystem(state.fsCurrentUri).catch((e) => setOutput(e.message));
- });
-
- elements.fsModeTreeBtn.addEventListener("click", async () => {
- if (state.fsViewMode === "tree") {
- // Already in tree mode: toggle all collapse ↔ expand (first level)
- if (state.fsTreeExpanded.size > 0) {
- state.fsTreeExpanded.clear();
- await renderFsTree();
- } else {
- const firstLevel = state.fsTreeData[state.fsCurrentUri] || [];
- await Promise.all(
- firstLevel
- .filter((e) => e.isDir && !state.fsTreeData[e.uri])
- .map(async (e) => {
- try {
- const payload = await callConsole(
- `/ov/fs/ls?uri=${encodeURIComponent(e.uri)}&show_all_hidden=true`,
- { method: "GET" }
- );
- const children = normalizeFsEntries(payload.result, e.uri);
- children.sort((a, b) => {
- if (a.isDir !== b.isDir) return a.isDir ? -1 : 1;
- return (a.uri || "").localeCompare(b.uri || "");
- });
- state.fsTreeData[e.uri] = children;
- } catch (_) {}
- })
- );
- for (const entry of firstLevel) {
- if (entry.isDir) state.fsTreeExpanded.add(entry.uri);
- }
- await renderFsTree();
- }
- return;
- }
- setFsViewMode("tree");
- state.fsTreeData = {};
- state.fsTreeExpanded = new Set();
- loadFilesystem(state.fsCurrentUri).catch((e) => setOutput(e.message));
- });
-}
-
-function bindFind() {
- elements.findBtn.addEventListener("click", async () => {
- const query = elements.findQuery.value.trim();
- const rawLimit = elements.findLimit.value.trim();
- const parsedLimit = Number.parseInt(rawLimit, 10);
- if (!query) {
- setOutput("Query cannot be empty.");
- return;
- }
-
- try {
- const requestBody = {
- query,
- target_uri: elements.findTarget.value.trim(),
- };
- if (Number.isInteger(parsedLimit) && parsedLimit > 0) {
- requestBody.limit = parsedLimit;
- }
-
- const payload = await callConsole("/ov/search/find", {
- method: "POST",
- body: JSON.stringify(requestBody),
- });
-
- const rows = normalizeFindRows(payload.result);
- renderFindTable(rows);
- setOutput(payload);
- } catch (error) {
- setOutput(error.message);
- }
- });
-}
-
-function buildAddResourcePayload() {
- const payload = {
- to: elements.addResourceTarget.value.trim(),
- reason: elements.addResourceReason.value.trim(),
- instruction: elements.addResourceInstruction.value.trim(),
- wait: elements.addResourceWait.checked,
- strict: elements.addResourceStrict.checked,
- directly_upload_media: elements.addResourceUploadMedia.checked,
- };
-
- const timeoutRaw = elements.addResourceTimeout.value.trim();
- if (timeoutRaw) {
- const timeout = Number.parseFloat(timeoutRaw);
- if (Number.isFinite(timeout) && timeout > 0) {
- payload.timeout = timeout;
- }
- }
-
- const ignoreDirs = elements.addResourceIgnoreDirs.value.trim();
- if (ignoreDirs) {
- payload.ignore_dirs = ignoreDirs;
- }
-
- const include = elements.addResourceInclude.value.trim();
- if (include) {
- payload.include = include;
- }
-
- const exclude = elements.addResourceExclude.value.trim();
- if (exclude) {
- payload.exclude = exclude;
- }
-
- return payload;
-}
-
-function renderAddResourceMode() {
- const isPathMode = state.addResourceMode === "path";
- elements.addResourceModePathBtn.classList.toggle("active", isPathMode);
- elements.addResourceModeUploadBtn.classList.toggle("active", !isPathMode);
- elements.addResourceModePathBtn.setAttribute("aria-selected", String(isPathMode));
- elements.addResourceModeUploadBtn.setAttribute("aria-selected", String(!isPathMode));
- elements.addResourcePathPane.hidden = !isPathMode;
- elements.addResourceUploadPane.hidden = isPathMode;
-}
-
-function bindAddResource() {
- elements.addResourceModePathBtn.addEventListener("click", () => {
- state.addResourceMode = "path";
- renderAddResourceMode();
- });
-
- elements.addResourceModeUploadBtn.addEventListener("click", () => {
- state.addResourceMode = "upload";
- renderAddResourceMode();
- });
-
- elements.addResourceSubmitBtn.addEventListener("click", async () => {
- if (!state.writeEnabled) {
- setOutput("Write mode is disabled on the server.");
- return;
- }
-
- try {
- if (state.addResourceMode === "path") {
- const path = elements.addResourcePath.value.trim();
- if (!path) {
- setOutput("Path cannot be empty.");
- return;
- }
-
- const payload = await callConsole("/ov/resources", {
- method: "POST",
- body: JSON.stringify({
- ...buildAddResourcePayload(),
- path,
- }),
- });
- setOutput(payload);
- return;
- }
-
- const file = elements.addResourceFile.files?.[0];
- if (!file) {
- setOutput("Please select a file first.");
- return;
- }
-
- const formData = new FormData();
- formData.append("file", file);
- formData.append("telemetry", "true");
-
- setOutput(`Uploading ${file.name} ...`);
- const uploadPayload = await callConsole("/ov/resources/temp_upload", {
- method: "POST",
- body: formData,
- });
- const tempFileId = uploadPayload.result?.temp_file_id;
- if (!tempFileId) {
- throw new Error("Temp upload did not return temp_file_id.");
- }
-
- const addPayload = await callConsole("/ov/resources", {
- method: "POST",
- body: JSON.stringify({
- ...buildAddResourcePayload(),
- temp_file_id: tempFileId,
- }),
- });
-
- setOutput({
- status: "ok",
- result: {
- upload: uploadPayload.result,
- add_resource: addPayload.result,
- },
- telemetry: {
- upload: uploadPayload.telemetry,
- add_resource: addPayload.telemetry,
- },
- });
- } catch (error) {
- setOutput(error.message);
- }
- });
-}
-
-function normalizeArrayResult(result, candidateKeys = []) {
- if (Array.isArray(result)) {
- return result;
- }
- if (isRecord(result)) {
- for (const key of candidateKeys) {
- if (Array.isArray(result[key])) {
- return result[key];
- }
- }
- }
- return [];
-}
-
-function normalizeTenantAccount(item) {
- if (typeof item === "string") {
- const accountId = item.trim();
- return accountId
- ? {
- accountId,
- userCount: null,
- raw: item,
- }
- : null;
- }
-
- if (!isRecord(item)) {
- return null;
- }
-
- const accountIdValue = pickFirstNonEmpty([
- item.account_id,
- item.accountId,
- item.id,
- item.name,
- item.uri,
- ]);
- if (accountIdValue === null) {
- return null;
- }
-
- return {
- accountId: String(accountIdValue),
- userCount: pickFirstNonEmpty([item.user_count, item.userCount, item.users, item.member_count]),
- raw: item,
- };
-}
-
-function normalizeTenantUser(item) {
- if (typeof item === "string") {
- const userId = item.trim();
- return userId ? { userId, role: "", raw: item } : null;
- }
-
- if (!isRecord(item)) {
- return null;
- }
-
- const userIdValue = pickFirstNonEmpty([item.user_id, item.userId, item.id, item.name]);
- if (userIdValue === null) {
- return null;
- }
-
- let role = pickFirstNonEmpty([item.role, item.user_role, item.userRole, item.permission, item.permissions]);
- if (role === null && typeof item.is_admin === "boolean") {
- role = item.is_admin ? "admin" : "member";
- }
-
- return {
- userId: String(userIdValue),
- role: role === null ? "" : String(role),
- raw: item,
- };
-}
-
-function updateTenantCurrentAccountLabel() {
- elements.tenantCurrentAccount.textContent = state.tenantSelectedAccountId
- ? `Account: ${state.tenantSelectedAccountId}`
- : "No account selected";
-}
-
-function compareTenantRows(left, right, field) {
- const leftValue = isRecord(left) ? left[field] : undefined;
- const rightValue = isRecord(right) ? right[field] : undefined;
- return compareFindValues(leftValue, rightValue);
-}
-
-function sortTenantRows(rows, field, direction) {
- const sorted = [...rows].sort((left, right) => compareTenantRows(left, right, field));
- if (direction === "desc") {
- sorted.reverse();
- }
- return sorted;
-}
-
-function applyTenantAccountFilter() {
- const keyword = elements.tenantAccountSearch.value.trim().toLowerCase();
- state.tenantFilteredAccounts = state.tenantAccounts.filter((account) =>
- account.accountId.toLowerCase().includes(keyword)
- );
-}
-
-function updateTenantSortButtons(buttons, activeField, direction) {
- for (const button of buttons) {
- const field = button.dataset.tenantAccountSort || button.dataset.tenantUserSort || "";
- const isActive = field === activeField;
- const suffix = !isActive ? "" : direction === "asc" ? " ↑" : " ↓";
- button.textContent = `${field}${suffix}`;
- button.setAttribute("aria-sort", isActive ? (direction === "asc" ? "ascending" : "descending") : "none");
- }
-}
-
-function renderAccountsTable() {
- if (!elements.tenantAccountsBody) {
- return;
- }
-
- elements.tenantAccountsBody.innerHTML = "";
- applyTenantAccountFilter();
- const rows = sortTenantRows(
- state.tenantFilteredAccounts,
- state.tenantAccountSortField,
- state.tenantAccountSortDirection
- );
- updateTenantSortButtons(
- elements.tenantAccountSortBtns,
- state.tenantAccountSortField,
- state.tenantAccountSortDirection
- );
-
- if (!rows.length) {
- const tr = document.createElement("tr");
- const td = document.createElement("td");
- td.colSpan = 3;
- td.className = "tenant-empty";
- td.textContent = "No accounts";
- tr.appendChild(td);
- elements.tenantAccountsBody.appendChild(tr);
- return;
- }
-
- for (const account of rows) {
- const tr = document.createElement("tr");
- tr.classList.toggle("tenant-row-selected", account.accountId === state.tenantSelectedAccountId);
-
- const accountCell = document.createElement("td");
- const accountBtn = document.createElement("button");
- accountBtn.type = "button";
- accountBtn.className = "tenant-account-btn";
- accountBtn.textContent = account.accountId;
- accountBtn.addEventListener("click", async () => {
- state.tenantSelectedAccountId = account.accountId;
- updateTenantCurrentAccountLabel();
- renderAccountsTable();
- try {
- await loadTenantUsers(account.accountId);
- } catch (error) {
- setOutput(error.message);
- }
- });
- accountCell.appendChild(accountBtn);
- tr.appendChild(accountCell);
-
- const countCell = document.createElement("td");
- countCell.textContent =
- account.userCount === null || account.userCount === undefined || account.userCount === ""
- ? "-"
- : String(account.userCount);
- tr.appendChild(countCell);
-
- const actionCell = document.createElement("td");
- const actions = document.createElement("div");
- actions.className = "tenant-actions";
-
- const deleteBtn = document.createElement("button");
- deleteBtn.type = "button";
- deleteBtn.className = "danger";
- deleteBtn.textContent = "Delete";
- deleteBtn.disabled = !state.writeEnabled;
- deleteBtn.addEventListener("click", (event) => {
- event.preventDefault();
- event.stopPropagation();
- void executeTenantAction(
- {
- title: "Delete account",
- message: `Delete account "${account.accountId}" and its tenant users?`,
- confirmLabel: `Type ${account.accountId} to confirm`,
- confirmToken: account.accountId,
- actionLabel: "Delete account",
- run: async () =>
- callConsole(`/ov/admin/accounts/${encodeURIComponent(account.accountId)}`, {
- method: "DELETE",
- }),
- afterSuccess: async () => {
- await loadTenantAccounts({ showOutput: false });
- },
- },
- { confirm: true }
- );
- });
- actions.appendChild(deleteBtn);
-
- actionCell.appendChild(actions);
- tr.appendChild(actionCell);
- elements.tenantAccountsBody.appendChild(tr);
- }
-}
-
-function tenantRoleOptions(role) {
- const defaults = ["user", "admin"];
- if (role && !defaults.includes(role)) {
- defaults.unshift(role);
- }
- return defaults;
-}
-
-function renderUsersTable() {
- if (!elements.tenantUsersBody) {
- return;
- }
-
- elements.tenantUsersBody.innerHTML = "";
- updateTenantSortButtons(elements.tenantUserSortBtns, state.tenantUserSortField, state.tenantUserSortDirection);
-
- if (!state.tenantSelectedAccountId) {
- const tr = document.createElement("tr");
- const td = document.createElement("td");
- td.colSpan = 3;
- td.className = "tenant-empty";
- td.textContent = "Select an account to view users";
- tr.appendChild(td);
- elements.tenantUsersBody.appendChild(tr);
- return;
- }
-
- const rows = sortTenantRows(state.tenantUsers, state.tenantUserSortField, state.tenantUserSortDirection);
- if (!rows.length) {
- const tr = document.createElement("tr");
- const td = document.createElement("td");
- td.colSpan = 3;
- td.className = "tenant-empty";
- td.textContent = "No users";
- tr.appendChild(td);
- elements.tenantUsersBody.appendChild(tr);
- return;
- }
-
- for (const user of rows) {
- const tr = document.createElement("tr");
-
- const userIdCell = document.createElement("td");
- userIdCell.textContent = user.userId;
- tr.appendChild(userIdCell);
-
- const roleCell = document.createElement("td");
- roleCell.textContent = user.role || "-";
- tr.appendChild(roleCell);
-
- const actionCell = document.createElement("td");
- const actions = document.createElement("div");
- actions.className = "tenant-actions";
-
- const roleSelect = document.createElement("select");
- roleSelect.className = "tenant-role-select";
- for (const optionValue of tenantRoleOptions(user.role)) {
- const option = document.createElement("option");
- option.value = optionValue;
- option.textContent = optionValue;
- option.selected = optionValue === (user.role || "member");
- roleSelect.appendChild(option);
- }
- actions.appendChild(roleSelect);
-
- const roleBtn = document.createElement("button");
- roleBtn.type = "button";
- roleBtn.textContent = "Update Role";
- roleBtn.disabled = !state.writeEnabled;
- roleBtn.addEventListener("click", () => {
- void executeTenantAction({
- title: "Update user role",
- message: `Set role for "${user.userId}" under "${state.tenantSelectedAccountId}" to "${roleSelect.value}".`,
- confirmLabel: `Type ${state.tenantSelectedAccountId}/${user.userId} to confirm`,
- confirmToken: `${state.tenantSelectedAccountId}/${user.userId}`,
- actionLabel: "Save role",
- run: async () =>
- callConsole(
- `/ov/admin/accounts/${encodeURIComponent(state.tenantSelectedAccountId)}/users/${encodeURIComponent(
- user.userId
- )}/role`,
- {
- method: "PUT",
- body: JSON.stringify({ role: roleSelect.value }),
- }
- ),
- afterSuccess: async () => {
- await loadTenantUsers(state.tenantSelectedAccountId, { showOutput: false });
- },
- });
- });
- actions.appendChild(roleBtn);
-
- const keyBtn = document.createElement("button");
- keyBtn.type = "button";
- keyBtn.textContent = "Reset API Key";
- keyBtn.disabled = !state.writeEnabled;
- keyBtn.addEventListener("click", () => {
- void executeTenantAction({
- title: "Reset API key",
- message: `Generate a new API key for "${user.userId}" under "${state.tenantSelectedAccountId}".`,
- confirmLabel: `Type ${state.tenantSelectedAccountId}/${user.userId} to confirm`,
- confirmToken: `${state.tenantSelectedAccountId}/${user.userId}`,
- actionLabel: "Reset key",
- run: async () =>
- callConsole(
- `/ov/admin/accounts/${encodeURIComponent(state.tenantSelectedAccountId)}/users/${encodeURIComponent(
- user.userId
- )}/key`,
- { method: "POST", body: JSON.stringify({}) }
- ),
- });
- });
- actions.appendChild(keyBtn);
-
- const deleteBtn = document.createElement("button");
- deleteBtn.type = "button";
- deleteBtn.className = "danger";
- deleteBtn.textContent = "Remove";
- deleteBtn.disabled = !state.writeEnabled;
- deleteBtn.addEventListener("click", () => {
- void executeTenantAction(
- {
- title: "Remove user",
- message: `Remove "${user.userId}" from account "${state.tenantSelectedAccountId}".`,
- confirmLabel: `Type ${state.tenantSelectedAccountId}/${user.userId} to confirm`,
- confirmToken: `${state.tenantSelectedAccountId}/${user.userId}`,
- actionLabel: "Remove user",
- run: async () =>
- callConsole(
- `/ov/admin/accounts/${encodeURIComponent(state.tenantSelectedAccountId)}/users/${encodeURIComponent(
- user.userId
- )}`,
- { method: "DELETE" }
- ),
- afterSuccess: async () => {
- await loadTenantUsers(state.tenantSelectedAccountId, { showOutput: false });
- },
- },
- { confirm: true }
- );
- });
- actions.appendChild(deleteBtn);
-
- actionCell.appendChild(actions);
- tr.appendChild(actionCell);
- elements.tenantUsersBody.appendChild(tr);
- }
-}
-
-async function loadTenantUsers(accountId, { showOutput = true } = {}) {
- if (!accountId) {
- state.tenantUsers = [];
- updateTenantCurrentAccountLabel();
- renderUsersTable();
- return null;
- }
-
- const payload = await callConsole(`/ov/admin/accounts/${encodeURIComponent(accountId)}/users`, {
- method: "GET",
- });
- const normalizedUsers = normalizeArrayResult(payload.result, ["users", "items", "results"])
- .map(normalizeTenantUser)
- .filter(Boolean);
- state.tenantSelectedAccountId = accountId;
- state.tenantUsers = normalizedUsers;
- updateTenantCurrentAccountLabel();
- renderUsersTable();
- if (showOutput) {
- setOutput(payload);
- }
- return payload;
-}
-
-async function loadTenantAccounts({ showOutput = true } = {}) {
- const payload = await callConsole("/ov/admin/accounts", { method: "GET" });
- const normalizedAccounts = normalizeArrayResult(payload.result, ["accounts", "items", "results"])
- .map(normalizeTenantAccount)
- .filter(Boolean);
- state.tenantAccounts = normalizedAccounts;
- state.tenantAccountsLoaded = true;
-
- const hasSelected = state.tenantSelectedAccountId
- ? normalizedAccounts.some((account) => account.accountId === state.tenantSelectedAccountId)
- : false;
- if (!hasSelected) {
- state.tenantSelectedAccountId = normalizedAccounts[0]?.accountId || "";
- }
-
- renderAccountsTable();
- if (state.tenantSelectedAccountId) {
- await loadTenantUsers(state.tenantSelectedAccountId, { showOutput: false });
- } else {
- state.tenantUsers = [];
- updateTenantCurrentAccountLabel();
- renderUsersTable();
- }
- if (showOutput) {
- setOutput(payload);
- }
- return payload;
-}
-
-async function ensureTenantsLoaded() {
- if (!state.tenantAccountsLoaded) {
- await loadTenantAccounts({ showOutput: false });
- }
-}
-
-function closeTenantConfirmModal() {
- elements.tenantConfirmModal.hidden = true;
- elements.tenantConfirmInput.value = "";
- elements.tenantConfirmError.hidden = true;
- elements.tenantConfirmError.textContent = "";
- state.tenantConfirmRequest = null;
-}
-
-function updateTenantConfirmState() {
- const request = state.tenantConfirmRequest;
- if (!request) {
- return;
- }
- const expected = request.confirmToken || "";
- const value = elements.tenantConfirmInput.value.trim();
- const valid = !expected || value === expected;
- elements.tenantConfirmActionBtn.disabled = !valid;
- elements.tenantConfirmError.hidden = true;
- elements.tenantConfirmError.textContent = "";
-}
-
-function openTenantConfirmModal(request) {
- state.tenantConfirmRequest = request;
- elements.tenantConfirmTitle.textContent = request.title;
- elements.tenantConfirmMessage.textContent = request.message;
- elements.tenantConfirmLabel.textContent = request.confirmLabel || "Type to confirm";
- elements.tenantConfirmActionBtn.textContent = request.actionLabel || "Confirm";
- elements.tenantConfirmInput.value = "";
- elements.tenantConfirmActionBtn.disabled = true;
- elements.tenantConfirmError.hidden = true;
- elements.tenantConfirmError.textContent = "";
- elements.tenantConfirmModal.hidden = false;
- updateTenantConfirmState();
- elements.tenantConfirmInput.focus();
-}
-
-async function performTenantAction(request) {
- const payload = await request.run();
- if (request.afterSuccess) {
- await request.afterSuccess(payload);
- }
- setOutput(payload);
-}
-
-async function executeTenantAction(request, { confirm = false } = {}) {
- if (!state.writeEnabled) {
- setOutput("Write mode is disabled on the server.");
- return;
- }
-
- if (confirm) {
- openTenantConfirmModal(request);
- return;
- }
-
- try {
- await performTenantAction(request);
- } catch (error) {
- setOutput(error.message);
- }
-}
-
-function bindTenantSortButtons() {
- for (const button of elements.tenantAccountSortBtns) {
- button.addEventListener("click", () => {
- const field = button.dataset.tenantAccountSort;
- if (!field) {
- return;
- }
- if (state.tenantAccountSortField === field) {
- state.tenantAccountSortDirection = state.tenantAccountSortDirection === "asc" ? "desc" : "asc";
- } else {
- state.tenantAccountSortField = field;
- state.tenantAccountSortDirection = "asc";
- }
- renderAccountsTable();
- });
- }
-
- for (const button of elements.tenantUserSortBtns) {
- button.addEventListener("click", () => {
- const field = button.dataset.tenantUserSort;
- if (!field) {
- return;
- }
- if (state.tenantUserSortField === field) {
- state.tenantUserSortDirection = state.tenantUserSortDirection === "asc" ? "desc" : "asc";
- } else {
- state.tenantUserSortField = field;
- state.tenantUserSortDirection = "asc";
- }
- renderUsersTable();
- });
- }
-}
-
-function bindAddMemory() {
- elements.addMemoryBtn.addEventListener("click", async () => {
- if (!state.writeEnabled) {
- setOutput("Write mode is disabled on the server.");
- return;
- }
-
- const text = elements.addMemoryInput.value.trim();
- if (!text) {
- setOutput("Please enter content to add as memory.");
- return;
- }
-
- let messages;
- try {
- const parsed = JSON.parse(text);
- if (Array.isArray(parsed)) {
- messages = parsed;
- } else {
- messages = [{ role: "user", content: text }];
- }
- } catch (_) {
- messages = [{ role: "user", content: text }];
- }
-
- try {
- setOutput("Creating session...");
- const sessionPayload = await callConsole("/ov/sessions", {
- method: "POST",
- body: JSON.stringify({}),
- });
- const sessionId = sessionPayload.result?.session_id;
- if (!sessionId) {
- throw new Error("Failed to create session: no session_id returned.");
- }
-
- for (const msg of messages) {
- const payload = { ...msg };
- await callConsole(`/ov/sessions/${sessionId}/messages`, {
- method: "POST",
- body: JSON.stringify(payload),
- });
- }
-
- setOutput("Committing session...");
- const commitPayload = await callConsole(`/ov/sessions/${sessionId}/commit`, {
- method: "POST",
- body: JSON.stringify({}),
- });
- setOutput(commitPayload);
- } catch (error) {
- setOutput({ error: error.message });
- }
- });
-}
-
-function bindTenants() {
- bindTenantSortButtons();
- renderAccountsTable();
- renderUsersTable();
- updateTenantCurrentAccountLabel();
-
- elements.tenantAccountSearch.addEventListener("input", () => {
- renderAccountsTable();
- });
-
- elements.tenantRefreshAccountsBtn.addEventListener("click", async () => {
- try {
- await loadTenantAccounts();
- } catch (error) {
- setOutput(error.message);
- }
- });
-
- elements.tenantCreateAccountBtn.addEventListener("click", async () => {
- const accountId = elements.tenantCreateAccountId.value.trim();
- const adminUserId = elements.tenantCreateAdminUserId.value.trim();
- if (!accountId || !adminUserId) {
- setOutput("Please input account_id and first admin user_id.");
- return;
- }
-
- await executeTenantAction({
- title: "Create account",
- message: `Create account "${accountId}" with initial admin "${adminUserId}".`,
- confirmLabel: `Type ${accountId} to confirm`,
- confirmToken: accountId,
- actionLabel: "Create account",
- run: async () =>
- callConsole("/ov/admin/accounts", {
- method: "POST",
- body: JSON.stringify({ account_id: accountId, admin_user_id: adminUserId }),
- }),
- afterSuccess: async () => {
- elements.tenantCreateAccountId.value = "";
- await loadTenantAccounts({ showOutput: false });
- },
- });
- });
-
- elements.tenantAddUserBtn.addEventListener("click", async () => {
- const accountId = state.tenantSelectedAccountId;
- const userId = elements.tenantAddUserId.value.trim();
- const role = elements.tenantAddUserRole.value;
- if (!accountId) {
- setOutput("Select an account before adding users.");
- return;
- }
- if (!userId) {
- setOutput("Please input new user_id.");
- return;
- }
-
- await executeTenantAction({
- title: "Add user",
- message: `Add user "${userId}" to account "${accountId}" with role "${role}".`,
- confirmLabel: `Type ${accountId}/${userId} to confirm`,
- confirmToken: `${accountId}/${userId}`,
- actionLabel: "Add user",
- run: async () =>
- callConsole(`/ov/admin/accounts/${encodeURIComponent(accountId)}/users`, {
- method: "POST",
- body: JSON.stringify({ user_id: userId, role }),
- }),
- afterSuccess: async () => {
- elements.tenantAddUserId.value = "";
- await loadTenantUsers(accountId, { showOutput: false });
- },
- });
- });
-
- elements.tenantConfirmInput.addEventListener("input", () => {
- updateTenantConfirmState();
- });
-
- elements.tenantConfirmCancelBtn.addEventListener("click", () => {
- closeTenantConfirmModal();
- });
-
- elements.tenantConfirmModal.addEventListener("click", (event) => {
- if (event.target === elements.tenantConfirmModal) {
- closeTenantConfirmModal();
- }
- });
-
- elements.tenantConfirmActionBtn.addEventListener("click", async () => {
- const request = state.tenantConfirmRequest;
- if (!request) {
- return;
- }
-
- const expected = request.confirmToken || "";
- const typed = elements.tenantConfirmInput.value.trim();
- if (expected && typed !== expected) {
- elements.tenantConfirmError.hidden = false;
- elements.tenantConfirmError.textContent = "Confirmation text mismatch.";
- return;
- }
-
- elements.tenantConfirmActionBtn.disabled = true;
- try {
- await performTenantAction(request);
- closeTenantConfirmModal();
- } catch (error) {
- closeTenantConfirmModal();
- setOutput(error.message);
- }
- });
-}
-
-function bindMonitor() {
- elements.systemBtn.addEventListener("click", async () => {
- try {
- const payload = await callConsole("/ov/system/status", { method: "GET" });
- const rows = Object.entries(payload.result || {}).map(([key, value]) => ({
- label: `${key}: ${typeof value === "string" ? value : JSON.stringify(value)}`,
- }));
- renderList(elements.monitorResults, rows);
- setOutput(payload);
- } catch (error) {
- setOutput(error.message);
- }
- });
-
- elements.observerBtn.addEventListener("click", async () => {
- try {
- const payload = await callConsole("/ov/observer/system", { method: "GET" });
- const rows = Object.entries(payload.result?.components || {}).map(([name, value]) => ({
- label: `${name}: ${value?.status || JSON.stringify(value)}`,
- }));
- renderList(elements.monitorResults, rows);
- setOutput(payload);
- } catch (error) {
- setOutput(error.message);
- }
- });
-}
-
-async function init() {
- state.connectionSettings = resolveRuntimeConsoleSettings(window.localStorage, getApiKey());
- if (state.connectionSettings.apiKey) {
- window.sessionStorage.setItem(SESSION_KEY, state.connectionSettings.apiKey);
- }
- elements.accountInput.value = state.connectionSettings.accountId;
- elements.userInput.value = state.connectionSettings.userId;
- elements.agentIdInput.value = state.connectionSettings.agentId;
-
- initShellState();
- bindShellControls();
- initResizablePanes();
- initFsColumnResize();
- bindTabs();
- bindConnection();
- bindFilesystem();
- bindFind();
- renderFindTable([]);
- bindAddResource();
- renderAddResourceMode();
- bindAddMemory();
- bindTenants();
- bindMonitor();
- syncResultEmptyState();
- updateConnectionHint();
- setActivePanel(state.activePanel);
- await refreshCapabilities();
-
- try {
- await loadFilesystem("viking://");
- } catch (error) {
- setOutput(error.message);
- }
-}
-
-init();
diff --git a/openviking/console/static/apple-touch-icon.png b/openviking/console/static/apple-touch-icon.png
deleted file mode 100644
index 60289db06..000000000
Binary files a/openviking/console/static/apple-touch-icon.png and /dev/null differ
diff --git a/openviking/console/static/console_settings.js b/openviking/console/static/console_settings.js
deleted file mode 100644
index ff023934d..000000000
--- a/openviking/console/static/console_settings.js
+++ /dev/null
@@ -1,107 +0,0 @@
-const LEGACY_API_KEY_STORAGE_KEY = "ov_console_api_key";
-const CONNECTION_SETTINGS_STORAGE_KEY = "ov_console_connection_settings_v1";
-
-function normalizeValue(value) {
- if (value === undefined || value === null) {
- return "";
- }
- return String(value).trim();
-}
-
-export function normalizeConsoleSettings(settings = {}) {
- return {
- apiKey: normalizeValue(settings.apiKey),
- accountId: normalizeValue(settings.accountId),
- userId: normalizeValue(settings.userId),
- agentId: normalizeValue(settings.agentId),
- };
-}
-
-export function serializeConsoleSettings(settings = {}) {
- const normalized = normalizeConsoleSettings(settings);
- const payload = {};
-
- for (const [key, value] of Object.entries(normalized)) {
- if (value) {
- payload[key] = value;
- }
- }
-
- return JSON.stringify(payload);
-}
-
-export function parseConsoleSettings(rawValue) {
- if (!rawValue) {
- return normalizeConsoleSettings();
- }
-
- try {
- const parsed = JSON.parse(rawValue);
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
- return normalizeConsoleSettings();
- }
- return normalizeConsoleSettings(parsed);
- } catch (_error) {
- return normalizeConsoleSettings();
- }
-}
-
-export function loadConsoleSettings(storage) {
- const stored = storage.getItem(CONNECTION_SETTINGS_STORAGE_KEY);
- if (stored) {
- return parseConsoleSettings(stored);
- }
-
- return normalizeConsoleSettings({
- apiKey: storage.getItem(LEGACY_API_KEY_STORAGE_KEY) || "",
- });
-}
-
-export function resolveRuntimeConsoleSettings(storage, sessionApiKey = "") {
- const saved = loadConsoleSettings(storage);
- const runtimeApiKey = normalizeValue(sessionApiKey) || saved.apiKey;
- return normalizeConsoleSettings({
- ...saved,
- apiKey: runtimeApiKey,
- });
-}
-
-export function saveConsoleSettings(storage, settings) {
- const normalized = normalizeConsoleSettings(settings);
- storage.setItem(CONNECTION_SETTINGS_STORAGE_KEY, serializeConsoleSettings(normalized));
-
- if (normalized.apiKey) {
- storage.setItem(LEGACY_API_KEY_STORAGE_KEY, normalized.apiKey);
- } else {
- storage.removeItem(LEGACY_API_KEY_STORAGE_KEY);
- }
-
- return normalized;
-}
-
-export function clearConsoleSettings(storage) {
- storage.removeItem(CONNECTION_SETTINGS_STORAGE_KEY);
- storage.removeItem(LEGACY_API_KEY_STORAGE_KEY);
-}
-
-export function buildRequestHeaders(baseHeaders = {}, settings = {}) {
- const normalized = normalizeConsoleSettings(settings);
- const headers = {
- ...baseHeaders,
- };
-
- if (normalized.apiKey) {
- headers["X-API-Key"] = normalized.apiKey;
- }
- if (normalized.accountId) {
- headers["X-OpenViking-Account"] = normalized.accountId;
- }
- if (normalized.userId) {
- headers["X-OpenViking-User"] = normalized.userId;
- }
- if (normalized.agentId) {
- headers["X-OpenViking-Agent"] = normalized.agentId;
- }
-
- return headers;
-}
diff --git a/openviking/console/static/favicon-32.png b/openviking/console/static/favicon-32.png
deleted file mode 100644
index 2a1662ed7..000000000
Binary files a/openviking/console/static/favicon-32.png and /dev/null differ
diff --git a/openviking/console/static/index.html b/openviking/console/static/index.html
deleted file mode 100644
index 346ee6422..000000000
--- a/openviking/console/static/index.html
+++ /dev/null
@@ -1,398 +0,0 @@
-<!doctype html>
-<html lang="en">
- <head>
- <meta charset="UTF-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>OpenViking Console</title>
- <link rel="icon" type="image/x-icon" href="/console/favicon.ico" />
- <link rel="icon" type="image/png" sizes="32x32" href="/console/favicon-32.png" />
- <link rel="apple-touch-icon" href="/console/apple-touch-icon.png" />
- <link rel="stylesheet" href="/console/styles.css" />
- </head>
- <body>
- <div class="workspace shell">
- <header class="topbar">
- <div class="topbar-left">
- <button id="navToggleBtn" class="icon-btn" type="button" aria-label="Toggle navigation">☰</button>
- <div class="brand">
- <span class="brand-title">OpenViking Console</span>
- <span class="brand-subtitle">Control Plane Dashboard</span>
- </div>
- </div>
- <div class="topbar-right">
- <span class="pill">
- <span class="statusDot ok" aria-hidden="true"></span>
- UI Ready
- </span>
- <span id="writeBadge" class="badge">Readonly</span>
- <button id="resultToggleBtn" class="topbar-result-toggle" type="button">Hide Result</button>
- <div class="theme-toggle" role="group" aria-label="Theme mode">
- <button type="button" class="theme-btn" data-theme-mode="system" aria-pressed="false">System</button>
- <button type="button" class="theme-btn" data-theme-mode="dark" aria-pressed="false">Dark</button>
- <button type="button" class="theme-btn" data-theme-mode="light" aria-pressed="false">Light</button>
- </div>
- </div>
- </header>
-
- <div class="shell-body">
- <aside class="sidebar" aria-label="Capabilities">
- <nav class="nav-groups">
- <section class="nav-group">
- <h2 class="nav-group-title">Data</h2>
- <button id="tab-filesystem" class="tab nav-item active" data-panel="filesystem">FileSystem</button>
- <button id="tab-find" class="tab nav-item" data-panel="find">Find</button>
- <button id="tab-add-resource" class="tab nav-item" data-panel="add-resource">Add Resource</button>
- <button id="tab-add-memory" class="tab nav-item" data-panel="add-memory">Add Memory</button>
- </section>
-
- <section class="nav-group">
- <h2 class="nav-group-title">Ops</h2>
- <button id="tab-tenants" class="tab nav-item" data-panel="tenants">Tenants</button>
- <button id="tab-monitor" class="tab nav-item" data-panel="monitor">Monitor</button>
- </section>
-
- <section class="nav-group">
- <h2 class="nav-group-title">Access</h2>
- <button id="tab-settings" class="tab nav-item" data-panel="settings">Settings</button>
- </section>
- </nav>
- </aside>
-
- <div id="sidebarResizer" class="resizer resizer-vertical" role="separator" aria-orientation="vertical"></div>
-
- <main class="content-area">
- <section class="content">
- <div class="panel-stack">
- <section id="panel-filesystem" class="panel active">
- <h2>FileSystem</h2>
- <div class="fs-toolbar">
- <div class="fs-toolbar-nav">
- <button id="fsBackBtn" class="ghost fs-nav-btn" title="Back">←</button>
- <button id="fsUpBtn" class="ghost fs-nav-btn" title="Up">↑</button>
- <button id="fsRefreshBtn" class="ghost fs-nav-btn" title="Refresh">↻</button>
- </div>
- <input id="fsCurrentUri" type="text" value="viking://" aria-label="Current URI" />
- <div class="fs-toolbar-controls">
- <div class="fs-view-toggle">
- <button id="fsModeListBtn" class="ghost active" aria-pressed="true">List</button>
- <button id="fsModeTreeBtn" class="ghost" aria-pressed="false">Tree</button>
- </div>
- <button id="fsGoBtn">Enter</button>
- </div>
- </div>
- <div id="fsTree" class="fs-tree" hidden></div>
- <div class="fs-table-wrap">
- <table class="fs-table">
- <thead>
- <tr>
- <th
- id="fsColAction"
- scope="col"
- data-min-width="34"
- data-resizable="false"
- aria-label="open file content"
- ></th>
- <th id="fsColUri" scope="col" data-min-width="220">
- <button class="fs-sort-btn" data-fs-sort="uri" aria-sort="none">uri</button>
- </th>
- <th id="fsColSize" scope="col" data-min-width="90">
- <button class="fs-sort-btn" data-fs-sort="size" aria-sort="none">size</button>
- </th>
- <th id="fsColIsDir" scope="col" data-min-width="90">
- <button class="fs-sort-btn" data-fs-sort="isDir" aria-sort="none">isDir</button>
- </th>
- <th id="fsColModTime" scope="col" data-min-width="160">
- <button class="fs-sort-btn" data-fs-sort="modTime" aria-sort="none">modTime</button>
- </th>
- <th id="fsColAbstract" scope="col" data-min-width="220">
- <button class="fs-sort-btn" data-fs-sort="abstract" aria-sort="none">abstract</button>
- </th>
- </tr>
- </thead>
- <tbody id="fsEntries"></tbody>
- </table>
- </div>
- <div class="fs-editor-shell" hidden>
- <label for="fsEditor">Editor</label>
- <textarea id="fsEditor" rows="16" spellcheck="false"></textarea>
- <div class="row">
- <button id="fsSaveBtn">Save</button>
- <button id="fsRevertBtn" class="ghost">Revert</button>
- </div>
- </div>
- </section>
-
- <section id="panel-find" class="panel">
- <h2>Find</h2>
- <div class="find-controls">
- <div class="find-field find-field-query">
- <label for="findQuery">Query</label>
- <input id="findQuery" type="text" placeholder="Search query" />
- </div>
- <div class="find-field">
- <label for="findTarget">Target URI (optional)</label>
- <input id="findTarget" type="text" placeholder="viking://resources/" />
- </div>
- <div class="find-field find-field-limit">
- <label for="findLimit">Limit</label>
- <input id="findLimit" type="number" min="1" step="1" placeholder="10" />
- </div>
- </div>
- <button id="findBtn">Run Find</button>
- <div class="find-table-wrap">
- <table class="find-table">
- <thead id="findResultsHead"></thead>
- <tbody id="findResultsBody"></tbody>
- </table>
- </div>
- </section>
-
- <section id="panel-add-resource" class="panel">
- <h2>Add Resource</h2>
- <div class="add-resource-mode-toggle" role="tablist" aria-label="Add Resource input mode">
- <button
- id="addResourceModePathBtn"
- class="active"
- type="button"
- role="tab"
- aria-selected="true"
- aria-controls="addResourcePathPane"
- >
- Path
- </button>
- <button
- id="addResourceModeUploadBtn"
- type="button"
- role="tab"
- aria-selected="false"
- aria-controls="addResourceUploadPane"
- >
- Upload
- </button>
- </div>
- <div id="addResourcePathPane" class="add-resource-input-pane" role="tabpanel">
- <label for="addResourcePath">Path on OpenViking server</label>
- <input id="addResourcePath" type="text" placeholder="/abs/path/on/server/or/dir" />
- </div>
- <div id="addResourceUploadPane" class="add-resource-input-pane" role="tabpanel" hidden>
- <label for="addResourceFile">Upload file for temp path</label>
- <input id="addResourceFile" type="file" />
- </div>
- <label for="addResourceTarget">Target URI (optional)</label>
- <input id="addResourceTarget" type="text" placeholder="viking://resources/" />
- <div class="row wrap checks">
- <label class="check-item" for="addResourceWait">
- <input id="addResourceWait" type="checkbox" />
- <span>wait</span>
- </label>
- <label class="check-item" for="addResourceStrict">
- <input id="addResourceStrict" type="checkbox" checked />
- <span>strict</span>
- </label>
- <label class="check-item" for="addResourceUploadMedia">
- <input id="addResourceUploadMedia" type="checkbox" checked />
- <span>directly_upload_media</span>
- </label>
- </div>
- <label for="addResourceTimeout">Timeout seconds (optional)</label>
- <input id="addResourceTimeout" type="number" min="0" step="0.1" placeholder="30" />
- <label for="addResourceIgnoreDirs">ignore_dirs (optional, comma-separated)</label>
- <input id="addResourceIgnoreDirs" type="text" placeholder=".git,node_modules,.venv" />
- <label for="addResourceInclude">include pattern (optional)</label>
- <input id="addResourceInclude" type="text" placeholder="*.md,*.txt" />
- <label for="addResourceExclude">exclude pattern (optional)</label>
- <input id="addResourceExclude" type="text" placeholder="*.log,*.tmp" />
- <label for="addResourceReason">Reason (optional)</label>
- <textarea id="addResourceReason" rows="2" placeholder="Why add this resource?"></textarea>
- <label for="addResourceInstruction">Instruction (optional)</label>
- <textarea
- id="addResourceInstruction"
- rows="2"
- placeholder="How should OpenViking process this resource?"
- ></textarea>
- <div class="row wrap">
- <button id="addResourceSubmitBtn">Add Resource</button>
- </div>
- <p class="muted">Use the tabs to choose either a server path or a local upload. Result panel will show backend response.</p>
- </section>
-
- <section id="panel-add-memory" class="panel">
- <h2>Add Memory</h2>
- <label for="addMemoryInput">Content</label>
- <textarea
- id="addMemoryInput"
- rows="8"
- placeholder="Plain text (treated as a user message), or JSON array of {role, content} objects for multi-turn."
- ></textarea>
- <button id="addMemoryBtn">Add Memory</button>
- </section>
-
- <section id="panel-tenants" class="panel">
- <h2>Tenants</h2>
- <div class="tenant-layout">
- <section class="tenant-pane">
- <div class="tenant-pane-head">
- <h3>Accounts</h3>
- <div class="row">
- <input id="tenantAccountSearch" type="text" placeholder="Filter account_id" />
- <button id="tenantRefreshAccountsBtn" class="ghost">Refresh</button>
- </div>
- </div>
- <div class="row tenant-inline-form">
- <input id="tenantCreateAccountId" type="text" placeholder="new account_id" />
- <input id="tenantCreateAdminUserId" type="text" value="admin" placeholder="first admin user_id" />
- <button id="tenantCreateAccountBtn" class="tenant-create-btn" data-tenant-write>Create</button>
- </div>
- <div class="tenant-table-wrap">
- <table class="tenant-table">
- <thead>
- <tr>
- <th scope="col">
- <button class="tenant-sort-btn" data-tenant-account-sort="account_id" aria-sort="none">
- account_id
- </button>
- </th>
- <th scope="col">
- <button class="tenant-sort-btn" data-tenant-account-sort="user_count" aria-sort="none">
- user_count
- </button>
- </th>
- <th scope="col">actions</th>
- </tr>
- </thead>
- <tbody id="tenantAccountsBody"></tbody>
- </table>
- </div>
- </section>
-
- <section class="tenant-pane">
- <div class="tenant-pane-head">
- <h3>Users</h3>
- <span id="tenantCurrentAccount" class="badge badge-soft">No account selected</span>
- </div>
- <div class="row tenant-inline-form">
- <input id="tenantAddUserId" type="text" placeholder="new user_id" />
- <select id="tenantAddUserRole">
- <option value="user">user</option>
- <option value="admin">admin</option>
- </select>
- <button id="tenantAddUserBtn" data-tenant-write>Add User</button>
- </div>
- <div class="tenant-table-wrap">
- <table class="tenant-table">
- <thead>
- <tr>
- <th scope="col">
- <button class="tenant-sort-btn" data-tenant-user-sort="user_id" aria-sort="none">
- user_id
- </button>
- </th>
- <th scope="col">
- <button class="tenant-sort-btn" data-tenant-user-sort="role" aria-sort="none">role</button>
- </th>
- <th scope="col">actions</th>
- </tr>
- </thead>
- <tbody id="tenantUsersBody"></tbody>
- </table>
- </div>
- </section>
- </div>
-
- <p id="tenantHint" class="muted">
- Tip: Select an account to load users. Write operations require explicit confirmation.
- </p>
-
- <div id="tenantConfirmModal" class="tenant-modal" hidden>
- <div class="tenant-modal-card" role="dialog" aria-modal="true" aria-labelledby="tenantConfirmTitle">
- <h3 id="tenantConfirmTitle">Confirm action</h3>
- <p id="tenantConfirmMessage" class="muted"></p>
- <label id="tenantConfirmLabel" for="tenantConfirmInput">Type to confirm</label>
- <input id="tenantConfirmInput" type="text" autocomplete="off" />
- <p id="tenantConfirmError" class="tenant-error" hidden></p>
- <div class="row">
- <button id="tenantConfirmCancelBtn" class="ghost">Cancel</button>
- <button id="tenantConfirmActionBtn" class="danger">Confirm</button>
- </div>
- </div>
- </div>
- </section>
-
- <section id="panel-monitor" class="panel">
- <h2>Monitor</h2>
- <div class="row">
- <button id="systemBtn">System Status</button>
- <button id="observerBtn">Observer(System)</button>
- </div>
- <ul id="monitorResults" class="list"></ul>
- </section>
-
- <section id="panel-settings" class="panel">
- <h2>Settings</h2>
- <label for="apiKeyInput">X-API-Key</label>
- <input id="apiKeyInput" type="password" placeholder="Paste key to reuse in this browser" />
- <label for="accountInput">X-OpenViking-Account</label>
- <input id="accountInput" type="text" placeholder="Default account_id for console requests" />
- <label for="userInput">X-OpenViking-User</label>
- <input id="userInput" type="text" placeholder="Default user_id for console requests" />
- <label for="agentIdInput">X-OpenViking-Agent</label>
- <input id="agentIdInput" type="text" placeholder="Default agent_id for console requests" />
- <div class="row">
- <button id="saveKeyBtn">Save</button>
- <button id="clearKeyBtn" class="ghost">Clear</button>
- </div>
- <p id="connectionHint" class="muted">No API key in session.</p>
-
- <h3 style="margin-top: 1.75rem;">Authorize an MCP client</h3>
- <p class="muted" style="margin-top: -0.25rem;">
- Confirm a pending OAuth authorization for Claude.ai / Claude Desktop /
- ChatGPT / Cursor. The client shows a 6-character verification code
- on its authorize page — paste it here and click Authorize.
- </p>
- <label for="oauthVerifyInput">Verification code</label>
- <input id="oauthVerifyInput" type="text" maxlength="12"
- autocomplete="off" placeholder="ABC234"
- style="font-family: ui-monospace, monospace; letter-spacing: 0.15em; text-transform: uppercase;">
- <div class="row" style="gap: 0.5rem;">
- <button id="oauthVerifyBtn" type="button">Authorize</button>
- <button id="oauthDenyBtn" class="ghost" type="button">Deny</button>
- </div>
- <p id="oauthVerifyHint" class="muted" style="margin: 0.5rem 0 0; font-size: 0.85rem;"></p>
-
- <details style="margin-top: 1.25rem;">
- <summary class="muted" style="cursor: pointer;">Generate OTP for legacy push flow</summary>
- <p class="muted" style="margin: 0.75rem 0;">
- For CLI / scripted clients that drive the older push-style flow:
- generate an OTP here, then paste it on the client side.
- </p>
- <div class="row">
- <button id="getOtpBtn" type="button">Get OTP</button>
- </div>
- <div id="otpBox" hidden style="margin-top: 0.75rem; padding: 0.75rem; border-radius: 6px; background: var(--surface-soft, #f5f5f7);">
- <div class="row" style="gap: 0.5rem; align-items: center;">
- <code id="otpValue" style="font-size: 1.4rem; letter-spacing: 0.15em; padding: 4px 10px; border-radius: 4px; background: var(--surface, white);"></code>
- <button id="otpCopyBtn" class="ghost" type="button">Copy</button>
- </div>
- <p id="otpExpiry" class="muted" style="margin: 0.5rem 0 0; font-size: 0.85rem;"></p>
- </div>
- </details>
- </section>
- </div>
-
- <div id="outputResizer" class="resizer resizer-horizontal" role="separator" aria-orientation="horizontal"></div>
-
- <section class="result-card">
- <div class="result-head">
- <h2>Result</h2>
- <button id="clearOutputBtn" class="ghost" type="button">Clear</button>
- </div>
- <pre id="output"></pre>
- </section>
- </section>
- </main>
- </div>
- </div>
-
- <script type="module" src="/console/app.js"></script>
- </body>
-</html>
diff --git a/openviking/console/static/styles.css b/openviking/console/static/styles.css
deleted file mode 100644
index 64cdebd8b..000000000
--- a/openviking/console/static/styles.css
+++ /dev/null
@@ -1,1489 +0,0 @@
-@import url("https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap");
-
-:root {
- color-scheme: dark;
-
- --sidebar-width: 260px;
- --panel-height: 440px;
- --panel-min-height: 0px;
- --result-min-height: 56px;
- --result-max-height: 360px;
-
- --bg: #12141a;
- --bg-accent: #161922;
- --bg-elevated: #1c2029;
- --bg-hover: #252b37;
-
- --panel: #151820;
- --panel-strong: #1a1f29;
- --card: #1b1f28;
- --surface-soft: rgba(255, 255, 255, 0.02);
-
- --text: #e7e8ec;
- --text-strong: #fafafa;
- --muted: #a0a5b1;
- --muted-soft: #7e8697;
-
- --border: #2f3543;
- --border-strong: #474f62;
-
- --accent: #ff5c5c;
- --accent-hover: #ff6f6f;
- --accent-subtle: rgba(255, 92, 92, 0.15);
- --accent-glow: rgba(255, 92, 92, 0.24);
-
- --ok: #30c482;
- --ok-hover: #49d592;
- --warn: #e5af3a;
- --danger: #ef5b6f;
-
- --radius-xs: 6px;
- --radius-sm: 8px;
- --radius-md: 12px;
- --radius-lg: 16px;
- --radius-pill: 999px;
-
- --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.22);
- --shadow-md: 0 8px 18px rgba(0, 0, 0, 0.28);
- --shadow-lg: 0 18px 34px rgba(0, 0, 0, 0.36);
-
- --dur-fast: 130ms;
- --dur-med: 210ms;
- --ease-out: cubic-bezier(0.16, 1, 0.3, 1);
-}
-
-:root[data-theme="light"] {
- color-scheme: light;
-
- --bg: #f6f8fc;
- --bg-accent: #eef2f8;
- --bg-elevated: #ffffff;
- --bg-hover: #e8edf6;
-
- --panel: #f3f6fb;
- --panel-strong: #edf1f9;
- --card: #ffffff;
- --surface-soft: rgba(12, 24, 44, 0.04);
-
- --text: #2a3244;
- --text-strong: #111828;
- --muted: #5a657a;
- --muted-soft: #7b8598;
-
- --border: #d7deeb;
- --border-strong: #bcc7db;
-
- --accent: #dc3e3e;
- --accent-hover: #eb4b4b;
- --accent-subtle: rgba(220, 62, 62, 0.14);
- --accent-glow: rgba(220, 62, 62, 0.2);
-
- --ok: #198a57;
- --ok-hover: #117548;
- --warn: #b98516;
- --danger: #d63f55;
-
- --shadow-sm: 0 1px 2px rgba(6, 18, 38, 0.08);
- --shadow-md: 0 10px 22px rgba(6, 18, 38, 0.11);
- --shadow-lg: 0 18px 38px rgba(6, 18, 38, 0.14);
-}
-
-* {
- box-sizing: border-box;
-}
-
-html,
-body {
- height: 100%;
-}
-
-body {
- margin: 0;
- font-family: "Space Grotesk", "Segoe UI", "Noto Sans", sans-serif;
- color: var(--text);
- background:
- radial-gradient(1100px 600px at -20% -25%, rgba(255, 92, 92, 0.14), transparent 58%),
- radial-gradient(900px 620px at 122% -18%, rgba(255, 163, 96, 0.11), transparent 58%),
- linear-gradient(145deg, #10131a 0%, var(--bg) 54%);
- -webkit-font-smoothing: antialiased;
- text-rendering: optimizeLegibility;
-}
-
-:root[data-theme="light"] body {
- background:
- radial-gradient(1000px 600px at -22% -22%, rgba(220, 62, 62, 0.09), transparent 60%),
- radial-gradient(900px 650px at 120% -20%, rgba(176, 74, 74, 0.08), transparent 60%),
- linear-gradient(145deg, #f0f4fa 0%, var(--bg) 55%);
-}
-
-h1,
-h2,
-h3 {
- margin: 0;
-}
-
-p {
- margin: 0;
-}
-
-.workspace {
- height: 100vh;
- display: flex;
- flex-direction: column;
-}
-
-@supports (height: 100dvh) {
- .workspace {
- height: 100dvh;
- }
-}
-
-.topbar {
- min-height: 60px;
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 14px;
- padding: 12px 18px;
- border-bottom: 1px solid var(--border);
- background: rgba(18, 20, 26, 0.88);
- backdrop-filter: blur(8px);
- position: relative;
- z-index: 20;
-}
-
-:root[data-theme="light"] .topbar {
- background: rgba(246, 248, 252, 0.9);
-}
-
-.topbar-left,
-.topbar-right {
- display: flex;
- align-items: center;
- gap: 10px;
- min-width: 0;
-}
-
-.topbar-result-toggle {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- min-height: 0;
- padding: 5px 10px;
- border: 1px solid var(--border);
- border-radius: var(--radius-pill);
- background: var(--panel-strong);
- color: var(--muted);
- font-size: 11px;
- font-weight: 600;
- letter-spacing: 0.02em;
- text-transform: none;
- box-shadow: none;
-}
-
-.topbar-result-toggle:hover {
- border-color: var(--border-strong);
- background: var(--bg-hover);
- color: var(--text-strong);
-}
-
-.brand {
- display: flex;
- flex-direction: column;
- gap: 2px;
- min-width: 0;
-}
-
-.brand-title {
- font-size: 15px;
- letter-spacing: 0.01em;
- font-weight: 700;
- color: var(--text-strong);
- white-space: nowrap;
-}
-
-.brand-subtitle {
- font-size: 11px;
- letter-spacing: 0.08em;
- text-transform: uppercase;
- color: var(--muted-soft);
-}
-
-.icon-btn {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- border: 1px solid var(--border);
- width: 34px;
- height: 34px;
- padding: 0;
- border-radius: var(--radius-sm);
- background: var(--panel-strong);
- color: var(--muted);
- line-height: 1;
- cursor: pointer;
- transition:
- border-color var(--dur-fast) var(--ease-out),
- color var(--dur-fast) var(--ease-out),
- background var(--dur-fast) var(--ease-out);
-}
-
-.icon-btn:hover {
- color: var(--text-strong);
- border-color: var(--border-strong);
- background: var(--bg-hover);
-}
-
-.pill,
-.badge {
- display: inline-flex;
- align-items: center;
- gap: 7px;
- border: 1px solid var(--border);
- border-radius: var(--radius-pill);
- padding: 6px 11px;
- font-size: 12px;
- background: var(--panel-strong);
- color: var(--muted);
-}
-
-.badge {
- font-family: "JetBrains Mono", "SF Mono", Consolas, monospace;
-}
-
-.badge.write {
- border-color: rgba(48, 196, 130, 0.4);
- color: var(--ok);
- background: rgba(48, 196, 130, 0.12);
-}
-
-.badge-soft {
- color: var(--muted);
- border-color: var(--border);
-}
-
-.statusDot {
- width: 7px;
- height: 7px;
- border-radius: 50%;
- background: var(--muted-soft);
-}
-
-.statusDot.ok {
- background: var(--ok);
- box-shadow: 0 0 0 3px rgba(48, 196, 130, 0.18);
-}
-
-.theme-toggle {
- display: inline-flex;
- align-items: center;
- border: 1px solid var(--border);
- border-radius: var(--radius-pill);
- padding: 2px;
- background: var(--panel-strong);
-}
-
-.theme-btn {
- border: 0;
- border-radius: var(--radius-pill);
- padding: 5px 10px;
- font-size: 11px;
- letter-spacing: 0.02em;
- font-weight: 600;
- color: var(--muted);
- background: transparent;
- cursor: pointer;
- transition:
- color var(--dur-fast) var(--ease-out),
- background var(--dur-fast) var(--ease-out);
-}
-
-.theme-btn.active {
- color: #fff;
- background: var(--accent);
-}
-
-.shell-body {
- flex: 1;
- min-height: 0;
- display: grid;
- grid-template-columns: var(--sidebar-width) 8px minmax(0, 1fr);
- transition: grid-template-columns var(--dur-med) var(--ease-out);
-}
-
-.shell.shell--nav-collapsed .shell-body {
- grid-template-columns: 0 0 minmax(0, 1fr);
-}
-
-.sidebar {
- min-height: 0;
- overflow: auto;
- padding: 16px 12px;
- border-right: 1px solid var(--border);
- background: linear-gradient(180deg, rgba(255, 255, 255, 0.02), rgba(255, 255, 255, 0));
-}
-
-:root[data-theme="light"] .sidebar {
- background: linear-gradient(180deg, rgba(255, 255, 255, 0.58), rgba(255, 255, 255, 0));
-}
-
-.shell.shell--nav-collapsed .sidebar {
- opacity: 0;
- pointer-events: none;
- overflow: hidden;
-}
-
-.nav-groups {
- display: flex;
- flex-direction: column;
- gap: 14px;
-}
-
-.nav-group {
- display: flex;
- flex-direction: column;
- gap: 6px;
-}
-
-.nav-group-title {
- font-size: 11px;
- text-transform: uppercase;
- letter-spacing: 0.11em;
- color: var(--muted-soft);
- padding: 0 8px;
-}
-
-.tab.nav-item {
- width: 100%;
- text-align: left;
- border: 1px solid transparent;
- border-radius: var(--radius-md);
- padding: 10px 12px;
- background: transparent;
- color: var(--muted);
- cursor: pointer;
- font-weight: 600;
- letter-spacing: 0.01em;
- transition:
- color var(--dur-fast) var(--ease-out),
- border-color var(--dur-fast) var(--ease-out),
- background var(--dur-fast) var(--ease-out),
- transform var(--dur-fast) var(--ease-out);
-}
-
-.tab.nav-item:hover {
- color: var(--text-strong);
- border-color: var(--border);
- background: var(--surface-soft);
- transform: translateX(1px);
-}
-
-.tab.nav-item.active {
- color: var(--text-strong);
- border-color: rgba(255, 92, 92, 0.34);
- background: linear-gradient(90deg, rgba(255, 92, 92, 0.22), rgba(255, 92, 92, 0.06));
-}
-
-.resizer {
- position: relative;
- border: 0;
- background: rgba(255, 255, 255, 0.08);
- transition: background var(--dur-fast) var(--ease-out);
-}
-
-:root[data-theme="light"] .resizer {
- background: rgba(20, 31, 57, 0.12);
-}
-
-.resizer:hover {
- background: rgba(255, 92, 92, 0.5);
-}
-
-.resizer-vertical {
- cursor: col-resize;
-}
-
-.resizer-horizontal {
- height: 8px;
- cursor: row-resize;
- border-radius: var(--radius-pill);
- background: var(--surface-soft);
- border: 1px solid transparent;
- transition:
- background var(--dur-fast) var(--ease-out),
- border-color var(--dur-fast) var(--ease-out);
-}
-
-.resizer-horizontal:hover {
- background: color-mix(in srgb, var(--surface-soft) 45%, var(--accent-subtle));
- border-color: var(--border);
-}
-
-.content-area {
- min-height: 0;
- min-width: 0;
- padding: 12px;
-}
-
-.content {
- height: 100%;
- min-height: 0;
- display: grid;
- align-content: start;
- grid-template-rows:
- minmax(0, var(--panel-height))
- 8px
- minmax(var(--result-min-height), 1fr);
- gap: 10px;
-}
-
-.shell.shell--result-collapsed .content {
- grid-template-rows:
- minmax(0, var(--panel-height))
- 8px
- minmax(0, 0);
-}
-
-.shell.shell--result-collapsed .result-card {
- display: none;
-}
-
-.shell.shell--result-empty .content {
- grid-template-rows:
- minmax(0, var(--panel-height))
- minmax(var(--result-min-height), 1fr);
-}
-
-.shell.shell--result-empty #outputResizer {
- display: none;
-}
-
-.panel-stack {
- min-height: 0;
- display: flex;
- height: var(--panel-height);
- overflow: auto;
-}
-
-.panel {
- display: none;
- min-height: 0;
- overflow: auto;
- padding: 14px;
- gap: 10px;
- border: 1px solid var(--border);
- border-radius: var(--radius-lg);
- background: linear-gradient(170deg, rgba(255, 255, 255, 0.02), rgba(255, 255, 255, 0.01));
- box-shadow: var(--shadow-md);
-}
-
-.panel.active {
- display: flex;
- flex-direction: column;
- flex: 1;
- min-width: 0;
-}
-
-.panel > h2 {
- font-size: 12px;
- letter-spacing: 0.1em;
- text-transform: uppercase;
- color: var(--muted-soft);
- margin-bottom: 12px;
-}
-
-.row {
- display: flex;
- align-items: center;
- gap: 8px;
-}
-
-.row.wrap {
- flex-wrap: wrap;
-}
-
-.checks {
- gap: 12px;
-}
-
-.check-item {
- display: inline-flex;
- align-items: center;
- gap: 6px;
- color: var(--muted);
- font-size: 12px;
-}
-
-label {
- font-size: 12px;
- color: var(--muted-soft);
-}
-
-.find-controls {
- display: grid;
- grid-template-columns: minmax(0, 1fr) 120px;
- gap: 10px;
- align-items: end;
-}
-
-.find-field {
- min-width: 0;
-}
-
-.find-field-query {
- grid-column: 1 / -1;
-}
-
-.find-field label {
- margin-top: 0;
-}
-
-.find-field-limit input {
- text-align: center;
-}
-
-input,
-textarea,
-button,
-select,
-pre,
-.badge,
-.tenant-table,
-.find-table,
-.fs-table {
- font-family: "JetBrains Mono", "SF Mono", Menlo, Consolas, monospace;
-}
-
-input,
-textarea,
-select,
-button {
- border: 1px solid var(--border);
- border-radius: var(--radius-sm);
- color: var(--text);
- background: var(--bg-elevated);
- padding: 8px 10px;
- transition:
- border-color var(--dur-fast) var(--ease-out),
- box-shadow var(--dur-fast) var(--ease-out),
- background var(--dur-fast) var(--ease-out),
- color var(--dur-fast) var(--ease-out);
-}
-
-input,
-textarea,
-select {
- width: 100%;
-}
-
-textarea {
- min-height: 70px;
- resize: vertical;
-}
-
-input::placeholder,
-textarea::placeholder {
- color: var(--muted-soft);
-}
-
-button {
- cursor: pointer;
- font-weight: 600;
- color: var(--text-strong);
- background: linear-gradient(180deg, rgba(255, 92, 92, 0.17), rgba(255, 92, 92, 0.08));
- border-color: rgba(255, 92, 92, 0.36);
-}
-
-button:hover {
- border-color: rgba(255, 92, 92, 0.56);
- background: linear-gradient(180deg, rgba(255, 92, 92, 0.24), rgba(255, 92, 92, 0.11));
-}
-
-button.ghost {
- color: var(--text);
- border-color: var(--border);
- background: linear-gradient(180deg, rgba(255, 255, 255, 0.06), rgba(255, 255, 255, 0.02));
-}
-
-button.ghost:hover {
- border-color: var(--border-strong);
- background: var(--bg-hover);
-}
-
-button.danger {
- border-color: rgba(239, 91, 111, 0.54);
- background: linear-gradient(180deg, rgba(239, 91, 111, 0.27), rgba(239, 91, 111, 0.12));
- color: #ffd7dd;
-}
-
-button.tenant-create-btn {
- color: #fff8f8;
- border-color: var(--accent);
- background: linear-gradient(180deg, var(--accent-hover), var(--accent));
- box-shadow: 0 10px 22px var(--accent-glow);
-}
-
-button.tenant-create-btn:hover {
- border-color: var(--accent-hover);
- background: linear-gradient(180deg, #ff7a7a, var(--accent-hover));
-}
-
-:root[data-theme="light"] button.tenant-create-btn {
- color: #ffffff;
- box-shadow: 0 10px 18px rgba(220, 62, 62, 0.2);
-}
-
-:root[data-theme="light"] button.tenant-create-btn:hover {
- background: linear-gradient(180deg, #f05656, var(--accent-hover));
-}
-
-button:disabled {
- opacity: 0.5;
- cursor: not-allowed;
-}
-
-button:focus-visible,
-input:focus-visible,
-textarea:focus-visible,
-select:focus-visible,
-.tab:focus-visible,
-.theme-btn:focus-visible,
-.icon-btn:focus-visible {
- outline: none;
- border-color: var(--accent);
- box-shadow: 0 0 0 3px var(--accent-subtle);
-}
-
-.muted {
- color: var(--muted);
- font-size: 12px;
-}
-
-.list {
- margin: 0;
- padding: 0;
- list-style: none;
- border: 1px solid var(--border);
- border-radius: var(--radius-md);
- overflow: hidden;
- background: var(--surface-soft);
-}
-
-.list li {
- border-bottom: 1px solid var(--border);
-}
-
-.list li:last-child {
- border-bottom: 0;
-}
-
-.list .row-item,
-.list button {
- width: 100%;
- text-align: left;
- border: 0;
- border-radius: 0;
- padding: 10px 12px;
- background: transparent;
- color: var(--text);
-}
-
-.list button:hover {
- background: var(--bg-hover);
-}
-
-.tenant-layout {
- display: grid;
- gap: 12px;
- grid-template-columns: minmax(300px, 1fr) minmax(360px, 1.2fr);
- min-height: 0;
-}
-
-.tenant-pane {
- min-height: 0;
- display: flex;
- flex-direction: column;
- gap: 8px;
- padding: 10px;
- border: 1px solid var(--border);
- border-radius: var(--radius-md);
- background: var(--surface-soft);
-}
-
-.tenant-pane-head {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 8px;
-}
-
-.tenant-pane h3 {
- font-size: 11px;
- letter-spacing: 0.08em;
- text-transform: uppercase;
- color: var(--muted-soft);
-}
-
-.tenant-inline-form {
- align-items: stretch;
-}
-
-.tenant-inline-form > * {
- min-width: 0;
-}
-
-.tenant-inline-form input:first-child {
- flex: 1.2;
-}
-
-.tenant-inline-form input:nth-child(2),
-.tenant-inline-form select {
- flex: 1;
-}
-
-.tenant-table-wrap,
-.find-table-wrap,
-.fs-table-wrap {
- min-height: 0;
- overflow: auto;
- border: 1px solid var(--border);
- border-radius: var(--radius-md);
- background: rgba(0, 0, 0, 0.08);
-}
-
-:root[data-theme="light"] .tenant-table-wrap,
-:root[data-theme="light"] .find-table-wrap,
-:root[data-theme="light"] .fs-table-wrap {
- background: rgba(255, 255, 255, 0.7);
-}
-
-.tenant-table,
-.find-table,
-.fs-table {
- width: 100%;
- border-collapse: collapse;
- font-size: 12px;
-}
-
-.tenant-table {
- min-width: 620px;
-}
-
-.find-table {
- min-width: 720px;
-}
-
-.fs-table {
- min-width: 1140px;
-}
-
-.tenant-table th,
-.tenant-table td,
-.find-table th,
-.find-table td,
-.fs-table th,
-.fs-table td {
- border-bottom: 1px solid var(--border);
- text-align: left;
-}
-
-.tenant-table th,
-.find-table th,
-.fs-table th {
- position: sticky;
- top: 0;
- z-index: 1;
- background: var(--panel-strong);
- padding: 8px 10px;
-}
-
-.tenant-table td,
-.find-table td,
-.fs-table td {
- padding: 9px 10px;
- color: var(--text);
- vertical-align: top;
-}
-
-.tenant-table tbody tr:last-child td,
-.find-table tbody tr:last-child td,
-.fs-table tbody tr:last-child td {
- border-bottom: 0;
-}
-
-.tenant-sort-btn,
-.find-sort-btn,
-.fs-sort-btn {
- width: 100%;
- border: 0;
- border-radius: 0;
- padding: 0;
- background: transparent;
- color: var(--muted);
- text-align: left;
- letter-spacing: 0.03em;
- font-size: 12px;
- cursor: pointer;
-}
-
-.tenant-sort-btn:hover,
-.find-sort-btn:hover,
-.fs-sort-btn:hover,
-.fs-sort-btn.active {
- color: var(--text-strong);
-}
-
-.fs-col-action {
- width: 42px;
- min-width: 42px;
- text-align: center;
- padding: 6px 8px !important;
-}
-
-.fs-uri-btn,
-.tenant-account-btn {
- border: 0;
- border-radius: 0;
- background: transparent;
- color: #ff8e8e;
- padding: 0;
- text-align: left;
- font-weight: 600;
-}
-
-:root[data-theme="light"] .fs-uri-btn,
-:root[data-theme="light"] .tenant-account-btn {
- color: #b33636;
-}
-
-.fs-uri-btn:hover,
-.tenant-account-btn:hover {
- color: var(--accent-hover);
- text-decoration: underline;
-}
-
-.fs-open-btn {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- width: 100%;
- border: 0;
- border-radius: 0;
- background: transparent;
- color: var(--ok);
- padding: 0;
- text-align: left;
- font-weight: 700;
-}
-
-.fs-open-btn:hover {
- color: var(--ok-hover);
- text-decoration: underline;
-}
-
-.fs-col-uri,
-.fs-col-size,
-.fs-col-dir,
-.fs-col-mod-time {
- white-space: nowrap;
-}
-
-.fs-col-abstract {
- min-width: 300px;
-}
-
-#fsColUri {
- width: 360px;
- min-width: 220px;
-}
-
-#fsColAction {
- width: 42px;
- min-width: 42px;
- max-width: 42px;
- padding: 8px 8px;
-}
-
-#fsColSize {
- width: 120px;
- min-width: 90px;
-}
-
-#fsColIsDir {
- width: 110px;
- min-width: 90px;
-}
-
-#fsColModTime {
- width: 220px;
- min-width: 160px;
-}
-
-#fsColAbstract {
- width: 340px;
- min-width: 220px;
-}
-
-.fs-col-resizer {
- position: absolute;
- top: 7px;
- right: -4px;
- width: 8px;
- bottom: 7px;
- cursor: col-resize;
- z-index: 3;
- touch-action: none;
-}
-
-.fs-col-resizer::before {
- content: "";
- position: absolute;
- left: 3px;
- top: 0;
- bottom: 0;
- width: 2px;
- border-radius: var(--radius-pill);
- background: rgba(255, 255, 255, 0.3);
-}
-
-:root[data-theme="light"] .fs-col-resizer::before {
- background: rgba(26, 42, 74, 0.28);
-}
-
-.fs-col-resizer:hover::before {
- background: var(--accent);
-}
-
-.tenant-actions {
- display: flex;
- align-items: center;
- flex-wrap: wrap;
- gap: 6px;
-}
-
-.tenant-actions button {
- padding: 4px 8px;
- font-size: 11px;
-}
-
-.tenant-role-select {
- max-width: 130px;
- padding: 5px 8px;
- font-size: 11px;
-}
-
-.tenant-row-selected td {
- background: rgba(255, 92, 92, 0.12);
-}
-
-.tenant-empty,
-.find-empty,
-.fs-empty {
- color: var(--muted-soft);
-}
-
-.find-cell-expandable {
- min-width: 240px;
-}
-
-.find-col-abstract {
- width: 300px;
- max-width: 300px;
- overflow: hidden;
-}
-
-.find-cell-content {
- display: grid;
- grid-template-columns: minmax(0, 1fr) auto;
- align-items: center;
- gap: 8px;
- min-width: 0;
- width: 100%;
- max-width: 100%;
-}
-
-.find-cell-content.expanded {
- align-items: flex-start;
-}
-
-.find-cell-text {
- flex: 1;
- min-width: 0;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
-}
-
-.find-cell-text.expanded {
- overflow: visible;
- white-space: normal;
- word-break: break-word;
-}
-
-.find-cell-expand-btn {
- flex-shrink: 0;
- border: 0;
- border-radius: 0;
- padding: 0 0 0 2px;
- background: transparent;
- color: var(--muted-soft);
- font-size: 10px;
- font-weight: 600;
- white-space: nowrap;
- letter-spacing: 0;
- opacity: 0.82;
-}
-
-.find-cell-expand-btn:hover {
- color: var(--text);
- text-decoration: underline;
- opacity: 1;
-}
-
-.tenant-modal {
- position: fixed;
- inset: 0;
- z-index: 40;
- display: flex;
- align-items: center;
- justify-content: center;
- padding: 16px;
- background: rgba(12, 14, 18, 0.56);
- backdrop-filter: blur(2px);
-}
-
-.tenant-modal[hidden] {
- display: none;
-}
-
-.tenant-modal-card {
- width: min(560px, 100%);
- display: flex;
- flex-direction: column;
- gap: 10px;
- padding: 14px;
- border: 1px solid var(--border);
- border-radius: var(--radius-md);
- background: var(--card);
- box-shadow: var(--shadow-lg);
-}
-
-.tenant-modal-card h3 {
- font-size: 13px;
- letter-spacing: 0.06em;
- text-transform: uppercase;
- color: var(--muted-soft);
-}
-
-.tenant-error {
- color: var(--danger);
- font-size: 12px;
-}
-
-.result-card {
- min-height: calc(var(--result-min-height) + 44px);
- height: 100%;
- display: flex;
- flex-direction: column;
- gap: 10px;
- overflow: hidden;
- padding: 12px;
- border: 1px solid var(--border);
- border-radius: var(--radius-lg);
- background: linear-gradient(160deg, rgba(255, 255, 255, 0.03), rgba(255, 255, 255, 0));
- box-shadow: var(--shadow-md);
-}
-
-.result-card--empty {
- background: rgba(255, 255, 255, 0.01);
-}
-
-.result-head {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 10px;
-}
-
-.result-head h2 {
- font-size: 12px;
- letter-spacing: 0.1em;
- text-transform: uppercase;
- color: var(--muted-soft);
-}
-
-pre {
- margin: 0;
- flex: 1 1 auto;
- min-height: var(--result-min-height);
- padding: 12px;
- border-radius: var(--radius-md);
- border: 1px solid var(--border);
- background: rgba(0, 0, 0, 0.24);
- color: var(--text);
- overflow: auto;
- white-space: pre-wrap;
- word-break: break-word;
- font-size: 12px;
- line-height: 1.5;
-}
-
-.result-card--empty pre {
- display: flex;
- align-items: center;
- justify-content: center;
- min-height: var(--result-min-height);
- background: transparent;
- border-style: dashed;
- color: var(--muted-soft);
-}
-
-#output[data-empty="true"]::before {
- content: "No result yet.";
- letter-spacing: 0.02em;
-}
-
-:root[data-theme="light"] pre {
- background: rgba(255, 255, 255, 0.8);
-}
-
-:root[data-theme="light"] .result-card--empty pre {
- background: transparent;
-}
-
-body.dragging-sidebar,
-body.dragging-sidebar *,
-body.dragging-fs-column,
-body.dragging-fs-column * {
- cursor: col-resize !important;
- user-select: none;
-}
-
-body.dragging-output,
-body.dragging-output * {
- cursor: row-resize !important;
- user-select: none;
-}
-
-::-webkit-scrollbar {
- width: 9px;
- height: 9px;
-}
-
-::-webkit-scrollbar-track {
- background: transparent;
-}
-
-::-webkit-scrollbar-thumb {
- border-radius: var(--radius-pill);
- border: 2px solid transparent;
- background: rgba(255, 255, 255, 0.2);
-}
-
-:root[data-theme="light"] ::-webkit-scrollbar-thumb {
- background: rgba(28, 40, 63, 0.22);
-}
-
-::-webkit-scrollbar-thumb:hover {
- background: rgba(255, 92, 92, 0.55);
-}
-
-.fs-toolbar {
- display: flex;
- align-items: center;
- gap: 6px;
- flex-shrink: 0;
-}
-
-.fs-toolbar input {
- flex: 1;
- width: 0;
- min-width: 0;
-}
-
-.fs-toolbar-nav {
- display: flex;
- align-items: center;
- gap: 2px;
- flex-shrink: 0;
-}
-
-.fs-nav-btn {
- width: 30px;
- height: 30px;
- padding: 0;
- font-size: 15px;
- display: flex;
- align-items: center;
- justify-content: center;
- font-family: "Space Grotesk", "Segoe UI", sans-serif;
-}
-
-.fs-toolbar-controls {
- display: flex;
- align-items: center;
- gap: 6px;
- flex-shrink: 0;
-}
-
-.fs-view-toggle {
- display: flex;
- align-items: center;
- gap: 0;
- border: 1px solid var(--border);
- border-radius: var(--radius-sm);
- overflow: hidden;
-}
-
-.fs-view-toggle button {
- border: 0;
- border-radius: 0;
- padding: 5px 10px;
- font-size: 11px;
- background: transparent;
- color: var(--muted);
-}
-
-.fs-view-toggle button:hover {
- background: var(--bg-hover);
- color: var(--text-strong);
-}
-
-.fs-view-toggle button.active {
- background: var(--accent);
- color: #fff;
- border-color: var(--accent);
-}
-
-.add-resource-mode-toggle {
- display: flex;
- align-items: center;
- gap: 4px;
- width: 100%;
- margin-bottom: 12px;
- border: 1px solid var(--border);
- border-radius: var(--radius-sm);
- padding: 4px;
- background: var(--panel);
-}
-
-.add-resource-mode-toggle button {
- flex: 1;
- border: 1px solid transparent;
- border-radius: calc(var(--radius-sm) - 2px);
- min-height: 34px;
- padding: 7px 12px;
- font-size: 12px;
- font-weight: 700;
- letter-spacing: 0.02em;
- background: transparent;
- color: var(--muted);
- box-shadow: none;
-}
-
-.add-resource-mode-toggle button:hover {
- background: var(--bg-hover);
- color: var(--text-strong);
-}
-
-.add-resource-mode-toggle button.active {
- background: var(--accent);
- color: #fff;
- border-color: rgba(255, 255, 255, 0.08);
- box-shadow: var(--shadow-sm);
-}
-
-.add-resource-input-pane[hidden] {
- display: none;
-}
-
-.add-resource-input-pane {
- margin-bottom: 4px;
-}
-
-@media (max-width: 1200px) {
- .find-controls {
- grid-template-columns: minmax(0, 1fr) 120px;
- }
-}
-
-@media (max-width: 720px) {
- .find-controls {
- grid-template-columns: 1fr;
- }
-
- .find-field-query,
- .find-field-limit {
- grid-column: auto;
- }
-}
-
-.fs-tree {
- overflow: auto;
- border: 1px solid var(--border);
- border-radius: var(--radius-md);
- background: rgba(0, 0, 0, 0.08);
- padding: 6px 0;
- min-height: 80px;
- flex: 1;
-}
-
-:root[data-theme="light"] .fs-tree {
- background: rgba(255, 255, 255, 0.7);
-}
-
-.fs-tree-item {
- display: flex;
- align-items: center;
- gap: 4px;
- padding: 3px 10px;
- font-size: 12px;
- cursor: pointer;
- user-select: none;
- font-family: "JetBrains Mono", "SF Mono", Menlo, Consolas, monospace;
-}
-
-.fs-tree-item:hover {
- background: var(--bg-hover);
-}
-
-.fs-tree-toggle {
- flex-shrink: 0;
- width: 14px;
- color: var(--muted);
- font-size: 10px;
-}
-
-.fs-tree-name {
- flex: 1;
- color: var(--text);
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-.fs-tree-item--dir .fs-tree-name {
- color: #ff8e8e;
- font-weight: 600;
-}
-
-:root[data-theme="light"] .fs-tree-item--dir .fs-tree-name {
- color: #b33636;
-}
-
-.fs-tree-info-btn {
- flex-shrink: 0;
- width: 18px;
- border: 0;
- border-radius: 0;
- background: transparent;
- color: var(--ok);
- padding: 0;
- font-size: 12px;
- font-weight: 700;
- cursor: pointer;
- text-align: center;
-}
-
-.fs-tree-info-btn:hover {
- color: var(--ok-hover);
- text-decoration: underline;
-}
-
-@media (max-width: 900px) {
- .topbar {
- padding: 10px 12px;
- min-height: 56px;
- }
-
- .brand-subtitle {
- display: none;
- }
-
- .topbar-right {
- gap: 6px;
- }
-
- .pill {
- display: none;
- }
-
- .shell-body {
- grid-template-columns: minmax(0, 1fr);
- }
-
- .sidebar {
- position: fixed;
- top: 56px;
- left: 0;
- bottom: 0;
- width: min(82vw, 320px);
- border-right: 1px solid var(--border);
- transform: translateX(-104%);
- transition: transform var(--dur-med) var(--ease-out);
- z-index: 35;
- background: var(--panel-strong);
- box-shadow: var(--shadow-lg);
- }
-
- .shell:not(.shell--nav-collapsed) .sidebar {
- transform: translateX(0);
- }
-
- .shell::after {
- content: "";
- position: fixed;
- inset: 56px 0 0 0;
- background: rgba(0, 0, 0, 0.4);
- opacity: 0;
- pointer-events: none;
- transition: opacity var(--dur-med) var(--ease-out);
- z-index: 30;
- }
-
- .shell:not(.shell--nav-collapsed)::after {
- opacity: 1;
- pointer-events: auto;
- }
-
- #sidebarResizer {
- display: none;
- }
-
- .content-area {
- padding: 10px;
- }
-
- .content {
- grid-template-rows:
- auto
- auto
- 6px
- auto;
- }
-
- .panel-stack {
- max-height: min(var(--panel-height), 38vh);
- }
-
- .tenant-layout {
- grid-template-columns: 1fr;
- }
-
- .tenant-inline-form {
- flex-wrap: wrap;
- }
-
- .tenant-inline-form button {
- width: 100%;
- }
-}
-
-@media (prefers-reduced-motion: reduce) {
- *,
- *::before,
- *::after {
- animation: none !important;
- transition: none !important;
- }
-}
diff --git a/openviking/observability/usage_audit/README.md b/openviking/observability/usage_audit/README.md
index 9a0171acf..1c558969b 100644
--- a/openviking/observability/usage_audit/README.md
+++ b/openviking/observability/usage_audit/README.md
@@ -174,7 +174,6 @@ vector filter,也不从历史写入事件累计当前库存。
- `/favicon.ico`
- `/favicon.png`
- `/apple-touch-icon.png`
-- `/console/*`
- `/api/v1/console/*`
## Console BFF API
@@ -375,9 +374,7 @@ curl "http://127.0.0.1:1933/api/v1/console/dashboard/summary" \
openviking/observability/events.py \
openviking/observability/usage_audit \
openviking/server/routers/console.py \
- openviking/console/app.py \
- tests/observability \
- tests/misc/test_console_proxy.py
+ tests/observability
```
## 常见问题
diff --git a/openviking/observability/usage_audit/projection.py b/openviking/observability/usage_audit/projection.py
index 728219a56..6339d5cbc 100644
--- a/openviking/observability/usage_audit/projection.py
+++ b/openviking/observability/usage_audit/projection.py
@@ -272,11 +272,7 @@ def _project_http_request(
def should_skip_audit_route(route: str) -> bool:
"""Return whether an HTTP route should be omitted from product audit."""
- return (
- route in AUDIT_EXCLUDED_ROUTES
- or route.startswith("/console/")
- or route.startswith("/api/v1/console/")
- )
+ return route in AUDIT_EXCLUDED_ROUTES or route.startswith("/api/v1/console/")
def retrieval_operation_for_http(method: str, route: str) -> str | None:
diff --git a/openviking/server/app.py b/openviking/server/app.py
index 35777c9b9..59e6ef5d6 100644
--- a/openviking/server/app.py
+++ b/openviking/server/app.py
@@ -606,19 +606,11 @@ def create_app(
except Exception as e: # noqa: BLE001
logger.warning("Skipping OAuth router registration: %s", e)
- # Web Studio SPA: serve the static bundle when present so the same OV
- # server origin can host the new frontend at /studio. The directory is
- # populated by the docker `web-studio-builder` stage; outside docker, set
- # OPENVIKING_WEB_STUDIO_DIR to a local `web-studio/dist` to enable it.
- # Favicon assets are bundled with web-studio (see web-studio/public/),
- # so the top-level /favicon.* and /mcp/favicon.* routes are served from
- # the same dist directory — no separate server-side static folder.
- _studio_env = os.environ.get("OPENVIKING_WEB_STUDIO_DIR", "").strip()
- if _studio_env:
- _studio_dir = Path(_studio_env)
- else:
- _studio_dir = Path(__file__).resolve().parents[2] / "web-studio" / "dist"
-
+ # Favicon routes — always registered so /favicon.* and /mcp/favicon.* never
+ # 404, even when web-studio isn't bundled. Source files live in
+ # openviking/server/static/ (shipped via package-data, ~30KB total) so they
+ # are available in every pip-install / docker / source-tree scenario.
+ _server_static_dir = Path(__file__).resolve().parent / "static"
_favicon_headers = {"Cache-Control": "public, max-age=86400"}
_favicon_files = {
"/favicon.ico": ("favicon.ico", "image/x-icon"),
@@ -628,21 +620,29 @@ def create_app(
"/mcp/favicon.png": ("favicon-32.png", "image/png"),
"/mcp/apple-touch-icon.png": ("apple-touch-icon.png", "image/png"),
}
- _favicon_source = _studio_dir if _studio_dir.is_dir() else None
- if _favicon_source is not None and all(
- (_favicon_source / fname).is_file() for fname, _ in _favicon_files.values()
- ):
- def _make_favicon_handler(filename: str, media_type: str):
- path = _favicon_source / filename
+ def _make_favicon_handler(filename: str, media_type: str):
+ path = _server_static_dir / filename
- async def _handler():
- return FileResponse(path, media_type=media_type, headers=_favicon_headers)
+ async def _handler():
+ return FileResponse(path, media_type=media_type, headers=_favicon_headers)
- return _handler
+ return _handler
- for _route, (_fname, _mime) in _favicon_files.items():
- app.add_api_route(_route, _make_favicon_handler(_fname, _mime), include_in_schema=False)
+ for _route, (_fname, _mime) in _favicon_files.items():
+ app.add_api_route(_route, _make_favicon_handler(_fname, _mime), include_in_schema=False)
+
+ # Web Studio SPA: serve the static bundle when present so the same OV
+ # server origin can host the new frontend at /studio. The directory is
+ # populated by the docker `web-studio-builder` stage and shipped inside
+ # the openviking python package (see pyproject.toml package-data). Outside
+ # docker, set OPENVIKING_WEB_STUDIO_DIR to a local `web-studio/dist` to
+ # enable a dev build without rebuilding the wheel.
+ _studio_env = os.environ.get("OPENVIKING_WEB_STUDIO_DIR", "").strip()
+ if _studio_env:
+ _studio_dir = Path(_studio_env)
+ else:
+ _studio_dir = Path(__file__).resolve().parent.parent / "web_studio" / "dist"
if _studio_dir.is_dir() and (_studio_dir / "index.html").is_file():
_studio_root = _studio_dir.resolve()
diff --git a/openviking/server/static/apple-touch-icon.png b/openviking/server/static/apple-touch-icon.png
new file mode 100644
index 000000000..5c8385566
Binary files /dev/null and b/openviking/server/static/apple-touch-icon.png differ
diff --git a/openviking/server/static/favicon-32.png b/openviking/server/static/favicon-32.png
new file mode 100644
index 000000000..27c94520b
Binary files /dev/null and b/openviking/server/static/favicon-32.png differ
diff --git a/openviking/console/static/favicon.ico b/openviking/server/static/favicon.ico
similarity index 100%
rename from openviking/console/static/favicon.ico
rename to openviking/server/static/favicon.ico
diff --git a/openviking/web_studio/__init__.py b/openviking/web_studio/__init__.py
new file mode 100644
index 000000000..e38163b2e
--- /dev/null
+++ b/openviking/web_studio/__init__.py
@@ -0,0 +1,11 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Built web-studio assets, populated by the docker web-studio-builder stage.
+
+The actual SPA source lives at the repository root in ``web-studio/``. During
+the docker build the Vite output (``web-studio/dist``) is copied into
+``openviking/web_studio/dist`` so the python wheel ships the bundle as
+package-data. The server resolves ``dist/`` relative to this package at
+runtime; if it is absent (e.g. ``pip install`` without running ``npm run
+build`` first) the /studio routes simply aren't registered.
+"""
diff --git a/pyproject.toml b/pyproject.toml
index c81845a27..7cdbfdf0d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -216,7 +216,8 @@ exclude = ["tests*", "docs*", "examples*"]
[tool.setuptools.package-data]
openviking = [
"prompts/templates/**/*.yaml",
- "console/static/**/*",
+ "server/static/**/*",
+ "web_studio/dist/**/*",
"lib/ragfs_python*.so",
"lib/ragfs_python*.pyd",
"bin/ov",
diff --git a/setup.py b/setup.py
index abfbaa8f6..ad7149d09 100644
--- a/setup.py
+++ b/setup.py
@@ -344,12 +344,9 @@ class OpenVikingBuildExt(build_ext):
with zipfile.ZipFile(str(whl_files[0])) as zf:
for name in zf.namelist():
basename = Path(name).name
- is_ragfs_extension = (
- basename == "ragfs_python.pyd"
- or (
- basename.startswith("ragfs_python.abi3.")
- and basename.endswith((".so", ".pyd"))
- )
+ is_ragfs_extension = basename == "ragfs_python.pyd" or (
+ basename.startswith("ragfs_python.abi3.")
+ and basename.endswith((".so", ".pyd"))
)
if is_ragfs_extension:
target_path = ragfs_lib_dir / basename
@@ -362,7 +359,9 @@ class OpenVikingBuildExt(build_ext):
break
if not extracted:
- message = "Could not find ragfs_python stable-ABI native extension in built wheel."
+ message = (
+ "Could not find ragfs_python stable-ABI native extension in built wheel."
+ )
if require_ragfs_artifact:
raise RuntimeError(message)
print(f"[Warning] {message}")
@@ -492,7 +491,8 @@ setup(
"lib/ragfs_python*.pyd",
"bin/ov",
"bin/ov.exe",
- "console/static/**/*",
+ "server/static/**/*",
+ "web_studio/dist/**/*",
"storage/vectordb/engine/*.abi3.so",
"storage/vectordb/engine/*.pyd",
],
diff --git a/tests/misc/test_console_proxy.py b/tests/misc/test_console_proxy.py
deleted file mode 100644
index 0b56b267b..000000000
--- a/tests/misc/test_console_proxy.py
+++ /dev/null
@@ -1,57 +0,0 @@
-import httpx
-import pytest
-
-from openviking.console.app import create_console_app
-from openviking.console.config import ConsoleConfig
-
-
-async def test_console_bff_proxy_forwards_console_routes():
- async def handler(request: httpx.Request) -> httpx.Response:
- assert request.method == "GET"
- assert request.url.path == "/api/v1/console/dashboard/summary"
- assert request.url.query == b"range=today"
- assert request.headers["x-api-key"] == "test-key"
- return httpx.Response(
- status_code=200,
- json={"status": "ok", "result": {"enabled": True}},
- headers={"x-request-id": "req-console"},
- )
-
- app = create_console_app(
- config=ConsoleConfig(openviking_base_url="http://openviking.test"),
- upstream_transport=httpx.MockTransport(handler),
- )
- transport = httpx.ASGITransport(app=app)
-
- async with httpx.AsyncClient(transport=transport, base_url="http://console.test") as client:
- response = await client.get(
- "/console/api/v1/ov/console/dashboard/summary?range=today",
- headers={"x-api-key": "test-key"},
- )
-
- assert response.status_code == 200
- assert response.headers["x-request-id"] == "req-console"
- assert response.json() == {"status": "ok", "result": {"enabled": True}}
-
-
-async def test_console_bff_proxy_rejects_path_traversal():
- called = False
-
- async def handler(request: httpx.Request) -> httpx.Response:
- nonlocal called
- called = True
- return httpx.Response(status_code=500)
-
- app = create_console_app(
- config=ConsoleConfig(openviking_base_url="http://openviking.test"),
- upstream_transport=httpx.MockTransport(handler),
- )
- transport = httpx.ASGITransport(app=app)
-
- async with httpx.AsyncClient(transport=transport, base_url="http://console.test") as client:
- response = await client.get("/console/api/v1/ov/console/%2e%2e/admin/accounts")
-
- assert response.status_code == 404
- assert called is False
diff --git a/tests/misc/test_console_static_assets.py b/tests/misc/test_console_static_assets.py
deleted file mode 100644
index 28de9ea34..000000000
--- a/tests/misc/test_console_static_assets.py
+++ /dev/null
@@ -1,15 +0,0 @@
-from pathlib import Path
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
-
-
-def _read_text(relative_path: str) -> str:
- return (REPO_ROOT / relative_path).read_text(encoding="utf-8")
-
-
-def test_console_add_resource_payload_uses_to_field():
- app_js = _read_text("openviking/console/static/app.js")
-
- assert "function buildAddResourcePayload()" in app_js
- assert "to: elements.addResourceTarget.value.trim()," in app_js
- assert "target: elements.addResourceTarget.value.trim()," not in app_js
diff --git a/web-studio/public/apple-touch-icon.png b/web-studio/public/apple-touch-icon.png
index 60289db06..5c8385566 100644
Binary files a/web-studio/public/apple-touch-icon.png and b/web-studio/public/apple-touch-icon.png differ
diff --git a/web-studio/public/favicon-32.png b/web-studio/public/favicon-32.png
index 2a1662ed7..27c94520b 100644
Binary files a/web-studio/public/favicon-32.png and b/web-studio/public/favicon-32.png differ