feat(webui): improve setup flows across chat channels (NAN-112) (#5356)

* feat(webui): improve channel setup flows

* fix(webui): refine channel setup interactions (NAN-112)

* fix(webui): keep email setup sections channel-owned

* fix(webui): remove concrete channel details from shared components

* refactor(webui): remove unused channel setup resources

* fix(webui): finish channel-owned setup boundaries

* fix(webui): update channel switches optimistically

* test(channels): remove obsolete absence assertions

* fix(webui): flatten channel instance settings disclosure

* fix(webui): complete channel setup and connection flows

* fix(whatsapp): wait for session database release

* fix(webui): preserve scrolling channel controls

* fix(webui): stage channel connection checks

* fix(channels): align verification actions

* fix(email): expose connection checks

* fix(webui): align channel field actions

* fix(email): verify account credentials

* fix(wecom): bypass system proxy for websocket

* fix(channels): stabilize async connection cleanup

* fix(webui): autosave channel credentials

* fix(email): make provider presets non-destructive

* test(weixin): isolate persisted QR credentials
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-11 15:22:14 +08:00
1 parent 3cc3012b3a
commit e8a29a0087
291 files changed
+12194 -3979

No files matched your search

+3
View File
@@ -572,4 +572,7 @@ def test_channel_setup_contract_owns_fields_and_validation() -> None:
"choices": [],
"required": True,
}],
"requirements": [
{"alternatives": [["channels.setup_contract.token"]]},
],
}
+63 -49
View File
@@ -292,7 +292,7 @@ def test_special_setup_validation_is_owned_by_channel_package(name: str):
assert plugin.setup.validator.__module__ == f"nanobot.channels.{name}.validation"
@pytest.mark.parametrize("name", ["feishu", "weixin"])
@pytest.mark.parametrize("name", ["feishu", "weixin", "whatsapp"])
def test_interactive_connector_is_owned_by_channel_package(name: str):
plugin = load_channel_package(name)
@@ -582,6 +582,9 @@ def test_plugin_setup_contract_drives_feature_payload(monkeypatch: pytest.Monkey
"required": False,
},
],
"requirements": [
{"alternatives": [["channels.setupplugin.token"]]},
],
"official_url": "https://plugin.example/setup",
}
assert feature["configured_fields"] == [
@@ -630,10 +633,11 @@ def test_plugin_contract_error_is_isolated_in_feature_payload(monkeypatch):
"type": "channel",
"capabilities": [],
"settings_visible": True,
"setup": {"fields": []},
"setup": {"fields": [], "requirements": []},
"enabled": False,
"configured": False,
"installed": True,
"requires_dependencies": False,
"ready": False,
"status": "invalid_config",
"install_supported": True,
@@ -842,10 +846,7 @@ def test_discover_plugins_excludes_internal_helpers():
names = discover_plugins()
assert "_feishu_ws" not in names
assert "_setup" not in names
assert "setup" not in names
assert "_feishu_instances" not in names
def test_discover_enabled_imports_only_enabled_packages():
@@ -1880,6 +1881,47 @@ def test_enable_optional_feature_reports_install_failure(monkeypatch, tmp_path):
assert not config_path.exists()
def test_install_only_adds_channel_support_without_enabling_it(monkeypatch, tmp_path):
from nanobot.optional_features import InstallResult
from nanobot.webui.nanobot_features_api import nanobot_features_action
config_path = tmp_path / "config.json"
config_path.write_text(
json.dumps({"channels": {"fakeplugin": {"enabled": False, "marker": "keep"}}}),
encoding="utf-8",
)
before = config_path.read_bytes()
_stub_channel_registry(
monkeypatch,
_channel_plugin(_FakePlugin, dependencies=("fake-sdk>=1",)),
)
monkeypatch.setattr("nanobot.optional_features.optional_dependency_groups", lambda: {})
installed = False
def extra_installed(_name: str, _dependencies: list[str] | None) -> bool:
return installed
def install_extra(name: str, dependencies: list[str], *, runner) -> InstallResult:
nonlocal installed
installed = True
return InstallResult(True, f"{name} support", ["pip", *dependencies])
monkeypatch.setattr("nanobot.optional_features.extra_installed", extra_installed)
monkeypatch.setattr("nanobot.optional_features.install_extra", install_extra)
payload = nanobot_features_action(
"enable",
{"name": ["fakeplugin"], "install_only": ["true"]},
config_path=config_path,
)
feature = payload["features"][0]
assert config_path.read_bytes() == before
assert feature["installed"] is True
assert feature["enabled"] is False
assert payload["requires_restart"] is True
def test_disable_optional_feature_rejects_unknown_features_and_non_channels(
monkeypatch,
tmp_path,
@@ -2022,6 +2064,7 @@ def test_optional_features_payload_counts_enabled_channel_with_missing_dependenc
assert matrix["name"] == "matrix"
assert matrix["enabled"] is True
assert matrix["installed"] is False
assert matrix["requires_dependencies"] is True
assert matrix["ready"] is False
assert payload["enabled_count"] == 1
@@ -2303,50 +2346,21 @@ def test_optional_features_payload_lists_feishu_instances(monkeypatch):
assert feishu["enabled"] is True
assert feishu["configured"] is True
assert payload["enabled_count"] == 1
assert feishu["instances"] == [
{
"id": "default",
"name": "nanobot",
"display_name": "Voraflare Bot",
"avatar_url": "https://example.com/bot.png",
"enabled": True,
"configured": True,
"config_values": {
"channels.feishu.appId": "cli_default",
"channels.feishu.domain": "feishu",
"channels.feishu.groupPolicy": "mention",
"channels.feishu.topicIsolation": "true",
},
"configured_fields": [
"channels.feishu.appId",
"channels.feishu.appSecret",
"channels.feishu.domain",
"channels.feishu.groupPolicy",
"channels.feishu.topicIsolation",
],
},
{
"id": "product",
"name": "Product bot",
"display_name": "Product bot",
"avatar_url": "",
"enabled": False,
"configured": True,
"config_values": {
"channels.feishu.appId": "cli_product",
"channels.feishu.domain": "feishu",
"channels.feishu.groupPolicy": "mention",
"channels.feishu.topicIsolation": "true",
},
"configured_fields": [
"channels.feishu.appId",
"channels.feishu.appSecret",
"channels.feishu.domain",
"channels.feishu.groupPolicy",
"channels.feishu.topicIsolation",
],
},
instances = feishu["instances"]
assert [
(item["id"], item["name"], item["display_name"], item["avatar_url"], item["enabled"])
for item in instances
] == [
("default", "nanobot", "Voraflare Bot", "https://example.com/bot.png", True),
("product", "Product bot", "Product bot", "", False),
]
assert [item["configured"] for item in instances] == [True, True]
assert instances[0]["config_values"]["channels.feishu.appId"] == "cli_default"
assert instances[1]["config_values"]["channels.feishu.appId"] == "cli_product"
assert all(
"channels.feishu.appSecret" in item["configured_fields"]
for item in instances
)
def test_optional_features_payload_does_not_refresh_saved_feishu_identity(monkeypatch, tmp_path):
@@ -2699,7 +2713,7 @@ def test_optional_dependency_metadata_for_enable():
"wecom": ("wecom-aibot-sdk-python>=0.1.7,<0.2.0",),
"weixin": ("qrcode[pil]>=8.0", "pycryptodome>=3.20.0"),
"whatsapp": (
"neonize>=0.3.18.post0,<0.4.0",
"neonize>=0.4.3.post0,<0.5.0",
"segno>=1.6.1,<2.0.0",
),
}
+106 -6
View File
@@ -33,17 +33,58 @@ EXPECTED_CHANNELS = {
"whatsapp",
}
INTERNAL_CHANNEL_FIELDS = {
"feishu": {"instanceId", "identityKey"},
"signal": {"allowFrom"},
"weixin": {"token"},
"whatsapp": {"databasePath", "lidMappings"},
# nanobot WebUI owns this transport and intentionally has no channel dialog.
"websocket": {
"allowFrom",
"host",
"maxMessageBytes",
"path",
"pingIntervalS",
"pingTimeoutS",
"port",
"publicWsUrl",
"sslCertfile",
"sslKeyfile",
"streaming",
"token",
"tokenIssuePath",
"tokenIssueSecret",
"tokenTtlS",
"trustedProxyAuth",
"unixSocketPath",
"websocketRequiresToken",
},
}
def _flatten_channel_fields(value: object, prefix: str = "") -> set[str]:
if not isinstance(value, dict):
return {prefix} if prefix else set()
if not value:
return {prefix} if prefix else set()
fields: set[str] = set()
for key, nested in value.items():
path = f"{prefix}.{key}" if prefix else key
fields.update(_flatten_channel_fields(nested, path))
return fields
def test_channel_setup_spec_derives_route_and_secret_metadata() -> None:
slack = channel_setup_spec("slack")
assert slack is not None
assert slack.secrets == {"appToken", "botToken"}
assert slack.route_field_types == {
"appToken": "secret",
"botToken": "secret",
"groupPolicy": ("enum", {"mention", "open", "allowlist"}),
}
assert slack.route_field_types["appToken"] == "secret"
assert slack.route_field_types["botToken"] == "secret"
assert slack.route_field_types["groupPolicy"] == (
"enum",
{"mention", "open", "allowlist"},
)
assert slack.simple_required_fields == ("appToken", "botToken")
assert slack.fields["groupPolicy"].default == "mention"
group_policy = next(
@@ -73,7 +114,7 @@ def test_channel_setup_spec_separates_writable_and_snapshot_fields() -> None:
assert matrix is not None
assert discord is not None
assert "allowFrom" not in matrix.route_field_types
assert "allowFrom" in matrix.route_field_types
assert "allowFrom" in matrix.snapshot_fields
assert "allowFrom" in discord.route_field_types
assert "allowFrom" not in discord.snapshot_fields
@@ -87,6 +128,7 @@ def test_webui_forms_have_writable_mattermost_and_whatsapp_contracts() -> None:
assert whatsapp is not None
assert mattermost.route_field_types["serverUrl"] == "string"
assert mattermost.route_field_types["token"] == "secret"
assert whatsapp.route_field_types["proxy"] == "string"
assert whatsapp.route_field_types["allowFrom"] == "list"
assert whatsapp.route_field_types["groupPolicy"] == (
"enum",
@@ -94,6 +136,19 @@ def test_webui_forms_have_writable_mattermost_and_whatsapp_contracts() -> None:
)
def test_weixin_token_is_managed_only_by_qr_login() -> None:
weixin = channel_setup_spec("weixin")
assert weixin is not None
assert weixin.simple_required_fields == ("token",)
assert "token" not in weixin.route_field_types
assert "token" not in weixin.snapshot_fields
assert all(
field["field"] != "token"
for field in weixin.to_public_dict("weixin")["fields"]
)
def test_every_channel_is_a_self_contained_package() -> None:
channel_dir = Path(channel_setup_module.__file__).parent
package_names = {path.parent.name for path in channel_dir.glob("*/manifest.py")}
@@ -127,6 +182,13 @@ def test_channel_locales_cover_authoritative_setup_contracts() -> None:
)
setup_messages = english["setup"]
field_messages = setup_messages.get("fields", {})
contract_message_keys = {
re.sub(r"[^A-Za-z0-9_-]+", "_", field_name)
for field_name in plugin.setup.fields
}
assert not set(field_messages) - contract_message_keys, (
f"{name} has locale copy for fields outside its setup contract"
)
for field_name, field in plugin.setup.fields.items():
if not field.writable:
continue
@@ -136,6 +198,26 @@ def test_channel_locales_cover_authoritative_setup_contracts() -> None:
assert setup_messages.get("officialLabel"), f"{name} has no localized official label"
def test_every_runtime_channel_field_has_a_webui_contract() -> None:
for name, plugin in discover_plugins().items():
runtime_fields = _flatten_channel_fields(plugin.load_channel_class().default_config())
runtime_fields.discard("enabled")
setup = plugin.setup
assert setup is not None
contract_fields = set(setup.fields)
internal_fields = INTERNAL_CHANNEL_FIELDS.get(name, set())
assert not runtime_fields - contract_fields - internal_fields, (
f"{name} runtime fields missing from WebUI contract: "
f"{sorted(runtime_fields - contract_fields - internal_fields)}"
)
assert not {
field_name
for field_name in runtime_fields - internal_fields
if field_name not in setup.route_field_types
}, f"{name} has user-configurable runtime fields that WebUI cannot save"
def test_channel_manifests_only_import_contract_modules() -> None:
channel_dir = Path(channel_setup_module.__file__).parent
allowed_imports = {
@@ -184,6 +266,24 @@ def test_weixin_package_manifest_owns_runtime_and_webui_metadata() -> None:
assert plugin.webui == "webui/index.tsx"
def test_whatsapp_package_manifest_owns_browser_connector() -> None:
plugin = load_channel_package("whatsapp")
assert plugin is not None
assert plugin.connector == "nanobot.channels.whatsapp.connect:WhatsAppConnectStore"
assert plugin.webui == "webui/index.tsx"
def test_mochat_package_manifest_exposes_required_setup() -> None:
plugin = load_channel_package("mochat")
assert plugin is not None
assert plugin.webui == "webui/index.ts"
assert plugin.settings_visible is True
assert plugin.setup is not None
assert plugin.setup.simple_required_fields == ("clawToken",)
def test_package_manifests_do_not_import_runtimes() -> None:
code = f"""
import sys
+2
View File
@@ -64,6 +64,8 @@ class TestFormatPairingReply:
assert "nanobot WebUI" in reply
assert "ABCD-EFGH" in reply
assert "/pairing approve ABCD-EFGH" in reply
assert "private nanobot" in reply
assert "approved users" not in reply
class TestApproveDeny:
+18
View File
@@ -59,6 +59,24 @@ def _mutation_request(path: str, payload: dict[str, object]) -> SimpleNamespace:
return request
@pytest.mark.asyncio
async def test_close_releases_channel_connectors() -> None:
router = _router()
closed = False
class Connector:
async def close(self) -> None:
nonlocal closed
closed = True
router._system._channel_connectors["whatsapp"] = Connector()
await router.close()
assert closed is True
assert router._system._channel_connectors == {}
@pytest.mark.asyncio
async def test_mcp_list_serializes_local_runtime_failure_snapshot(tmp_path) -> None:
config_path = tmp_path / "config.json"
+23
View File
@@ -1,8 +1,10 @@
from __future__ import annotations
from nanobot.channels.registry import load_channel_plugin
from nanobot.config.schema import Config
from nanobot.webui.settings_system import (
coerce_channel_value,
save_channel_config_values,
system_settings_payload,
update_agent_system_settings,
)
@@ -42,3 +44,24 @@ def test_system_domain_validates_channel_field_values() -> None:
]
assert coerce_channel_value("enabled", "yes", "bool") is True
assert coerce_channel_value("port", "8765", "int") == 8765
assert coerce_channel_value("delay", "0.6", "float") == 0.6
assert coerce_channel_value("overrides", '{"123": "open"}', "json") == {
"123": "open"
}
assert coerce_channel_value("token", None, "secret") == ""
def test_channel_secret_is_cleared_only_by_explicit_null() -> None:
config = Config.model_validate({
"channels": {"matrix": {"password": "saved-password"}},
})
saved = save_channel_config_values(
config,
"matrix",
{"channels.matrix.password": None},
load_channel_plugin=load_channel_plugin,
)
assert saved == ["channels.matrix.password"]
assert config.channels.matrix["password"] == ""