fix(webui): make headless login self-explanatory (#5735)

* fix(webui): guide headless login

* fix(webui): correct SSH handoff and password fallback
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-13 05:01:13 +08:00
1 parent 7cede64f07
commit f8c1f2ede0
15 files changed
+265 -86

No files matched your search

+8 -13
View File
@@ -26,6 +26,7 @@ from nanobot.cli.webui_support import (
_open_webui_browser,
_prepare_webui_bundle_for_gateway,
_print_foreground_port_conflict,
_print_webui_manual_access,
_resolve_webui_config_path,
_tcp_endpoint_reachable,
_warn_webui_bind_scope,
@@ -147,7 +148,7 @@ def webui(
console.print("Configure a provider and model in WebUI Settings → Models.")
try:
changed_webui, generated_bootstrap_secret = _ensure_local_webui_channel(
changed_webui = _ensure_local_webui_channel(
setup_config,
port=port,
yes=yes,
@@ -196,14 +197,8 @@ def webui(
)
if no_open:
console.print("[dim]Browser opening disabled by --no-open.[/dim]")
if generated_bootstrap_secret:
console.print(
"[yellow]A WebUI bootstrap secret was generated and saved in this config.[/yellow]"
)
console.print(
"[dim]Open the WebUI and enter channels.websocket.tokenIssueSecret from "
f"{config_path}, or rerun without --no-open to open the authenticated URL.[/dim]"
)
if not dev:
_print_webui_manual_access(runtime_config, config_path, webui_url)
if not dev:
webui_bundle_mode = _webui_build_mode_for_interactive(yes=yes)
@@ -277,8 +272,8 @@ def webui(
"Restart the gateway if you need it to pick up local source changes: "
f"[cyan]{_gateway_instance_command('restart', config_path=config_path, workspace=workspace)}[/cyan]"
)
if not no_open:
_open_webui_browser(webui_url, wait=False)
if not no_open and not _open_webui_browser(webui_url, wait=False):
_print_webui_manual_access(runtime_config, config_path, webui_url)
if runtime.status().running:
_attach_to_background_gateway(runtime)
else:
@@ -352,8 +347,8 @@ def webui(
raise typer.Exit(1) from exc
return
if not no_open:
_open_webui_browser(webui_url)
if not no_open and not _open_webui_browser(webui_url):
_print_webui_manual_access(runtime_config, config_path, webui_url)
_attach_to_background_gateway(runtime)
finally:
lease.release(wait_for_stop=False)
+85 -11
View File
@@ -1,6 +1,7 @@
"""Shared WebUI setup, URL, health, and browser helpers."""
import os
import shutil
import sys
import time
import webbrowser
@@ -47,6 +48,7 @@ __all__ = [
"_open_webui_browser",
"_prepare_webui_bundle_for_gateway",
"_print_foreground_port_conflict",
"_print_webui_manual_access",
"_print_webui_foreground_lifecycle",
"_resolve_webui_config_path",
"_tcp_endpoint_reachable",
@@ -62,6 +64,8 @@ __all__ = [
console = Console()
_TEXT_ONLY_BROWSERS = frozenset({"elinks", "links", "links2", "lynx", "w3m"})
def _launch_browser(url: str) -> bool:
"""Open *url* and request a foreground browser window."""
@@ -74,6 +78,36 @@ def _launch_browser(url: str) -> bool:
return bool(webbrowser.open(url, new=2, autoraise=True))
def _text_only_browser_name() -> str | None:
"""Return the configured text browser name when it cannot run the WebUI."""
if sys.platform in {"darwin", "win32"}:
return None
try:
browser = webbrowser.get()
except webbrowser.Error:
return None
command = str(getattr(browser, "name", "") or "").strip()
if not command:
return None
import shlex
try:
executable = Path(shlex.split(command)[0])
except (IndexError, ValueError):
return None
names = {executable.name.lower()}
resolved_executable = Path(shutil.which(str(executable)) or executable)
try:
names.add(resolved_executable.resolve(strict=False).name.lower())
except OSError:
pass
return next((name for name in names if name in _TEXT_ONLY_BROWSERS), None)
def _launch_macos_browser(url: str) -> bool:
"""Deliver URLs through Launch Services, never a credential-bearing argv."""
import ctypes
@@ -209,8 +243,8 @@ def _validate_gateway_startup(config: Config) -> str | None:
)
console.print(
Text(
f"If prompted, enter the configured channels.websocket.{secret_key} "
f"value (see {config_path}).",
f"If prompted, enter the WebUI password from "
f"channels.websocket.{secret_key} in {config_path}.",
style="dim",
)
)
@@ -309,27 +343,29 @@ def _ensure_local_webui_channel(
*,
port: int | None,
yes: bool,
) -> tuple[bool, bool]:
) -> bool:
"""Enable the local WebUI channel with safe localhost defaults."""
from nanobot.channels.websocket.runtime import WebSocketConfig
current: Any = getattr(config.channels, "websocket", None) or {}
model = WebSocketConfig.model_validate(current)
changed = False
generated_secret = False
needs_enable = not model.enabled
needs_port = port is not None and model.port != port
needs_secret = not model.token_issue_secret.strip() and not model.token.strip()
if not needs_enable and not needs_port and not needs_secret:
return False, False
return False
target_port = port if port is not None else model.port
console.print()
console.print("[bold]Local WebUI setup[/bold]")
console.print(f" URL: [cyan]http://127.0.0.1:{target_port}[/cyan]")
console.print(" Bind: [cyan]127.0.0.1 only[/cyan] (not exposed to your LAN)")
console.print(" Auth: generated WebUI bootstrap secret stored in config")
if needs_secret:
console.print(" WebUI password: will be generated and stored in config")
else:
console.print(" WebUI password: already stored in config")
console.print(
" LAN access requires an explicit host change plus a WebUI password in config."
)
@@ -352,10 +388,9 @@ def _ensure_local_webui_channel(
model.token_issue_secret = secrets.token_urlsafe(32)
changed = True
generated_secret = True
setattr(config.channels, "websocket", model.model_dump(by_alias=True, exclude_none=True))
return changed, generated_secret
return changed
def _warn_webui_bind_scope(config: Config) -> None:
@@ -464,18 +499,57 @@ def _print_foreground_port_conflict(
)
def _open_webui_browser(url: str, *, wait: bool = True) -> None:
def _open_webui_browser(url: str, *, wait: bool = True) -> bool:
"""Open the WebUI in the user's default browser, with a copyable fallback."""
if wait:
_wait_for_webui(url)
display_url = _webui_display_url(url)
text_browser = _text_only_browser_name()
if text_browser:
console.print(
f"[yellow]The configured browser ({escape(text_browser)}) cannot run the WebUI "
"because it does not support JavaScript.[/yellow]"
)
return False
try:
if _launch_browser(url):
console.print(f"[green]✓[/green] Opened WebUI: [cyan]{display_url}[/cyan]")
return True
else:
console.print(f"[yellow]Could not open browser; visit {display_url}[/yellow]")
console.print("[yellow]Could not open a browser automatically.[/yellow]")
except Exception as exc:
console.print(f"[yellow]Could not open browser ({exc}); visit {display_url}[/yellow]")
console.print(f"[yellow]Could not open a browser automatically ({escape(str(exc))}).[/yellow]")
return False
def _print_webui_manual_access(config: Config, config_path: Path, url: str) -> None:
"""Print a complete local or SSH-tunnel browser handoff without exposing credentials."""
from urllib.parse import urlparse
browser_url = url.split("/#/", 1)[0]
parsed = urlparse(browser_url)
port = parsed.port or (443 if parsed.scheme == "https" else 80)
tunnel_host = _host_for_local_browser(parsed.hostname or "127.0.0.1")
tunnel_url = f"{parsed.scheme}://127.0.0.1:{port}"
ws_cfg = _webui_config_dict(config)
password_key = (
"tokenIssueSecret" if str(ws_cfg.get("tokenIssueSecret") or "").strip() else "token"
)
console.print()
console.print("[bold]Open the WebUI manually[/bold]")
console.print(f" WebUI: [cyan]{browser_url}[/cyan]")
console.print(
" WebUI password: "
f"[cyan]channels.websocket.{password_key}[/cyan] in [cyan]{config_path}[/cyan]"
)
console.print()
console.print("If nanobot is running on another machine, create an SSH tunnel from yours:")
console.print(
f" [cyan]ssh -N -L {port}:{tunnel_host}:{port} <user>@<server>[/cyan]"
)
console.print("Replace [cyan]<user>[/cyan] and [cyan]<server>[/cyan] and keep the tunnel open.")
console.print(f"Then open [cyan]{tunnel_url}[/cyan] on your computer.")
def _print_webui_foreground_lifecycle(*, attached: bool) -> None:
+74 -7
View File
@@ -2232,9 +2232,9 @@ def test_webui_yes_creates_config_and_enables_local_websocket(
assert options.config_path == str(config_file.resolve(strict=False))
assert options.workspace == str(workspace.resolve(strict=False))
compact_output = re.sub(r"\s+", " ", _strip_ansi(result.stdout))
assert "bootstrap secret was generated" in compact_output
assert "Open the WebUI manually" in compact_output
assert "channels.websocket.tokenIssueSecret" in compact_output
assert "rerun without --no-open" in compact_output
assert "ssh -N -L 8899:127.0.0.1:8899 <user>@<server>" in compact_output
assert seen["lease_release_wait_for_stop"] is False
assert "stop_timeout" not in seen
@@ -2540,13 +2540,14 @@ def test_webui_yes_opens_settings_for_incomplete_custom_model_setup(
def test_open_webui_browser_redacts_bootstrap_secret(monkeypatch, capsys) -> None:
opened: list[str] = []
url = "http://127.0.0.1:8765/#/?bootstrapSecret=super-secret"
monkeypatch.setattr(cli_webui_support, "_text_only_browser_name", lambda: None)
monkeypatch.setattr(
cli_webui_support,
"_launch_browser",
lambda value: opened.append(value) or True,
)
cli_webui_support._open_webui_browser(url, wait=False)
assert cli_webui_support._open_webui_browser(url, wait=False) is True
assert opened == [url]
output = _strip_ansi(capsys.readouterr().out)
@@ -2555,14 +2556,80 @@ def test_open_webui_browser_redacts_bootstrap_secret(monkeypatch, capsys) -> Non
def test_open_webui_browser_reports_launch_failure(monkeypatch, capsys) -> None:
monkeypatch.setattr(cli_webui_support, "_text_only_browser_name", lambda: None)
monkeypatch.setattr(cli_webui_support, "_launch_browser", lambda _value: False)
cli_webui_support._open_webui_browser("http://127.0.0.1:8765/", wait=False)
assert "Could not open browser; visit http://127.0.0.1:8765/" in _strip_ansi(
capsys.readouterr().out
opened = cli_webui_support._open_webui_browser(
"http://127.0.0.1:8765/",
wait=False,
)
assert opened is False
assert "Could not open a browser automatically." in _strip_ansi(capsys.readouterr().out)
def test_open_webui_browser_rejects_text_only_browser(monkeypatch, capsys) -> None:
monkeypatch.setattr(cli_webui_support, "_text_only_browser_name", lambda: "links")
monkeypatch.setattr(
cli_webui_support,
"_launch_browser",
lambda _value: pytest.fail("text-only browser must not be opened"),
)
opened = cli_webui_support._open_webui_browser(
"http://127.0.0.1:8765/",
wait=False,
)
output = re.sub(r"\s+", " ", _strip_ansi(capsys.readouterr().out))
assert opened is False
assert "links" in output
assert "does not support JavaScript" in output
def test_text_only_browser_name_detects_links(monkeypatch) -> None:
monkeypatch.setattr(cli_webui_support.sys, "platform", "linux")
monkeypatch.setattr(
cli_webui_support.webbrowser,
"get",
lambda: SimpleNamespace(name="links"),
)
assert cli_webui_support._text_only_browser_name() == "links"
@pytest.mark.parametrize(
("host", "tunnel_host"),
[
("127.0.0.1", "127.0.0.1"),
("0.0.0.0", "127.0.0.1"),
("::1", "[::1]"),
("::", "[::1]"),
("192.0.2.10", "192.0.2.10"),
],
)
def test_print_webui_manual_access_includes_password_source_and_ssh_tunnel(
capsys, host: str, tunnel_host: str,
) -> None:
config = Config(channels={"websocket": {
"host": host, "port": 8899, "tokenIssueSecret": "do-not-print",
}})
config_path = Path("/srv/nanobot/config.json")
cli_webui_support._print_webui_manual_access(
config,
config_path,
cli_webui_support._webui_browser_url(config),
)
output = re.sub(r"\s+", " ", _strip_ansi(capsys.readouterr().out))
assert f"WebUI: http://{tunnel_host}:8899" in output
assert "channels.websocket.tokenIssueSecret" in output
assert str(config_path) in output
assert f"ssh -N -L 8899:{tunnel_host}:8899 <user>@<server>" in output
assert "Then open http://127.0.0.1:8899 on your computer." in output
assert "do-not-print" not in output
def test_launch_browser_uses_macos_url_services(monkeypatch) -> None:
seen: list[str] = []
+18 -3
View File
@@ -382,9 +382,20 @@ function AuthForm({
className="flex w-full max-w-sm flex-col gap-4"
>
<div className="space-y-2">
<h1 className="text-sm font-medium text-foreground">
<label htmlFor="webui-access-password">{t("app.auth.label")}</label>
<h1 className="text-lg font-semibold text-foreground">
{t("app.auth.title")}
</h1>
<p id="webui-auth-help" className="text-sm text-muted-foreground">
{t("app.auth.help")}
</p>
</div>
<div className="space-y-2">
<label
htmlFor="webui-access-password"
className="text-sm font-medium text-foreground"
>
{t("app.auth.label")}
</label>
<div className="relative">
<Input
ref={inputRef}
@@ -399,7 +410,11 @@ function AuthForm({
}}
disabled={submitting}
aria-invalid={validationError ? true : undefined}
aria-describedby={validationError ? "webui-auth-error" : undefined}
aria-describedby={
validationError
? "webui-auth-help webui-auth-error"
: "webui-auth-help"
}
className="pr-10"
autoFocus
/>
+6 -4
View File
@@ -7,15 +7,17 @@
},
"error": {
"title": "Couldn't reach nanobot",
"gatewayHint": "Make sure the gateway is running (`nanobot gateway`) and that this page is open on the same machine."
"gatewayHint": "Make sure the gateway is running (`nanobot gateway`) and this browser can reach its WebUI address."
},
"auth": {
"label": "Password",
"title": "Connect to nanobot",
"label": "WebUI password",
"help": "Find this password at channels.websocket.tokenIssueSecret in the nanobot config, usually ~/.nanobot/config.json. If that value is empty, use channels.websocket.token.",
"showPassword": "Show password",
"hidePassword": "Hide password",
"submit": "Connect",
"required": "Enter your password.",
"invalid": "Incorrect password. Try again."
"required": "Enter the WebUI password.",
"invalid": "That WebUI password wasn't accepted. Copy it from the nanobot config and try again."
},
"account": {
"section": "Account",
+6 -4
View File
@@ -7,15 +7,17 @@
},
"error": {
"title": "No se pudo conectar con nanobot",
"gatewayHint": "Asegúrate de que la gateway esté en ejecución (`nanobot gateway`) y de que esta página esté abierta en la misma máquina."
"gatewayHint": "Asegúrate de que la gateway esté en ejecución (`nanobot gateway`) y de que este navegador pueda acceder a la dirección de la WebUI."
},
"auth": {
"label": "Contraseña",
"title": "Conectar con nanobot",
"label": "Contraseña de WebUI",
"help": "Busca esta contraseña en channels.websocket.tokenIssueSecret dentro de la configuración de nanobot, normalmente ~/.nanobot/config.json. Si ese valor está vacío, usa channels.websocket.token.",
"showPassword": "Mostrar contraseña",
"hidePassword": "Ocultar contraseña",
"submit": "Conectar",
"required": "Introduce la contraseña.",
"invalid": "Contraseña incorrecta. Inténtalo de nuevo."
"required": "Introduce la contraseña de WebUI.",
"invalid": "No se aceptó esa contraseña de WebUI. Cópiala de la configuración de nanobot e inténtalo de nuevo."
},
"account": {
"section": "Cuenta",
+6 -4
View File
@@ -7,15 +7,17 @@
},
"error": {
"title": "Impossible de joindre nanobot",
"gatewayHint": "Assurez-vous que la gateway est en cours d’exécution (`nanobot gateway`) et que cette page est ouverte sur la même machine."
"gatewayHint": "Assurez-vous que la gateway est en cours d’exécution (`nanobot gateway`) et que ce navigateur peut atteindre son adresse WebUI."
},
"auth": {
"label": "Mot de passe",
"title": "Se connecter à nanobot",
"label": "Mot de passe de la WebUI",
"help": "Ce mot de passe se trouve dans channels.websocket.tokenIssueSecret dans la configuration de nanobot, généralement ~/.nanobot/config.json. Si cette valeur est vide, utilisez channels.websocket.token.",
"showPassword": "Afficher le mot de passe",
"hidePassword": "Masquer le mot de passe",
"submit": "Se connecter",
"required": "Saisissez le mot de passe.",
"invalid": "Mot de passe incorrect. Réessayez."
"required": "Saisissez le mot de passe de la WebUI.",
"invalid": "Ce mot de passe de la WebUI n’a pas été accepté. Copiez-le depuis la configuration de nanobot et réessayez."
},
"account": {
"section": "Compte",
+6 -4
View File
@@ -7,15 +7,17 @@
},
"error": {
"title": "Tidak dapat menjangkau nanobot",
"gatewayHint": "Pastikan gateway sedang berjalan (`nanobot gateway`) dan halaman ini dibuka pada mesin yang sama."
"gatewayHint": "Pastikan gateway sedang berjalan (`nanobot gateway`) dan browser ini dapat menjangkau alamat WebUI-nya."
},
"auth": {
"label": "Kata sandi",
"title": "Hubungkan ke nanobot",
"label": "Kata sandi WebUI",
"help": "Temukan kata sandi ini di channels.websocket.tokenIssueSecret dalam konfigurasi nanobot, biasanya ~/.nanobot/config.json. Jika nilainya kosong, gunakan channels.websocket.token.",
"showPassword": "Tampilkan kata sandi",
"hidePassword": "Sembunyikan kata sandi",
"submit": "Hubungkan",
"required": "Masukkan kata sandi.",
"invalid": "Kata sandi salah. Coba lagi."
"required": "Masukkan kata sandi WebUI.",
"invalid": "Kata sandi WebUI tersebut tidak diterima. Salin dari konfigurasi nanobot lalu coba lagi."
},
"account": {
"section": "Akun",
+6 -4
View File
@@ -7,15 +7,17 @@
},
"error": {
"title": "nanobot に接続できませんでした",
"gatewayHint": "gateway(`nanobot gateway`)が起動しており、このページが同じマシン上で開かれていることを確認してください。"
"gatewayHint": "gateway(`nanobot gateway`)が起動しており、このブラウザーから WebUI のアドレスに到達できることを確認してください。"
},
"auth": {
"label": "パスワード",
"title": "nanobot に接続",
"label": "WebUI パスワード",
"help": "このパスワードは nanobot の設定内の channels.websocket.tokenIssueSecret にあります。通常は ~/.nanobot/config.json です。この値が空の場合は channels.websocket.token を使用してください。",
"showPassword": "パスワードを表示",
"hidePassword": "パスワードを隠す",
"submit": "接続",
"required": "パスワードを入力してください。",
"invalid": "パスワードが正しくありません。もう一度お試しください。"
"required": "WebUI パスワードを入力してください。",
"invalid": "その WebUI パスワードは受け付けられませんでした。nanobot の設定からコピーして、もう一度お試しください。"
},
"account": {
"section": "アカウント",
+6 -4
View File
@@ -7,15 +7,17 @@
},
"error": {
"title": "nanobot에 연결할 수 없습니다",
"gatewayHint": "gateway(`nanobot gateway`)가 실행 중인지, 그리고 이 페이지가 같은 머신에서 열려 있는지 확인하세요."
"gatewayHint": "gateway(`nanobot gateway`)가 실행 중이고 이 브라우저에서 WebUI 주소에 접근할 수 있는지 확인하세요."
},
"auth": {
"label": "비밀번호",
"title": "nanobot에 연결",
"label": "WebUI 비밀번호",
"help": "이 비밀번호는 nanobot 설정의 channels.websocket.tokenIssueSecret에 있으며, 일반적으로 ~/.nanobot/config.json에 저장됩니다. 이 값이 비어 있으면 channels.websocket.token을 사용하세요.",
"showPassword": "비밀번호 표시",
"hidePassword": "비밀번호 숨기기",
"submit": "연결",
"required": "비밀번호를 입력하세요.",
"invalid": "비밀번호가 올바르지 않습니다. 다시 시도하세요."
"required": "WebUI 비밀번호를 입력하세요.",
"invalid": "해당 WebUI 비밀번호가 허용되지 않았습니다. nanobot 설정에서 복사한 후 다시 시도하세요."
},
"account": {
"section": "계정",
+6 -4
View File
@@ -7,15 +7,17 @@
},
"error": {
"title": "Não foi possível conectar-se com o nanobot",
"gatewayHint": "Verifique se o gateway está em execução (`nanobot gateway`) e se esta página está aberta na mesma máquina."
"gatewayHint": "Verifique se o gateway está em execução (`nanobot gateway`) e se este navegador consegue acessar o endereço da WebUI."
},
"auth": {
"label": "Senha",
"title": "Conectar ao nanobot",
"label": "Senha da WebUI",
"help": "Encontre esta senha em channels.websocket.tokenIssueSecret na configuração do nanobot, normalmente em ~/.nanobot/config.json. Se esse valor estiver vazio, use channels.websocket.token.",
"showPassword": "Mostrar senha",
"hidePassword": "Ocultar senha",
"submit": "Conectar",
"required": "Digite a senha.",
"invalid": "Senha incorreta. Tente novamente."
"required": "Digite a senha da WebUI.",
"invalid": "Essa senha da WebUI não foi aceita. Copie-a da configuração do nanobot e tente novamente."
},
"account": {
"section": "Conta",
+6 -4
View File
@@ -7,15 +7,17 @@
},
"error": {
"title": "Không thể kết nối tới nanobot",
"gatewayHint": "Hãy chắc chắn gateway đang chạy (`nanobot gateway`) và trang này được mở trên cùng máy."
"gatewayHint": "Hãy chắc chắn gateway đang chạy (`nanobot gateway`) và trình duyệt này có thể truy cập địa chỉ WebUI của gateway."
},
"auth": {
"label": "Mật khẩu",
"title": "Kết nối với nanobot",
"label": "Mật khẩu WebUI",
"help": "Tìm mật khẩu này tại channels.websocket.tokenIssueSecret trong cấu hình nanobot, thường là ~/.nanobot/config.json. Nếu giá trị này trống, hãy dùng channels.websocket.token.",
"showPassword": "Hiện mật khẩu",
"hidePassword": "Ẩn mật khẩu",
"submit": "Kết nối",
"required": "Nhập mật khẩu.",
"invalid": "Mật khẩu không đúng. Hãy thử lại."
"required": "Nhập mật khẩu WebUI.",
"invalid": "Mật khẩu WebUI đó không được chấp nhận. Hãy sao chép từ cấu hình nanobot rồi thử lại."
},
"account": {
"section": "Tài khoản",
+6 -4
View File
@@ -7,15 +7,17 @@
},
"error": {
"title": "无法连接到 nanobot",
"gatewayHint": "请确认网关已启动(`nanobot gateway`),并且当前页面与网关运行在同一台机器上。"
"gatewayHint": "请确认网关已启动(`nanobot gateway`),并且当前浏览器可以访问它的 WebUI 地址。"
},
"auth": {
"label": "密码",
"title": "连接到 nanobot",
"label": "WebUI 密码",
"help": "请在 nanobot 配置中的 channels.websocket.tokenIssueSecret 查找此密码,配置文件通常位于 ~/.nanobot/config.json。若该值为空,请使用 channels.websocket.token。",
"showPassword": "显示密码",
"hidePassword": "隐藏密码",
"submit": "连接",
"required": "请输入密码。",
"invalid": "密码错误,请重试。"
"required": "请输入 WebUI 密码。",
"invalid": "该 WebUI 密码未通过验证。请从 nanobot 配置中复制密码后重试。"
},
"account": {
"section": "账户",
+6 -4
View File
@@ -7,15 +7,17 @@
},
"error": {
"title": "無法連線到 nanobot",
"gatewayHint": "請確認閘道已啟動(`nanobot gateway`),並且目前頁面與閘道在同一台機器上開啟。"
"gatewayHint": "請確認閘道已啟動(`nanobot gateway`),並且目前瀏覽器可以存取它的 WebUI 位址。"
},
"auth": {
"label": "密碼",
"title": "連線到 nanobot",
"label": "WebUI 密碼",
"help": "請在 nanobot 設定中的 channels.websocket.tokenIssueSecret 尋找此密碼,設定檔通常位於 ~/.nanobot/config.json。若該值為空,請使用 channels.websocket.token。",
"showPassword": "顯示密碼",
"hidePassword": "隱藏密碼",
"submit": "連線",
"required": "請輸入密碼。",
"invalid": "密碼錯誤,請再試一次。"
"required": "請輸入 WebUI 密碼。",
"invalid": "該 WebUI 密碼未通過驗證。請從 nanobot 設定中複製密碼後再試一次。"
},
"account": {
"section": "帳戶",
+20 -12
View File
@@ -349,9 +349,14 @@ describe("App layout", () => {
render(<App />);
expect(await screen.findByRole("heading", { level: 1, name: "Password" }))
expect(await screen.findByRole("heading", { level: 1, name: "Connect to nanobot" }))
.toBeInTheDocument();
const password = screen.getByLabelText("Password");
const password = screen.getByLabelText("WebUI password");
expect(screen.getByText(/channels\.websocket\.tokenIssueSecret/))
.toBeInTheDocument();
expect(password).toHaveAccessibleDescription(
/If that value is empty, use channels\.websocket\.token\./,
);
expect(password).toHaveAttribute(
"autocomplete",
"current-password",
@@ -359,7 +364,7 @@ describe("App layout", () => {
expect(password).not.toHaveAttribute("placeholder");
expect(screen.queryByText("Authentication required")).not.toBeInTheDocument();
expect(
screen.queryByText("Incorrect password. Try again."),
screen.queryByText(/WebUI password wasn't accepted/),
).not.toBeInTheDocument();
expect(connectSpy).not.toHaveBeenCalled();
});
@@ -372,7 +377,7 @@ describe("App layout", () => {
render(<App />);
const password = await screen.findByLabelText("Password");
const password = await screen.findByLabelText("WebUI password");
await user.type(password, "correct horse battery staple");
expect(password).toHaveAttribute("type", "password");
@@ -397,16 +402,19 @@ describe("App layout", () => {
render(<App />);
const password = await screen.findByLabelText("Password");
const password = await screen.findByLabelText("WebUI password");
const connect = screen.getByRole("button", { name: "Connect" });
expect(connect).toBeEnabled();
fireEvent.click(connect);
expect(await screen.findByRole("alert")).toHaveTextContent(
"Enter your password.",
"Enter the WebUI password.",
);
expect(password).toHaveAttribute("aria-invalid", "true");
expect(password).toHaveAttribute("aria-describedby", "webui-auth-error");
expect(password).toHaveAttribute(
"aria-describedby",
"webui-auth-help webui-auth-error",
);
expect(password).toHaveFocus();
expect(fetchBootstrap).toHaveBeenCalledTimes(1);
});
@@ -420,10 +428,10 @@ describe("App layout", () => {
render(<App />);
expect(await screen.findByRole("heading", { level: 1, name: "Password" }))
expect(await screen.findByRole("heading", { level: 1, name: "Connect to nanobot" }))
.toBeInTheDocument();
expect(
screen.queryByText("Incorrect password. Try again."),
screen.queryByText(/WebUI password wasn't accepted/),
).not.toBeInTheDocument();
expect(connectSpy).not.toHaveBeenCalled();
});
@@ -435,13 +443,13 @@ describe("App layout", () => {
render(<App />);
const password = await screen.findByLabelText("Password");
const password = await screen.findByLabelText("WebUI password");
fireEvent.change(password, { target: { value: "wrong-password" } });
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
const retryPassword = await screen.findByLabelText("Password");
const retryPassword = await screen.findByLabelText("WebUI password");
expect(await screen.findByRole("alert")).toHaveTextContent(
"Incorrect password. Try again.",
"That WebUI password wasn't accepted. Copy it from the nanobot config and try again.",
);
expect(retryPassword).toHaveAttribute("aria-invalid", "true");
expect(retryPassword).toHaveFocus();